@obzerver/server 0.11.4 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,207 @@
1
+ import type { IngestPayload } from '@obzerver/node/protocol';
2
+ import { type Db } from './db.js';
3
+ export type PlanId = 'self-hosted' | 'free' | 'pro' | 'scale' | 'enterprise';
4
+ export type Feature = 'logs' | 'alerts' | 'slos';
5
+ export declare const FEATURES: Feature[];
6
+ export interface Plan {
7
+ id: PlanId;
8
+ name: string;
9
+ /** Included events per month; null = no allowance (self-hosted). */
10
+ included: number | null;
11
+ /** Raw-data retention in days; null = the server's OBZERVER_RETENTION_DAYS. */
12
+ retentionDays: number | null;
13
+ features: Record<Feature, boolean>;
14
+ /** What happens past the allowance: Free reduces detail in stages, paid plans allow overage. */
15
+ overage: 'none' | 'reduce' | 'billed';
16
+ /** Spike protection default: on, on for the first month on the plan, or off. */
17
+ spikeDefault: 'on' | 'first-month' | 'off';
18
+ }
19
+ export declare const PLANS: Record<PlanId, Plan>;
20
+ export declare const PLAN_IDS: PlanId[];
21
+ export declare const isPlanId: (v: unknown) => v is PlanId;
22
+ /** Free: after this many events in one UTC day, most trace waterfalls pause until 00:00 UTC. */
23
+ export declare const FREE_DAILY_PACE = 30000;
24
+ /** Free: at this multiple of the allowance, new telemetry is refused (429) until next month. */
25
+ export declare const FREE_REFUSE_AT = 2;
26
+ /** On plans with retention past this, the span tree of a fast, successful execution is dropped after it. */
27
+ export declare const SPAN_TREE_DAYS = 7;
28
+ /** Executions slower than this keep full traces when detail is reduced or overage is paused. */
29
+ export declare const SLOW_MS = 1000;
30
+ export declare const MAX_THRESHOLDS = 5;
31
+ export interface UsageSettings {
32
+ plan: PlanId;
33
+ /** When the current plan was chosen (Scale's spike protection defaults on for its first month). */
34
+ planSince: number;
35
+ /** Enterprise: negotiated allowance and retention. */
36
+ enterprise: {
37
+ included: number;
38
+ retentionDays: number;
39
+ };
40
+ /** Monthly overage budget in events beyond the allowance; null = none, 0 = collect nothing beyond. */
41
+ budget: number | null;
42
+ /** null = the plan's default. */
43
+ spikeProtection: boolean | null;
44
+ /** Up to five quota-notification thresholds, in % of the allowance. */
45
+ thresholds: number[];
46
+ /** Who gets the quota emails (comma-separated). */
47
+ notify: string;
48
+ /** Optional price per million overage events (USD), to show cost and size spike protection like NestJS's $50 rule. */
49
+ overageRate: number | null;
50
+ }
51
+ export declare const DEFAULT_SETTINGS: UsageSettings;
52
+ export type UsageState = 'unlimited' | 'ok' | 'paced' | 'reduced' | 'refused' | 'overage' | 'paused';
53
+ export interface EventCounts {
54
+ requests: number;
55
+ jobs: number;
56
+ errors: number;
57
+ logs: number;
58
+ spans: number;
59
+ }
60
+ export declare const total: (c: EventCounts) => number;
61
+ export declare const dayKey: (t: number) => string;
62
+ export declare const monthKey: (t: number) => string;
63
+ export declare function monthStart(t: number): number;
64
+ export declare function nextMonth(t: number): number;
65
+ declare const nextDay: (t: number) => number;
66
+ /** The events in an SDK batch, the way they are metered. */
67
+ export declare function countEvents(p: IngestPayload): EventCounts;
68
+ export type Admit = {
69
+ refuse: true;
70
+ seconds: number;
71
+ error: string;
72
+ } | {
73
+ refuse: false;
74
+ payload: IngestPayload;
75
+ billed: EventCounts;
76
+ unbilled: EventCounts;
77
+ dropped: number;
78
+ state: UsageState;
79
+ };
80
+ export interface MeterOptions {
81
+ /** Every project's database, for month totals and the per-project breakdown. */
82
+ projects: () => {
83
+ slug: string;
84
+ name: string;
85
+ db: Db;
86
+ }[];
87
+ /** Plan for a server that has none stored yet (OBZERVER_PLAN). */
88
+ defaultPlan?: string | null;
89
+ log?: (m: string) => void;
90
+ /** Sends a quota email; rejects when email isn't set up. */
91
+ email?: (to: string, subject: string, text: string) => Promise<void>;
92
+ }
93
+ export declare class UsageMeter {
94
+ private root;
95
+ private opts;
96
+ private cache;
97
+ /** Billed events per minute over the last hour, for spike protection's "current pace". */
98
+ private minutes;
99
+ constructor(root: Db, opts: MeterOptions);
100
+ settings(): UsageSettings;
101
+ /** Validates and stores a settings change; returns the new settings or throws an Error with a message for the user. */
102
+ save(patch: Partial<UsageSettings>, now?: number): UsageSettings;
103
+ plan(): Plan;
104
+ feature(f: Feature): boolean;
105
+ /** Raw-data retention for the plan, or the server's own setting on Self-hosted. */
106
+ retentionDays(serverDays: number): number;
107
+ spikeProtectionOn(now?: number): boolean;
108
+ private period;
109
+ private savePeriod;
110
+ /** Forget the cached month totals (after a project is removed). */
111
+ invalidate(): void;
112
+ private totals;
113
+ /** Where this month stands, and why. */
114
+ state(now?: number): {
115
+ state: UsageState;
116
+ reason: string | null;
117
+ };
118
+ /** Spike protection: pause overage when the current pace would push this month's overage past the limit. */
119
+ private spikeLimit;
120
+ private pacePerMs;
121
+ projectedOverage(now?: number): number;
122
+ /** Decide what of a batch is kept, before it is stored. */
123
+ admit(payload: IngestPayload, now?: number): Admit;
124
+ /** Add a stored batch to the project's usage, then send any quota notifications it crossed. */
125
+ record(db: Db, service: string, env: string | null, a: Extract<Admit, {
126
+ refuse: false;
127
+ }>, now?: number): void;
128
+ private checkThresholds;
129
+ private afterAllowance;
130
+ private mail;
131
+ pause(now?: number): void;
132
+ resume(now?: number): void;
133
+ /** The short form for /api/meta: plan, features and the month's state. */
134
+ summary(now?: number): {
135
+ plan: PlanId;
136
+ name: string;
137
+ features: Record<Feature, boolean>;
138
+ included: number | null;
139
+ used: number;
140
+ pct: number | null;
141
+ state: UsageState;
142
+ reason: string | null;
143
+ };
144
+ /** Everything the Usage page shows. */
145
+ report(now?: number): {
146
+ plan: Plan;
147
+ plans: Plan[];
148
+ settings: UsageSettings;
149
+ month: string;
150
+ resetsAt: number;
151
+ used: number;
152
+ included: number | null;
153
+ pct: number | null;
154
+ today: number;
155
+ projected: number;
156
+ overage: number;
157
+ unbilled: number;
158
+ dropped: number;
159
+ kinds: EventCounts;
160
+ state: UsageState;
161
+ reason: string | null;
162
+ spikeProtection: {
163
+ on: boolean;
164
+ limit: number | null;
165
+ tripped: number | null;
166
+ resumed: boolean;
167
+ };
168
+ pausedAt: number | null;
169
+ notified: {
170
+ pct: number;
171
+ ts: number;
172
+ used: number;
173
+ }[];
174
+ limits: {
175
+ dailyPace: number | null;
176
+ refuseAt: number | null;
177
+ spanTreeDays: number | null;
178
+ };
179
+ daily: {
180
+ day: string;
181
+ events: number;
182
+ unbilled: number;
183
+ dropped: number;
184
+ }[];
185
+ byProject: {
186
+ slug: string;
187
+ name: string;
188
+ billed: number;
189
+ unbilled: number;
190
+ dropped: number;
191
+ apps: {
192
+ service: string;
193
+ env: string | null;
194
+ billed: number;
195
+ requests: number;
196
+ jobs: number;
197
+ errors: number;
198
+ logs: number;
199
+ spans: number;
200
+ }[];
201
+ }[];
202
+ };
203
+ }
204
+ /** Plans with retention past 7 days drop the span tree of fast, successful executions after 7 days. */
205
+ export declare function pruneSpanTrees(db: Db, now?: number): number;
206
+ export declare const fmt: (n: number) => string;
207
+ export { nextDay };
package/dist/usage.js ADDED
@@ -0,0 +1,436 @@
1
+ // Usage metering in Observability Events (OEs), the same model as NestJS Observe:
2
+ // one event per request, background job run, error, log entry or trace span an app reports.
3
+ // Events add up: a request that ran through three of your own methods, wrote two log lines and raised
4
+ // one error is seven events. Database-query and outbound-HTTP spans don't count (they are detail about
5
+ // a method span that already counts), and neither do runtime samples or custom metrics.
6
+ //
7
+ // A plan sets the monthly allowance, the retention window and which features are on. The default plan
8
+ // is "Self-hosted": no allowance, your own retention, everything on.
9
+ import { getSetting, setSetting } from './db.js';
10
+ export const FEATURES = ['logs', 'alerts', 'slos'];
11
+ const ALL_ON = { logs: true, alerts: true, slos: true };
12
+ export const PLANS = {
13
+ 'self-hosted': { id: 'self-hosted', name: 'Self-hosted', included: null, retentionDays: null, features: ALL_ON, overage: 'none', spikeDefault: 'off' },
14
+ free: { id: 'free', name: 'Free', included: 300_000, retentionDays: 3, features: { logs: false, alerts: false, slos: false }, overage: 'reduce', spikeDefault: 'off' },
15
+ pro: { id: 'pro', name: 'Pro', included: 25_000_000, retentionDays: 30, features: { logs: true, alerts: true, slos: false }, overage: 'billed', spikeDefault: 'on' },
16
+ scale: { id: 'scale', name: 'Scale', included: 200_000_000, retentionDays: 90, features: ALL_ON, overage: 'billed', spikeDefault: 'first-month' },
17
+ enterprise: { id: 'enterprise', name: 'Enterprise', included: 1_000_000_000, retentionDays: 365, features: ALL_ON, overage: 'billed', spikeDefault: 'off' },
18
+ };
19
+ export const PLAN_IDS = Object.keys(PLANS);
20
+ export const isPlanId = (v) => typeof v === 'string' && v in PLANS;
21
+ /** Free: after this many events in one UTC day, most trace waterfalls pause until 00:00 UTC. */
22
+ export const FREE_DAILY_PACE = 30_000;
23
+ /** Free: at this multiple of the allowance, new telemetry is refused (429) until next month. */
24
+ export const FREE_REFUSE_AT = 2;
25
+ /** On plans with retention past this, the span tree of a fast, successful execution is dropped after it. */
26
+ export const SPAN_TREE_DAYS = 7;
27
+ /** Executions slower than this keep full traces when detail is reduced or overage is paused. */
28
+ export const SLOW_MS = 1000;
29
+ export const MAX_THRESHOLDS = 5;
30
+ export const DEFAULT_SETTINGS = {
31
+ plan: 'self-hosted', planSince: 0, enterprise: { included: 1_000_000_000, retentionDays: 365 },
32
+ budget: null, spikeProtection: null, thresholds: [50, 80, 100], notify: '', overageRate: null,
33
+ };
34
+ export const total = (c) => c.requests + c.jobs + c.errors + c.logs + c.spans;
35
+ const zero = () => ({ requests: 0, jobs: 0, errors: 0, logs: 0, spans: 0 });
36
+ const DAY = 86400000;
37
+ export const dayKey = (t) => new Date(t).toISOString().slice(0, 10);
38
+ export const monthKey = (t) => new Date(t).toISOString().slice(0, 7);
39
+ export function monthStart(t) { const d = new Date(t); return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1); }
40
+ export function nextMonth(t) { const d = new Date(t); return Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1); }
41
+ const nextDay = (t) => Math.floor(t / DAY) * DAY + DAY;
42
+ // ---------------------------------------------------------------- what counts
43
+ const validTrace = (t) => !!t && typeof t.traceId === 'string' && typeof t.duration === 'number' && Number.isFinite(t.duration);
44
+ /** Spans of the app's own code: everything but the root (the request/job itself), database queries and outbound HTTP. */
45
+ const billableSpans = (t) => {
46
+ let n = 0;
47
+ for (const s of Array.isArray(t.spans) ? t.spans : [])
48
+ if (s && s.parentId && s.kind !== 'db' && s.kind !== 'http')
49
+ n += Math.max(1, Math.floor(Number(s.count) || 1));
50
+ return n;
51
+ };
52
+ /** A 5xx response or a failed job. */
53
+ const serverError = (t) => !!t.failed && (t.kind === 'job' || !t.status || t.status >= 500);
54
+ /** Keeps its full trace when detail is reduced: server errors, failed jobs, anything slower than 1 s. */
55
+ const keepsDetail = (t) => serverError(t) || t.duration > SLOW_MS;
56
+ /** The events in an SDK batch, the way they are metered. */
57
+ export function countEvents(p) {
58
+ const c = zero();
59
+ for (const t of Array.isArray(p.traces) ? p.traces : []) {
60
+ if (!validTrace(t))
61
+ continue;
62
+ if (t.kind === 'job')
63
+ c.jobs++;
64
+ else
65
+ c.requests++;
66
+ c.spans += billableSpans(t);
67
+ }
68
+ for (const e of Array.isArray(p.errors) ? p.errors : [])
69
+ if (e && e.fingerprint)
70
+ c.errors++;
71
+ for (const l of Array.isArray(p.logs) ? p.logs : [])
72
+ if (l)
73
+ c.logs++;
74
+ return c;
75
+ }
76
+ export class UsageMeter {
77
+ root;
78
+ opts;
79
+ cache = null;
80
+ /** Billed events per minute over the last hour, for spike protection's "current pace". */
81
+ minutes = new Map();
82
+ constructor(root, opts) {
83
+ this.root = root;
84
+ this.opts = opts;
85
+ if (!getSetting(root, 'usage_settings') && opts.defaultPlan) {
86
+ const id = String(opts.defaultPlan).toLowerCase();
87
+ if (isPlanId(id))
88
+ this.save({ plan: id });
89
+ else
90
+ opts.log?.(`OBZERVER_PLAN "${opts.defaultPlan}" is not a plan (${PLAN_IDS.join(', ')}); using Self-hosted`);
91
+ }
92
+ }
93
+ settings() {
94
+ let s = {};
95
+ try {
96
+ s = JSON.parse(getSetting(this.root, 'usage_settings') || '{}');
97
+ }
98
+ catch {
99
+ s = {};
100
+ }
101
+ return { ...DEFAULT_SETTINGS, ...s, enterprise: { ...DEFAULT_SETTINGS.enterprise, ...(s.enterprise || {}) } };
102
+ }
103
+ /** Validates and stores a settings change; returns the new settings or throws an Error with a message for the user. */
104
+ save(patch, now = Date.now()) {
105
+ const cur = this.settings();
106
+ const next = { ...cur };
107
+ if (patch.plan !== undefined) {
108
+ if (!isPlanId(patch.plan))
109
+ throw new Error(`Unknown plan. Use one of: ${PLAN_IDS.join(', ')}`);
110
+ if (patch.plan !== cur.plan) {
111
+ next.plan = patch.plan;
112
+ next.planSince = now;
113
+ next.spikeProtection = null;
114
+ }
115
+ }
116
+ if (patch.enterprise) {
117
+ const inc = Number(patch.enterprise.included ?? cur.enterprise.included);
118
+ const ret = Number(patch.enterprise.retentionDays ?? cur.enterprise.retentionDays);
119
+ if (!(inc > 0) || !(ret >= 1 && ret <= 3650))
120
+ throw new Error('Enterprise needs an allowance above 0 and 1–3650 days of retention');
121
+ next.enterprise = { included: Math.round(inc), retentionDays: Math.round(ret) };
122
+ }
123
+ if (patch.budget !== undefined) {
124
+ if (patch.budget === null || patch.budget === '')
125
+ next.budget = null;
126
+ else {
127
+ const b = Number(patch.budget);
128
+ if (!(b >= 0))
129
+ throw new Error('The overage budget is a number of events, 0 or more');
130
+ next.budget = Math.round(b);
131
+ }
132
+ }
133
+ if (patch.spikeProtection !== undefined)
134
+ next.spikeProtection = patch.spikeProtection === null ? null : !!patch.spikeProtection;
135
+ if (patch.thresholds !== undefined) {
136
+ const t = [...new Set((Array.isArray(patch.thresholds) ? patch.thresholds : []).map(Number))].filter((x) => x > 0 && x <= 1000).sort((a, b) => a - b);
137
+ if (t.length > MAX_THRESHOLDS)
138
+ throw new Error(`Up to ${MAX_THRESHOLDS} notification thresholds`);
139
+ next.thresholds = t.map((x) => Math.round(x));
140
+ }
141
+ if (patch.notify !== undefined)
142
+ next.notify = String(patch.notify || '').slice(0, 1000);
143
+ if (patch.overageRate !== undefined) {
144
+ const r = patch.overageRate === null || patch.overageRate === '' ? null : Number(patch.overageRate);
145
+ if (r !== null && !(r >= 0))
146
+ throw new Error('The overage rate is a price per million events, 0 or more');
147
+ next.overageRate = r;
148
+ }
149
+ setSetting(this.root, 'usage_settings', JSON.stringify(next));
150
+ return next;
151
+ }
152
+ plan() {
153
+ const s = this.settings();
154
+ const p = PLANS[s.plan];
155
+ return s.plan === 'enterprise' ? { ...p, included: s.enterprise.included, retentionDays: s.enterprise.retentionDays } : p;
156
+ }
157
+ feature(f) { return this.plan().features[f]; }
158
+ /** Raw-data retention for the plan, or the server's own setting on Self-hosted. */
159
+ retentionDays(serverDays) { return this.plan().retentionDays ?? serverDays; }
160
+ spikeProtectionOn(now = Date.now()) {
161
+ const s = this.settings();
162
+ if (s.spikeProtection !== null)
163
+ return s.spikeProtection;
164
+ const d = PLANS[s.plan].spikeDefault;
165
+ return d === 'on' || (d === 'first-month' && now - s.planSince < 31 * DAY);
166
+ }
167
+ period(now) {
168
+ const month = monthKey(now);
169
+ let p = null;
170
+ try {
171
+ p = JSON.parse(getSetting(this.root, 'usage_period') || 'null');
172
+ }
173
+ catch {
174
+ p = null;
175
+ }
176
+ if (!p || p.month !== month)
177
+ p = { month, notified: [], pausedAt: null, spikeAt: null, resumed: false };
178
+ return p;
179
+ }
180
+ savePeriod(p) { setSetting(this.root, 'usage_period', JSON.stringify(p)); }
181
+ /** Forget the cached month totals (after a project is removed). */
182
+ invalidate() { this.cache = null; }
183
+ totals(now) {
184
+ const month = monthKey(now);
185
+ const day = dayKey(now);
186
+ if (!this.cache || this.cache.month !== month) {
187
+ let billed = 0;
188
+ let dayBilled = 0;
189
+ for (const { db } of this.opts.projects()) {
190
+ billed += db.get('SELECT SUM(billed) n FROM usage_daily WHERE day >= ?', `${month}-01`)?.n ?? 0;
191
+ dayBilled += db.get('SELECT SUM(billed) n FROM usage_daily WHERE day = ?', day)?.n ?? 0;
192
+ }
193
+ this.cache = { month, day, billed, dayBilled };
194
+ this.minutes.clear();
195
+ }
196
+ else if (this.cache.day !== day) {
197
+ this.cache.day = day;
198
+ this.cache.dayBilled = 0;
199
+ }
200
+ return this.cache;
201
+ }
202
+ /** Where this month stands, and why. */
203
+ state(now = Date.now()) {
204
+ const plan = this.plan();
205
+ if (plan.included == null)
206
+ return { state: 'unlimited', reason: null };
207
+ const { billed, dayBilled } = this.totals(now);
208
+ if (plan.overage === 'reduce') {
209
+ if (billed >= plan.included * FREE_REFUSE_AT)
210
+ return { state: 'refused', reason: `${fmt(plan.included * FREE_REFUSE_AT)} events this month: new telemetry is refused until the 1st` };
211
+ if (billed >= plan.included)
212
+ return { state: 'reduced', reason: 'Past the monthly allowance: charts stay live, most traces arrive without spans' };
213
+ if (dayBilled >= FREE_DAILY_PACE)
214
+ return { state: 'paced', reason: `${fmt(FREE_DAILY_PACE)} events today: most trace waterfalls pause until 00:00 UTC` };
215
+ return { state: 'ok', reason: null };
216
+ }
217
+ if (billed < plan.included)
218
+ return { state: 'ok', reason: null };
219
+ const s = this.settings();
220
+ const p = this.period(now);
221
+ if (p.pausedAt)
222
+ return { state: 'paused', reason: 'Overage paused by hand' };
223
+ if (s.budget !== null && billed - plan.included >= s.budget)
224
+ return { state: 'paused', reason: s.budget === 0 ? 'The overage budget is 0: nothing is collected beyond the allowance' : 'The monthly overage budget is used up' };
225
+ if (p.spikeAt)
226
+ return { state: 'paused', reason: 'Spike protection paused overage' };
227
+ return { state: 'overage', reason: null };
228
+ }
229
+ /** Spike protection: pause overage when the current pace would push this month's overage past the limit. */
230
+ spikeLimit() {
231
+ const s = this.settings();
232
+ const inc = this.plan().included ?? 0;
233
+ return s.overageRate ? Math.round((50 / s.overageRate) * 1e6) : Math.round(inc * 0.5);
234
+ }
235
+ pacePerMs(now) {
236
+ const cut = Math.floor(now / 60000) - 60;
237
+ let n = 0;
238
+ for (const [m, c] of this.minutes) {
239
+ if (m <= cut)
240
+ this.minutes.delete(m);
241
+ else
242
+ n += c;
243
+ }
244
+ return n / (60 * 60000);
245
+ }
246
+ projectedOverage(now = Date.now()) {
247
+ const inc = this.plan().included;
248
+ if (inc == null)
249
+ return 0;
250
+ const { billed } = this.totals(now);
251
+ return Math.max(0, billed + this.pacePerMs(now) * (nextMonth(now) - now) - inc);
252
+ }
253
+ /** Decide what of a batch is kept, before it is stored. */
254
+ admit(payload, now = Date.now()) {
255
+ const plan = this.plan();
256
+ const all = countEvents(payload);
257
+ let { state } = this.state(now);
258
+ const p = { ...payload };
259
+ if (state === 'refused') {
260
+ const seconds = Math.max(1, Math.ceil((nextMonth(now) - now) / 1000));
261
+ return { refuse: true, seconds, error: `This month's events are past ${FREE_REFUSE_AT}× the Free plan's allowance. New telemetry is refused until the 1st (UTC). Upgrade the plan in Usage to keep collecting.` };
262
+ }
263
+ if (state === 'overage' && this.spikeProtectionOn(now) && !this.period(now).resumed) {
264
+ const projected = this.projectedOverage(now) + total(all);
265
+ if (projected >= this.spikeLimit()) {
266
+ const per = this.period(now);
267
+ per.spikeAt = now;
268
+ this.savePeriod(per);
269
+ state = 'paused';
270
+ this.opts.log?.(`spike protection paused overage (projected ${fmt(projected)} overage events this month)`);
271
+ void this.mail('Obzerver: spike protection paused overage', `A surge would have pushed this month's overage to about ${fmt(projected)} events at the current pace, so Obzerver paused overage. Server errors, failed jobs, runtime and custom metrics are still collected. Resume, change the budget or upgrade from the Usage page.`);
272
+ }
273
+ }
274
+ if (!plan.features.logs)
275
+ p.logs = [];
276
+ const traces = (Array.isArray(p.traces) ? p.traces : []);
277
+ if (state === 'paced' || state === 'reduced') {
278
+ p.traces = traces.map((t) => (validTrace(t) && !keepsDetail(t) && t.spans ? { ...t, spans: undefined } : t));
279
+ }
280
+ let unbilled = zero();
281
+ if (state === 'paused') {
282
+ // Unbilled while paused: server errors, failed jobs, runtime and custom metrics. Everything else waits for the 1st.
283
+ p.traces = traces.filter((t) => validTrace(t) && serverError(t));
284
+ p.errors = (Array.isArray(p.errors) ? p.errors : []).filter((e) => e && !e.handled);
285
+ p.logs = [];
286
+ unbilled = countEvents(p);
287
+ }
288
+ const billed = state === 'paused' ? zero() : countEvents(p);
289
+ return { refuse: false, payload: p, billed, unbilled, dropped: Math.max(0, total(all) - total(billed) - total(unbilled)), state };
290
+ }
291
+ /** Add a stored batch to the project's usage, then send any quota notifications it crossed. */
292
+ record(db, service, env, a, now = Date.now()) {
293
+ const b = a.billed;
294
+ const n = total(b);
295
+ db.run(`INSERT INTO usage_daily(day, service, env, requests, jobs, errors, logs, spans, billed, unbilled, dropped) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
296
+ ON CONFLICT(day, service, env) DO UPDATE SET requests = requests + excluded.requests, jobs = jobs + excluded.jobs, errors = errors + excluded.errors,
297
+ logs = logs + excluded.logs, spans = spans + excluded.spans, billed = billed + excluded.billed, unbilled = unbilled + excluded.unbilled, dropped = dropped + excluded.dropped`, dayKey(now), service, env ?? '', b.requests, b.jobs, b.errors, b.logs, b.spans, n, total(a.unbilled), a.dropped);
298
+ const t = this.totals(now);
299
+ t.billed += n;
300
+ t.dayBilled += n;
301
+ const m = Math.floor(now / 60000);
302
+ this.minutes.set(m, (this.minutes.get(m) ?? 0) + n);
303
+ this.checkThresholds(now);
304
+ }
305
+ checkThresholds(now) {
306
+ const inc = this.plan().included;
307
+ if (inc == null)
308
+ return;
309
+ const used = this.totals(now).billed;
310
+ const pct = (used / inc) * 100;
311
+ const per = this.period(now);
312
+ const crossed = this.settings().thresholds.filter((t) => pct >= t && !per.notified.some((x) => x.pct === t));
313
+ if (!crossed.length)
314
+ return;
315
+ for (const t of crossed)
316
+ per.notified.push({ pct: t, ts: now, used });
317
+ this.savePeriod(per);
318
+ const top = Math.max(...crossed);
319
+ this.opts.log?.(`usage passed ${top}% of this month's ${fmt(inc)} events`);
320
+ void this.mail(`Obzerver: ${top}% of this month's events used`, `Your apps have reported ${fmt(used)} of the ${fmt(inc)} events included in the ${this.plan().name} plan this month (${Math.floor(pct)}%). ${this.afterAllowance()}`);
321
+ }
322
+ afterAllowance() {
323
+ const plan = this.plan();
324
+ if (plan.overage === 'reduce')
325
+ return `Past the allowance, charts stay live but most traces arrive without spans; at ${FREE_REFUSE_AT}× new telemetry is refused until the 1st.`;
326
+ return 'Past the allowance, overage is collected within your spend controls.';
327
+ }
328
+ async mail(subject, text) {
329
+ const to = this.settings().notify.trim();
330
+ if (!to || !this.opts.email)
331
+ return;
332
+ try {
333
+ await this.opts.email(to, subject, text);
334
+ }
335
+ catch (e) {
336
+ this.opts.log?.(`usage email: ${e.message}`);
337
+ }
338
+ }
339
+ pause(now = Date.now()) { const p = this.period(now); p.pausedAt = now; this.savePeriod(p); }
340
+ resume(now = Date.now()) { const p = this.period(now); p.pausedAt = null; p.spikeAt = null; p.resumed = true; this.savePeriod(p); }
341
+ /** The short form for /api/meta: plan, features and the month's state. */
342
+ summary(now = Date.now()) {
343
+ const plan = this.plan();
344
+ const { state, reason } = this.state(now);
345
+ const used = this.totals(now).billed;
346
+ return { plan: plan.id, name: plan.name, features: plan.features, included: plan.included, used, pct: plan.included ? (used / plan.included) * 100 : null, state, reason };
347
+ }
348
+ /** Everything the Usage page shows. */
349
+ report(now = Date.now()) {
350
+ const plan = this.plan();
351
+ const s = this.settings();
352
+ const per = this.period(now);
353
+ const from = `${monthKey(now)}-01`;
354
+ const days = new Map();
355
+ const byProject = [];
356
+ const kinds = zero();
357
+ let unbilled = 0;
358
+ let dropped = 0;
359
+ for (const { slug, name, db } of this.opts.projects()) {
360
+ const rows = db.all('SELECT * FROM usage_daily WHERE day >= ?', from);
361
+ const apps = new Map();
362
+ let pb = 0, pu = 0, pd = 0;
363
+ for (const r of rows) {
364
+ const d = days.get(r.day) ?? { ...zero(), unbilled: 0, dropped: 0 };
365
+ for (const k of ['requests', 'jobs', 'errors', 'logs', 'spans']) {
366
+ d[k] += r[k];
367
+ kinds[k] += r[k];
368
+ }
369
+ d.unbilled += r.unbilled;
370
+ d.dropped += r.dropped;
371
+ days.set(r.day, d);
372
+ const key = `${r.service}\u0000${r.env}`;
373
+ const a = apps.get(key) ?? { service: r.service, env: r.env || null, billed: 0, requests: 0, jobs: 0, errors: 0, logs: 0, spans: 0 };
374
+ a.billed += r.billed;
375
+ a.requests += r.requests;
376
+ a.jobs += r.jobs;
377
+ a.errors += r.errors;
378
+ a.logs += r.logs;
379
+ a.spans += r.spans;
380
+ apps.set(key, a);
381
+ pb += r.billed;
382
+ pu += r.unbilled;
383
+ pd += r.dropped;
384
+ }
385
+ unbilled += pu;
386
+ dropped += pd;
387
+ byProject.push({ slug, name, billed: pb, unbilled: pu, dropped: pd, apps: [...apps.values()].sort((a, b) => b.billed - a.billed) });
388
+ }
389
+ byProject.sort((a, b) => b.billed - a.billed);
390
+ const start = monthStart(now);
391
+ const end = nextMonth(now);
392
+ const daily = [];
393
+ for (let t = start; t < end; t += DAY) {
394
+ const k = dayKey(t);
395
+ const d = days.get(k);
396
+ daily.push({ day: k, events: d ? total(d) : 0, unbilled: d?.unbilled ?? 0, dropped: d?.dropped ?? 0 });
397
+ }
398
+ const used = byProject.reduce((n, p) => n + p.billed, 0);
399
+ const { state, reason } = this.state(now);
400
+ const elapsed = Math.max(1, now - start);
401
+ const projected = Math.round(used + (used / elapsed) * (end - now));
402
+ return {
403
+ plan, plans: PLAN_IDS.map((id) => PLANS[id]), settings: s,
404
+ month: monthKey(now), resetsAt: end, used, included: plan.included,
405
+ pct: plan.included ? (used / plan.included) * 100 : null,
406
+ today: this.totals(now).dayBilled, projected,
407
+ overage: plan.included != null ? Math.max(0, used - plan.included) : 0,
408
+ unbilled, dropped, kinds, state, reason,
409
+ spikeProtection: { on: this.spikeProtectionOn(now), limit: plan.overage === 'billed' ? this.spikeLimit() : null, tripped: per.spikeAt, resumed: per.resumed },
410
+ pausedAt: per.pausedAt, notified: per.notified,
411
+ limits: { dailyPace: plan.overage === 'reduce' ? FREE_DAILY_PACE : null, refuseAt: plan.overage === 'reduce' && plan.included ? plan.included * FREE_REFUSE_AT : null, spanTreeDays: (plan.retentionDays ?? 0) > SPAN_TREE_DAYS ? SPAN_TREE_DAYS : null },
412
+ daily, byProject,
413
+ };
414
+ }
415
+ }
416
+ /** Plans with retention past 7 days drop the span tree of fast, successful executions after 7 days. */
417
+ export function pruneSpanTrees(db, now = Date.now()) {
418
+ const cut = now - SPAN_TREE_DAYS * DAY;
419
+ let n = 0;
420
+ db.tx(() => {
421
+ n = db.run(`DELETE FROM spans WHERE trace_row IN (SELECT id FROM traces WHERE ts < ? AND sampled = 1 AND failed = 0 AND duration <= ?)`, cut, SLOW_MS).changes;
422
+ db.run(`UPDATE traces SET sampled = 0, data = json_remove(data, '$.spans') WHERE ts < ? AND sampled = 1 AND failed = 0 AND duration <= ?`, cut, SLOW_MS);
423
+ });
424
+ return n;
425
+ }
426
+ export const fmt = (n) => {
427
+ if (n >= 1e9)
428
+ return `${+(n / 1e9).toFixed(n % 1e9 ? 1 : 0)}B`;
429
+ if (n >= 1e6)
430
+ return `${+(n / 1e6).toFixed(n % 1e6 ? 1 : 0)}M`;
431
+ if (n >= 1e3)
432
+ return `${+(n / 1e3).toFixed(n % 1e3 ? 1 : 0)}k`;
433
+ return String(Math.round(n));
434
+ };
435
+ export { nextDay };
436
+ //# sourceMappingURL=usage.js.map