Repository navigation
Expand file tree
/
Copy pathservice.ts
More file actions
82 lines (75 loc) · 2.21 KB
/
Copy pathservice.ts
File metadata and controls
82 lines (75 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import {
MINUTE,
bucketStart,
chooseInterval,
queryPreviousSummary,
queryBreakdown,
querySummary,
queryTimeseries,
type BreakdownOptions,
type BreakdownResponse,
type Dimension,
type Granularity,
type RealtimeResponse,
type RollupRepository,
type SummaryResponse,
type TimeseriesResponse,
} from '@pulse/core';
import type { SiteRegistry } from '../db/sites-repo.js';
import type { IngestPipeline } from '../ingest/pipeline.js';
export interface Range {
from: number;
to: number;
}
/** Read path shared by the REST API and the CSV export. */
export class StatsService {
constructor(
private readonly repo: RollupRepository,
private readonly sites: SiteRegistry,
private readonly pipeline: IngestPipeline,
private readonly now: () => number = Date.now,
) {}
private query(siteId: string, range: Range, interval?: Granularity) {
this.pipeline.flush();
return {
siteId,
from: range.from,
to: range.to,
timeZone: this.sites.timeZone(siteId),
now: this.now(),
...(interval ? { interval } : {}),
};
}
summary(siteId: string, range: Range): SummaryResponse {
const q = this.query(siteId, range);
return {
interval: chooseInterval(q.from, q.to, this.repo.retention, q.now),
current: querySummary(this.repo, q),
previous: queryPreviousSummary(this.repo, q),
};
}
timeseries(siteId: string, range: Range, interval?: Granularity): TimeseriesResponse {
return queryTimeseries(this.repo, this.query(siteId, range, interval));
}
breakdown(
siteId: string,
range: Range,
dimension: Dimension,
opts: BreakdownOptions,
): BreakdownResponse {
return queryBreakdown(this.repo, this.query(siteId, range), dimension, opts);
}
realtime(siteId: string): RealtimeResponse {
const now = this.now();
const to = bucketStart(now, 'minute') + MINUTE;
const ts = queryTimeseries(
this.repo,
this.query(siteId, { from: to - 30 * MINUTE, to }, 'minute'),
);
return {
active: this.pipeline.activeVisitors(siteId),
perMinute: ts.points.map((p) => ({ t: p.t, pageviews: p.pageviews, visitors: p.visitors })),
recent: this.pipeline.recentEvents(siteId),
};
}
}