@my-nestjs-kit/stats 0.0.0-stage → 0.1.0-dev.20261129010337

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.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +165 -2
  3. package/dist/buffers/memory-stats-buffer.d.ts +21 -0
  4. package/dist/buffers/memory-stats-buffer.js +84 -0
  5. package/dist/buffers/redis-stats-buffer.d.ts +79 -0
  6. package/dist/buffers/redis-stats-buffer.js +261 -0
  7. package/dist/helpers/stat-metrics.d.ts +61 -0
  8. package/dist/helpers/stat-metrics.js +193 -0
  9. package/dist/helpers/stat-period.d.ts +22 -0
  10. package/dist/helpers/stat-period.js +105 -0
  11. package/dist/helpers/stat-timeline.d.ts +16 -0
  12. package/dist/helpers/stat-timeline.js +58 -0
  13. package/dist/helpers/stat-zoned.d.ts +19 -0
  14. package/dist/helpers/stat-zoned.js +63 -0
  15. package/dist/index.d.ts +19 -0
  16. package/dist/index.js +40 -0
  17. package/dist/ports/stats-buffer.d.ts +37 -0
  18. package/dist/ports/stats-buffer.js +2 -0
  19. package/dist/ports/stats-store.d.ts +45 -0
  20. package/dist/ports/stats-store.js +12 -0
  21. package/dist/stats.constants.d.ts +31 -0
  22. package/dist/stats.constants.js +46 -0
  23. package/dist/stats.jobs.d.ts +29 -0
  24. package/dist/stats.jobs.js +34 -0
  25. package/dist/stats.module.d.ts +14 -0
  26. package/dist/stats.module.js +41 -0
  27. package/dist/stats.options.d.ts +35 -0
  28. package/dist/stats.options.js +4 -0
  29. package/dist/stats.scheduler.d.ts +20 -0
  30. package/dist/stats.scheduler.js +67 -0
  31. package/dist/stats.service.d.ts +80 -0
  32. package/dist/stats.service.js +370 -0
  33. package/dist/stats.types.d.ts +149 -0
  34. package/dist/stats.types.js +18 -0
  35. package/dist/stores/memory/in-memory-stats-store.d.ts +21 -0
  36. package/dist/stores/memory/in-memory-stats-store.js +102 -0
  37. package/dist/stores/typeorm/metric-snapshot.entity.d.ts +33 -0
  38. package/dist/stores/typeorm/metric-snapshot.entity.js +95 -0
  39. package/dist/stores/typeorm/metric-snapshots.migration.d.ts +20 -0
  40. package/dist/stores/typeorm/metric-snapshots.migration.js +60 -0
  41. package/dist/stores/typeorm/typeorm-stats-store.d.ts +48 -0
  42. package/dist/stores/typeorm/typeorm-stats-store.js +190 -0
  43. package/package.json +86 -3
@@ -0,0 +1,370 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.StatsService = void 0;
16
+ const common_1 = require("@nestjs/common");
17
+ const rxjs_1 = require("rxjs");
18
+ const stat_metrics_1 = require("./helpers/stat-metrics");
19
+ const stat_period_1 = require("./helpers/stat-period");
20
+ const stat_timeline_1 = require("./helpers/stat-timeline");
21
+ const stat_zoned_1 = require("./helpers/stat-zoned");
22
+ const stats_store_1 = require("./ports/stats-store");
23
+ const stats_constants_1 = require("./stats.constants");
24
+ const stats_options_1 = require("./stats.options");
25
+ const stats_types_1 = require("./stats.types");
26
+ /**
27
+ * The stats engine (skill `nestjs-stats`): writes go to the buffer as deltas, `flush()` moves taken deltas into the
28
+ * store, which adds them; reads sum the store plus the buffer's unflushed buckets when it exposes them.
29
+ *
30
+ * Writers inject this service only. `increment` / `recordGauge` / `incrementDuration` never reject: callers may
31
+ * `void` them.
32
+ */
33
+ let StatsService = class StatsService {
34
+ constructor(_o) {
35
+ this._o = _o;
36
+ this._logger = new common_1.Logger('StatsService');
37
+ this._flushing = null;
38
+ /** `write`: an increment was accepted here; `flush`: buckets of these namespaces reached the store. */
39
+ this.changed$ = new rxjs_1.Subject();
40
+ if (!_o?.buffer || !_o?.store)
41
+ throw new Error('StatsService: options.buffer and options.store are required');
42
+ this._granularities = _o.granularities?.length ? [..._o.granularities] : [...stats_constants_1.ALL_STAT_GRANULARITIES];
43
+ }
44
+ // ─── write ───────────────────────────────────────────────────────────────────────────────────────────────────
45
+ /** Hot path: buffer only, no store I/O. Never rejects (rule 14); a bad key or a buffer outage drops the write. */
46
+ async increment(p) {
47
+ try {
48
+ const buckets = this._bucketsOf(p);
49
+ if (buckets?.length)
50
+ await this._write(buckets);
51
+ }
52
+ catch (e) {
53
+ this._logger.warn(`stats write dropped (${String(p?.namespace).slice(0, 64)}): ${e?.message}`);
54
+ }
55
+ }
56
+ /** A gauge sample: `{ sum: v, n: 1 }` per value in each bucket; read the mean with `statGaugeAverage`. */
57
+ recordGauge({ values, ...rest }) {
58
+ const metrics = (0, stat_metrics_1.statDict)();
59
+ for (const [name, v] of Object.entries(values ?? {})) {
60
+ if (typeof v === 'number' && Number.isFinite(v))
61
+ metrics[name] = { [stats_constants_1.STAT_GAUGE_SUM]: v, [stats_constants_1.STAT_GAUGE_COUNT]: 1 };
62
+ }
63
+ return this.increment({ ...rest, metrics });
64
+ }
65
+ /**
66
+ * A span cut at every bucket boundary of the finest granularity written (rule 24): 23:40–01:10 gives each hour /
67
+ * day only its own seconds; coarser buckets get the sum of their pieces. Default granularities: the module's
68
+ * without `min`. Record closed pieces progressively for long spans (crash = the open piece is lost).
69
+ */
70
+ async incrementDuration(p) {
71
+ try {
72
+ const { value, status = 'seconds', start, end, granularities: own, ...series } = p;
73
+ const granularities = own?.length ? own : this._granularities.filter((g) => g !== stats_types_1.StatGranularity.MINUTE);
74
+ const finest = stats_constants_1.ALL_STAT_GRANULARITIES.find((g) => granularities.includes(g));
75
+ if (!finest || !(start instanceof Date) || !(end instanceof Date))
76
+ return;
77
+ const buckets = [];
78
+ for (const piece of (0, stat_period_1.splitStatSpan)(start, end, finest)) {
79
+ const seconds = Math.round(piece.ms / 1000);
80
+ if (seconds <= 0)
81
+ continue;
82
+ const pieceBuckets = this._bucketsOf({
83
+ ...series,
84
+ granularities,
85
+ at: piece.at,
86
+ metrics: { [value]: { [status]: seconds } },
87
+ });
88
+ if (!pieceBuckets)
89
+ return;
90
+ buckets.push(...pieceBuckets);
91
+ }
92
+ if (buckets.length)
93
+ await this._write(buckets); // one buffer round-trip for the whole span
94
+ }
95
+ catch (e) {
96
+ this._logger.warn(`stats duration dropped (${String(p?.namespace).slice(0, 64)}): ${e?.message}`);
97
+ }
98
+ }
99
+ // ─── flush / prune ───────────────────────────────────────────────────────────────────────────────────────────
100
+ /**
101
+ * Moves taken deltas into the store, which adds them. Safe with several instances on one buffer: a bucket is taken
102
+ * by one flusher only, and a batch is applied at most once (store flush log). On a store failure the batch's
103
+ * deltas go back into the buffer (or stay in flight for a retry when the outcome is unknown). Concurrent calls in
104
+ * one process share one run. Never rejects.
105
+ */
106
+ flush() {
107
+ if (!this._flushing) {
108
+ this._flushing = this._flush().finally(() => {
109
+ this._flushing = null;
110
+ });
111
+ }
112
+ return this._flushing;
113
+ }
114
+ /** Hard-delete store rows past retention (rule 12) and old flush-log rows. Never rejects. */
115
+ async prune(now = new Date()) {
116
+ const retention = { ...stats_constants_1.STAT_DEFAULT_RETENTION_MS, ...(this._o.retention ?? {}) };
117
+ for (const g of stats_constants_1.ALL_STAT_GRANULARITIES) {
118
+ const ms = retention[g];
119
+ if (ms === null || ms === undefined)
120
+ continue;
121
+ try {
122
+ await this._o.store.prune(g, new Date(now.getTime() - ms));
123
+ }
124
+ catch (e) {
125
+ this._logger.warn(`stats prune ${g} failed: ${e?.message}`);
126
+ }
127
+ }
128
+ try {
129
+ const keep = this._o.flushLogRetentionMs ?? stats_constants_1.STAT_DEFAULT_FLUSH_LOG_RETENTION_MS;
130
+ await this._o.store.pruneFlushLog?.(new Date(now.getTime() - keep));
131
+ }
132
+ catch (e) {
133
+ this._logger.warn(`stats flush-log prune failed: ${e?.message}`);
134
+ }
135
+ }
136
+ // ─── read ────────────────────────────────────────────────────────────────────────────────────────────────────
137
+ /**
138
+ * Gap-filled timeline (rule 10). Without `subjectType` every series of the namespace is summed (rule 8);
139
+ * `subjectId` without `subjectType` is a 400. At most 5000 points. Scope `subjectType` / `subjectId` to what the
140
+ * caller may see before calling this (rule 13).
141
+ */
142
+ async timeline(q) {
143
+ if (q.subjectId !== undefined && q.subjectType === undefined) {
144
+ throw new common_1.BadRequestException('subjectId requires subjectType');
145
+ }
146
+ const fromIn = new Date(q.from);
147
+ const to = new Date(q.to);
148
+ if (!Number.isFinite(fromIn.getTime()) || !Number.isFinite(to.getTime())) {
149
+ throw new common_1.BadRequestException('from / to must be dates');
150
+ }
151
+ // Counted by arithmetic before anything is allocated; the range below is then at most the cap.
152
+ if ((0, stat_period_1.statPeriodCount)(fromIn, to, q.granularity) > stats_constants_1.STAT_MAX_TIMELINE_POINTS) {
153
+ throw new common_1.BadRequestException(`Timeline exceeds ${stats_constants_1.STAT_MAX_TIMELINE_POINTS} points: narrow the range or use a coarser granularity`);
154
+ }
155
+ const buckets = (0, stat_period_1.statPeriodRange)(fromIn, to, q.granularity, stats_constants_1.STAT_MAX_TIMELINE_POINTS);
156
+ const from = buckets[0] ?? fromIn;
157
+ const { limit, ...filter } = q;
158
+ const rows = await this._cells({ ...filter, from, to });
159
+ return (0, stat_timeline_1.buildStatTimeline)({ namespace: q.namespace, granularity: q.granularity, buckets, from, to, rows, limit });
160
+ }
161
+ /** Today (UTC day) and all time, from `day` buckets (the namespace must write `day`). */
162
+ async totals(series, now = new Date()) {
163
+ const from = (0, stat_period_1.statPeriodStart)(now, stats_types_1.StatGranularity.DAY);
164
+ const to = (0, stat_period_1.statNextPeriodStart)(from, stats_types_1.StatGranularity.DAY);
165
+ const f = { ...series, granularity: stats_types_1.StatGranularity.DAY };
166
+ const [today, total] = await Promise.all([this._sum({ ...f, from, to }), this._sum(f)]);
167
+ return { today, total };
168
+ }
169
+ /** Like `totals`, kept per series (rule 27): subject and series key stay in each row. */
170
+ async seriesTotals(series, now = new Date()) {
171
+ const from = (0, stat_period_1.statPeriodStart)(now, stats_types_1.StatGranularity.DAY);
172
+ const to = (0, stat_period_1.statNextPeriodStart)(from, stats_types_1.StatGranularity.DAY);
173
+ const f = { ...series, granularity: stats_types_1.StatGranularity.DAY };
174
+ const [today, total] = await Promise.all([this._seriesCells({ ...f, from, to }), this._seriesCells(f)]);
175
+ return { today, total };
176
+ }
177
+ /**
178
+ * The last `days` local days of `timeZone` (today included), summed from UTC `hour` (or `min`) buckets (rule 17).
179
+ * DST-safe. A bucket belongs to the local day of its start, so with `hour` a :30 offset shifts half an hour.
180
+ */
181
+ async localDays(q) {
182
+ const { days: n, timeZone, now = new Date(), granularity = stats_types_1.StatGranularity.HOUR, ...series } = q;
183
+ if (!Number.isInteger(n) || n < 1)
184
+ throw new common_1.BadRequestException('days must be a positive integer');
185
+ // Before any loop or allocation: n days hold at least n × (buckets per day) buckets.
186
+ const perDay = granularity === stats_types_1.StatGranularity.MINUTE ? 24 * 60 : granularity === stats_types_1.StatGranularity.HOUR ? 24 : 1;
187
+ if (n > Math.floor(stats_constants_1.STAT_MAX_TIMELINE_POINTS / perDay)) {
188
+ throw new common_1.BadRequestException(`Too many ${granularity} buckets for ${n} days: at most ${Math.floor(stats_constants_1.STAT_MAX_TIMELINE_POINTS / perDay)} days`);
189
+ }
190
+ let today;
191
+ try {
192
+ today = (0, stat_zoned_1.zonedParts)(now, timeZone);
193
+ }
194
+ catch {
195
+ throw new common_1.BadRequestException(`Unknown timezone: ${timeZone}`);
196
+ }
197
+ const days = [];
198
+ for (let i = n - 1; i >= 0; i--) {
199
+ const d = new Date(Date.UTC(today.year, today.month - 1, today.day - i));
200
+ const [y, m, dd] = [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()];
201
+ days.push({
202
+ date: `${y}-${String(m).padStart(2, '0')}-${String(dd).padStart(2, '0')}`,
203
+ start: (0, stat_zoned_1.zonedMidnight)(y, m, dd, timeZone),
204
+ metrics: (0, stat_metrics_1.statDict)(),
205
+ });
206
+ }
207
+ const to = (0, stat_zoned_1.zonedMidnight)(today.year, today.month, today.day + 1, timeZone);
208
+ const from = (0, stat_period_1.statPeriodStart)(days[0].start, granularity);
209
+ // Exact count (a DST day has 25 hours, `from` is floored): arithmetic, no range is built.
210
+ if ((0, stat_period_1.statPeriodCount)(from, to, granularity) > stats_constants_1.STAT_MAX_TIMELINE_POINTS) {
211
+ throw new common_1.BadRequestException(`Too many ${granularity} buckets for ${n} days`);
212
+ }
213
+ const byDate = new Map(days.map((d) => [d.date, d]));
214
+ for (const r of await this._cells({ ...series, granularity, from, to })) {
215
+ const day = byDate.get((0, stat_zoned_1.zonedDateKey)(new Date(r.periodStart), timeZone));
216
+ if (day)
217
+ (0, stat_metrics_1.addStatMetrics)(day.metrics, (0, stat_metrics_1.statCellMetrics)(r.value, r.status, r.count));
218
+ }
219
+ return days;
220
+ }
221
+ /** Anything of the namespace in the store or still unflushed here (backfill guard, rule 25). */
222
+ async hasNamespace(namespace) {
223
+ for (const b of this._o.buffer.unflushed?.() ?? [])
224
+ if (b.namespace === namespace)
225
+ return true;
226
+ return this._o.store.hasNamespace(namespace);
227
+ }
228
+ // ─── internals ───────────────────────────────────────────────────────────────────────────────────────────────
229
+ /** Normalized buckets of one write, or `null` when the series is rejected (logged) or nothing is left. */
230
+ _bucketsOf(p) {
231
+ const series = (0, stat_metrics_1.normalizeStatSeries)(p);
232
+ if (!series) {
233
+ this._logger.warn(`stats write dropped: empty or too long series segment (${String(p?.namespace).slice(0, 64)})`);
234
+ return null;
235
+ }
236
+ const delta = (0, stat_metrics_1.normalizeStatMetrics)(p.metrics);
237
+ const at = p.at ?? new Date();
238
+ if (!delta || !(at instanceof Date) || !Number.isFinite(at.getTime()))
239
+ return null;
240
+ return (p.granularities?.length ? p.granularities : this._granularities).map((g) => ({
241
+ ...series,
242
+ granularity: g,
243
+ periodStart: (0, stat_period_1.statPeriodStart)(at, g),
244
+ metrics: delta,
245
+ }));
246
+ }
247
+ async _write(buckets) {
248
+ await this._o.buffer.add(buckets);
249
+ this.changed$.next({ type: 'write', namespaces: [...new Set(buckets.map((b) => b.namespace))] });
250
+ }
251
+ async _flush() {
252
+ const result = { batches: 0, buckets: 0 };
253
+ const namespaces = new Set();
254
+ const { buffer } = this._o;
255
+ try {
256
+ for (const batch of await buffer.reclaim(this._o.staleBatchMs ?? stats_constants_1.STAT_DEFAULT_STALE_BATCH_MS)) {
257
+ if (!batch.buckets.length) {
258
+ this._logger.warn(`stats batch ${batch.id} expired in flight before it was written: its deltas are lost`);
259
+ await buffer.ack(batch);
260
+ continue;
261
+ }
262
+ await this._apply(batch, result, namespaces);
263
+ }
264
+ const max = this._o.maxBatchesPerFlush ?? stats_constants_1.STAT_DEFAULT_MAX_BATCHES_PER_FLUSH;
265
+ for (let i = 0; i < max; i++) {
266
+ const batch = await buffer.take(this._o.batchSize ?? stats_constants_1.STAT_DEFAULT_BATCH_SIZE);
267
+ if (!batch)
268
+ break;
269
+ await this._apply(batch, result, namespaces);
270
+ }
271
+ }
272
+ catch (e) {
273
+ result.error = e?.message ?? String(e);
274
+ this._logger.warn(`stats flush stopped: ${result.error}`);
275
+ }
276
+ if (namespaces.size)
277
+ this.changed$.next({ type: 'flush', namespaces: [...namespaces] });
278
+ return result;
279
+ }
280
+ /** One batch: merge → ack; on failure find out whether it committed, then ack, restore, or leave it in flight. */
281
+ async _apply(batch, result, namespaces) {
282
+ const { buffer, store } = this._o;
283
+ if (!batch.buckets.length) {
284
+ await buffer.ack(batch);
285
+ return;
286
+ }
287
+ try {
288
+ await store.merge(batch);
289
+ }
290
+ catch (e) {
291
+ let outcome;
292
+ if (e instanceof stats_store_1.StatBatchFencedError)
293
+ outcome = 'fenced';
294
+ else {
295
+ try {
296
+ outcome = await store.fence(batch.id);
297
+ }
298
+ catch {
299
+ // Unknown: the batch stays in flight under its id; a later flush reclaims it and the flush log dedups.
300
+ throw e;
301
+ }
302
+ }
303
+ if (outcome === 'fenced') {
304
+ await buffer.restore(batch);
305
+ throw e;
306
+ }
307
+ // 'applied': the commit went through, only its ack was lost.
308
+ }
309
+ this._count(batch, result, namespaces);
310
+ try {
311
+ await buffer.ack(batch);
312
+ }
313
+ catch (e) {
314
+ // Applied; the batch is retried after `staleBatchMs` and skipped by the flush log.
315
+ this._logger.warn(`stats ack of applied batch ${batch.id} failed: ${e?.message}`);
316
+ }
317
+ }
318
+ _count(batch, result, namespaces) {
319
+ result.batches++;
320
+ result.buckets += batch.buckets.length;
321
+ for (const b of batch.buckets)
322
+ namespaces.add(b.namespace);
323
+ }
324
+ /** Store cells plus matching unflushed buckets (S4). */
325
+ async _cells(f) {
326
+ const rows = (await this._o.store.sumCells(f)).filter((r) => !(0, stat_metrics_1.isStatReservedKey)(r.value) && !(0, stat_metrics_1.isStatReservedKey)(r.status));
327
+ for (const b of this._o.buffer.unflushed?.() ?? []) {
328
+ if (!(0, stat_metrics_1.statBucketMatches)(b, f))
329
+ continue;
330
+ const periodStart = b.periodStart.toISOString();
331
+ for (const c of (0, stat_metrics_1.statCellsOf)(b.metrics, f))
332
+ rows.push({ periodStart, ...c });
333
+ }
334
+ return rows;
335
+ }
336
+ async _sum(f) {
337
+ const out = (0, stat_metrics_1.statDict)();
338
+ for (const r of await this._cells(f))
339
+ (0, stat_metrics_1.addStatMetrics)(out, (0, stat_metrics_1.statCellMetrics)(r.value, r.status, r.count));
340
+ return out;
341
+ }
342
+ async _seriesCells(f) {
343
+ const byKey = new Map();
344
+ const put = (r) => {
345
+ const k = JSON.stringify([r.subjectType, r.subjectId ?? null, r.seriesKey, r.value, r.status]);
346
+ const cur = byKey.get(k);
347
+ if (cur)
348
+ cur.count += r.count;
349
+ else
350
+ byKey.set(k, { ...r, subjectId: r.subjectId ?? null });
351
+ };
352
+ for (const r of await this._o.store.sumSeries(f))
353
+ if (!(0, stat_metrics_1.isStatReservedKey)(r.value) && !(0, stat_metrics_1.isStatReservedKey)(r.status))
354
+ put(r);
355
+ for (const b of this._o.buffer.unflushed?.() ?? []) {
356
+ if (!(0, stat_metrics_1.statBucketMatches)(b, f))
357
+ continue;
358
+ for (const c of (0, stat_metrics_1.statCellsOf)(b.metrics, f)) {
359
+ put({ subjectType: b.subjectType, subjectId: b.subjectId ?? null, seriesKey: b.seriesKey, ...c });
360
+ }
361
+ }
362
+ return [...byKey.values()];
363
+ }
364
+ };
365
+ exports.StatsService = StatsService;
366
+ exports.StatsService = StatsService = __decorate([
367
+ (0, common_1.Injectable)(),
368
+ __param(0, (0, common_1.Inject)(stats_options_1.STATS_MODULE_OPTIONS)),
369
+ __metadata("design:paramtypes", [Object])
370
+ ], StatsService);
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Stats engine contracts (skill `nestjs-stats`). App-agnostic: the app picks namespaces, values and statuses.
3
+ * Safe to share with a client that renders charts (no Nest / TypeORM imports here).
4
+ */
5
+ /** Bucket sizes, fine → coarse (the order is used: the first one listed is the finest). All UTC; week = ISO, Monday. */
6
+ export declare enum StatGranularity {
7
+ MINUTE = "min",
8
+ HOUR = "hour",
9
+ DAY = "day",
10
+ WEEK = "week",
11
+ MONTH = "month"
12
+ }
13
+ /** `subjectType` of a global series (with `subjectId: null`). */
14
+ export declare const STAT_SUBJECT_NONE = "none";
15
+ /** status → number. */
16
+ export type StatusCounts = Record<string, number>;
17
+ /** value → status → number: one bucket's cells. */
18
+ export type StatMetrics = Record<string, StatusCounts>;
19
+ /** Who a series belongs to. `subjectId` is a polymorphic ref with no FK. */
20
+ export interface StatSeriesRef {
21
+ /** Defines what values / statuses mean and their unit (one unit per namespace). */
22
+ namespace: string;
23
+ /** `STAT_SUBJECT_NONE` for a global series. */
24
+ subjectType: string;
25
+ subjectId: string | null;
26
+ /** Extra split inside one subject; `''` when unused. */
27
+ seriesKey: string;
28
+ }
29
+ export interface StatBucketRef extends StatSeriesRef {
30
+ granularity: StatGranularity;
31
+ /** UTC start of the bucket. */
32
+ periodStart: Date;
33
+ }
34
+ /** A bucket with its cells: a delta in a buffer, a total in a store. */
35
+ export interface StatBucket extends StatBucketRef {
36
+ metrics: StatMetrics;
37
+ }
38
+ /** One write. Values and statuses are normalized by the engine (stringified, control chars stripped, capped). */
39
+ export interface StatIncrement extends Partial<Pick<StatSeriesRef, 'subjectType' | 'subjectId' | 'seriesKey'>> {
40
+ namespace: string;
41
+ /** raw value → raw status → delta. Non-finite and zero deltas are dropped. */
42
+ metrics: Record<string, Record<string, number>>;
43
+ /** Default: the module's `granularities` (all five unless configured). */
44
+ granularities?: StatGranularity[];
45
+ /** Event time; default now. Any time is accepted: the flush adds, so a late write lands in its own bucket. */
46
+ at?: Date;
47
+ }
48
+ /** A gauge sample (CPU %, queue length): written as `{ sum, n }` per value, read with `statGaugeAverage`. */
49
+ export interface StatGaugeSample extends Omit<StatIncrement, 'metrics'> {
50
+ values: Record<string, number>;
51
+ }
52
+ /** A span (session, job, call) split over buckets so each period gets only its own share. */
53
+ export interface StatDurationIncrement extends Omit<StatIncrement, 'metrics' | 'at'> {
54
+ value: string;
55
+ /** Default `'seconds'`. */
56
+ status?: string;
57
+ start: Date;
58
+ end: Date;
59
+ }
60
+ /** Read filter. Omitted subject fields = every series of the namespace, summed (rule 8). */
61
+ export interface StatFilter extends Partial<Omit<StatSeriesRef, 'namespace'>> {
62
+ namespace: string;
63
+ granularity: StatGranularity;
64
+ /** Inclusive bucket start bound. */
65
+ from?: Date;
66
+ /** Exclusive bucket start bound. */
67
+ to?: Date;
68
+ values?: string[];
69
+ statuses?: string[];
70
+ }
71
+ /** One summed cell of one bucket (summed across the series that match the filter). */
72
+ export interface StatCellRow {
73
+ /** ISO UTC bucket start. */
74
+ periodStart: string;
75
+ value: string;
76
+ status: string;
77
+ count: number;
78
+ }
79
+ /** A summed cell kept per series (for counters with more dimensions than value × status, rule 27). */
80
+ export interface StatSeriesCellRow {
81
+ subjectType: string;
82
+ subjectId: string | null;
83
+ seriesKey: string;
84
+ value: string;
85
+ status: string;
86
+ count: number;
87
+ }
88
+ export interface StatTimelineQuery extends Omit<StatFilter, 'from' | 'to'> {
89
+ from: Date | string;
90
+ /** Exclusive. Send bucket-aligned bounds (`statLastPeriods`). */
91
+ to: Date | string;
92
+ /** Top-N values by total over all statuses. Default 50. */
93
+ limit?: number;
94
+ }
95
+ export interface StatTimelinePoint {
96
+ periodStart: string;
97
+ metrics: StatMetrics;
98
+ }
99
+ export interface StatTimeline {
100
+ namespace: string;
101
+ granularity: StatGranularity;
102
+ from: string;
103
+ to: string;
104
+ /** Kept values, ranked by their total. */
105
+ values: string[];
106
+ statuses: string[];
107
+ /** Per kept value over the window. */
108
+ totals: StatMetrics;
109
+ /** More values existed than `limit`. */
110
+ truncated: boolean;
111
+ /** One per bucket in [from, to), empty buckets included. */
112
+ points: StatTimelinePoint[];
113
+ }
114
+ /** A day in a given IANA timezone, summed from finer UTC buckets. */
115
+ export interface StatLocalDay {
116
+ /** `YYYY-MM-DD` in the requested timezone. */
117
+ date: string;
118
+ /** The instant of local midnight. */
119
+ start: Date;
120
+ metrics: StatMetrics;
121
+ }
122
+ /** Today (UTC day) and all time. */
123
+ export interface StatTotals {
124
+ today: StatMetrics;
125
+ total: StatMetrics;
126
+ }
127
+ export interface StatSeriesTotals {
128
+ today: StatSeriesCellRow[];
129
+ total: StatSeriesCellRow[];
130
+ }
131
+ /** Flattened totals: value → sum of its statuses. */
132
+ export interface StatCounters {
133
+ today: Record<string, number>;
134
+ total: Record<string, number>;
135
+ }
136
+ /**
137
+ * `StatsService.changed$`: `write` after an accepted increment (this process only), `flush` after buckets reached
138
+ * the store (this process's flush only).
139
+ */
140
+ export interface StatsChange {
141
+ type: 'write' | 'flush';
142
+ namespaces: string[];
143
+ }
144
+ export interface StatFlushResult {
145
+ batches: number;
146
+ buckets: number;
147
+ /** Set when a batch could not be written; its deltas were put back or stay in flight for a retry. */
148
+ error?: string;
149
+ }
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ /**
3
+ * Stats engine contracts (skill `nestjs-stats`). App-agnostic: the app picks namespaces, values and statuses.
4
+ * Safe to share with a client that renders charts (no Nest / TypeORM imports here).
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.STAT_SUBJECT_NONE = exports.StatGranularity = void 0;
8
+ /** Bucket sizes, fine → coarse (the order is used: the first one listed is the finest). All UTC; week = ISO, Monday. */
9
+ var StatGranularity;
10
+ (function (StatGranularity) {
11
+ StatGranularity["MINUTE"] = "min";
12
+ StatGranularity["HOUR"] = "hour";
13
+ StatGranularity["DAY"] = "day";
14
+ StatGranularity["WEEK"] = "week";
15
+ StatGranularity["MONTH"] = "month";
16
+ })(StatGranularity || (exports.StatGranularity = StatGranularity = {}));
17
+ /** `subjectType` of a global series (with `subjectId: null`). */
18
+ exports.STAT_SUBJECT_NONE = 'none';
@@ -0,0 +1,21 @@
1
+ import type { StatFlushBatch } from '../../ports/stats-buffer';
2
+ import { type StatBatchFenceResult, type StatsStore } from '../../ports/stats-store';
3
+ import type { StatBucket, StatCellRow, StatFilter, StatGranularity, StatSeriesCellRow } from '../../stats.types';
4
+ /**
5
+ * Store in a Map, with the flush log of the port contract. For tests and as the reference behaviour of
6
+ * `StatsStore` (what a SQLite store in an app must do); data is gone with the process.
7
+ */
8
+ export declare class InMemoryStatsStore implements StatsStore {
9
+ readonly rows: Map<string, StatBucket>;
10
+ readonly flushLog: Map<string, {
11
+ state: StatBatchFenceResult;
12
+ at: number;
13
+ }>;
14
+ merge(batch: StatFlushBatch): Promise<void>;
15
+ fence(batchId: string): Promise<StatBatchFenceResult>;
16
+ sumCells(f: StatFilter): Promise<StatCellRow[]>;
17
+ sumSeries(f: StatFilter): Promise<StatSeriesCellRow[]>;
18
+ hasNamespace(namespace: string): Promise<boolean>;
19
+ prune(granularity: StatGranularity, before: Date): Promise<number>;
20
+ pruneFlushLog(before: Date): Promise<number>;
21
+ }
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InMemoryStatsStore = void 0;
4
+ const stat_metrics_1 = require("../../helpers/stat-metrics");
5
+ const stats_store_1 = require("../../ports/stats-store");
6
+ /**
7
+ * Store in a Map, with the flush log of the port contract. For tests and as the reference behaviour of
8
+ * `StatsStore` (what a SQLite store in an app must do); data is gone with the process.
9
+ */
10
+ class InMemoryStatsStore {
11
+ constructor() {
12
+ this.rows = new Map();
13
+ this.flushLog = new Map();
14
+ }
15
+ async merge(batch) {
16
+ const known = this.flushLog.get(batch.id);
17
+ if (known?.state === 'applied')
18
+ return;
19
+ if (known?.state === 'fenced')
20
+ throw new stats_store_1.StatBatchFencedError(batch.id);
21
+ // All or nothing: compute first, then commit.
22
+ const next = new Map();
23
+ for (const b of batch.buckets) {
24
+ const key = (0, stat_metrics_1.statBucketId)(b);
25
+ const cur = next.get(key) ?? this.rows.get(key);
26
+ const row = cur
27
+ ? { ...cur, metrics: (0, stat_metrics_1.addStatMetrics)((0, stat_metrics_1.addStatMetrics)((0, stat_metrics_1.statDict)(), cur.metrics), b.metrics) }
28
+ : { ...b, metrics: (0, stat_metrics_1.addStatMetrics)((0, stat_metrics_1.statDict)(), b.metrics) };
29
+ next.set(key, row);
30
+ }
31
+ for (const [k, v] of next)
32
+ this.rows.set(k, v);
33
+ this.flushLog.set(batch.id, { state: 'applied', at: Date.now() });
34
+ }
35
+ async fence(batchId) {
36
+ const known = this.flushLog.get(batchId);
37
+ if (known)
38
+ return known.state;
39
+ this.flushLog.set(batchId, { state: 'fenced', at: Date.now() });
40
+ return 'fenced';
41
+ }
42
+ async sumCells(f) {
43
+ const sums = new Map();
44
+ for (const b of this.rows.values()) {
45
+ if (!(0, stat_metrics_1.statBucketMatches)(b, f))
46
+ continue;
47
+ const periodStart = b.periodStart.toISOString();
48
+ for (const c of (0, stat_metrics_1.statCellsOf)(b.metrics, f)) {
49
+ const k = JSON.stringify([periodStart, c.value, c.status]);
50
+ const row = sums.get(k);
51
+ if (row)
52
+ row.count += c.count;
53
+ else
54
+ sums.set(k, { periodStart, ...c });
55
+ }
56
+ }
57
+ return [...sums.values()];
58
+ }
59
+ async sumSeries(f) {
60
+ const sums = new Map();
61
+ for (const b of this.rows.values()) {
62
+ if (!(0, stat_metrics_1.statBucketMatches)(b, f))
63
+ continue;
64
+ for (const c of (0, stat_metrics_1.statCellsOf)(b.metrics, f)) {
65
+ const k = JSON.stringify([b.subjectType, b.subjectId, b.seriesKey, c.value, c.status]);
66
+ const row = sums.get(k);
67
+ if (row)
68
+ row.count += c.count;
69
+ else
70
+ sums.set(k, { subjectType: b.subjectType, subjectId: b.subjectId ?? null, seriesKey: b.seriesKey, ...c });
71
+ }
72
+ }
73
+ return [...sums.values()];
74
+ }
75
+ async hasNamespace(namespace) {
76
+ for (const b of this.rows.values())
77
+ if (b.namespace === namespace)
78
+ return true;
79
+ return false;
80
+ }
81
+ async prune(granularity, before) {
82
+ let n = 0;
83
+ for (const [k, b] of this.rows) {
84
+ if (b.granularity === granularity && b.periodStart.getTime() < before.getTime()) {
85
+ this.rows.delete(k);
86
+ n++;
87
+ }
88
+ }
89
+ return n;
90
+ }
91
+ async pruneFlushLog(before) {
92
+ let n = 0;
93
+ for (const [id, e] of this.flushLog) {
94
+ if (e.at < before.getTime()) {
95
+ this.flushLog.delete(id);
96
+ n++;
97
+ }
98
+ }
99
+ return n;
100
+ }
101
+ }
102
+ exports.InMemoryStatsStore = InMemoryStatsStore;