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

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,61 @@
1
+ import { type StatBucket, type StatCounters, type StatFilter, type StatMetrics, type StatSeriesRef, type StatTotals } from '../stats.types';
2
+ /**
3
+ * Keys that would reach `Object.prototype` (or shadow it) when used as a property name. Values and statuses come
4
+ * from callers, so these are dropped at normalization and skipped again wherever a metrics map is built or read.
5
+ */
6
+ export declare const STAT_RESERVED_KEYS: ReadonlySet<string>;
7
+ export declare const isStatReservedKey: (key: string) => boolean;
8
+ /**
9
+ * An empty map with no prototype. Every metrics map, cell and counter map is built with it, so no key can reach
10
+ * `Object.prototype` and no read sees an inherited property. `JSON.stringify` writes it like `{}`.
11
+ */
12
+ export declare const statDict: <T>() => Record<string, T>;
13
+ /** Own property check (`Object.hasOwn` is ES2022, the kit compiles against ES2021). */
14
+ export declare const statHasOwn: (o: object, key: string) => boolean;
15
+ /** `o[key]` only when it is an own property. */
16
+ export declare const statOwn: <T>(o: Record<string, T> | null | undefined, key: string) => T | undefined;
17
+ /** target += delta, cell by cell. Mutates and returns `target`. Reserved keys and non-finite counts are skipped. */
18
+ export declare function addStatMetrics(target: StatMetrics, delta: StatMetrics): StatMetrics;
19
+ /** Deep copy of a metrics object, as prototype-free maps. */
20
+ export declare const cloneStatMetrics: (m: StatMetrics) => StatMetrics;
21
+ /** A one-cell metrics map, built without an object literal keyed by caller data. */
22
+ export declare function statCellMetrics(value: string, status: string, count: number): StatMetrics;
23
+ /**
24
+ * Values and statuses become JSON keys and Redis hash fields: stringify, replace control chars (the field separator
25
+ * among them) with a space, trim, cap. `null` = drop the cell (rule 7), also for `__proto__` / `constructor` /
26
+ * `prototype` (prototype pollution).
27
+ */
28
+ export declare function normalizeStatKey(raw: unknown, max: number): string | null;
29
+ /** Normalized cells of a raw increment; `null` when nothing is left. Deltas for one cell are summed. */
30
+ export declare function normalizeStatMetrics(raw: Record<string, Record<string, number>>): StatMetrics | null;
31
+ /**
32
+ * The series of a write, or `null` when a segment is empty or longer than its column (rule 19): one overlong key
33
+ * would fail its whole store batch on every flush.
34
+ */
35
+ export declare function normalizeStatSeries(p: {
36
+ namespace: string;
37
+ subjectType?: string;
38
+ subjectId?: string | null;
39
+ seriesKey?: string;
40
+ }): StatSeriesRef | null;
41
+ /** Cardinality guard for user-supplied values: a known one or `__other__`. */
42
+ export declare const foldStatValue: (value: string | null, allowed: ReadonlySet<string>) => string | null;
43
+ /** Average of a gauge value in one bucket (`{ sum, n }` from `recordGauge`); `null` when it had no samples. */
44
+ export declare function statGaugeAverage(metrics: StatMetrics, value: string): number | null;
45
+ /** value → sum of its statuses. */
46
+ export declare function flattenStatTotals(totals: StatTotals): StatCounters;
47
+ /** Flat counters of several namespaces of one unit, summed key by key (never object spread). */
48
+ export declare function mergeStatCounters(...parts: StatCounters[]): StatCounters;
49
+ /** In-memory identity of a bucket (never parsed back). */
50
+ export declare const statBucketId: (b: {
51
+ granularity: string;
52
+ periodStart: Date;
53
+ } & StatSeriesRef) => string;
54
+ /** Same test a store applies in SQL; used for unflushed buckets (S4). */
55
+ export declare function statBucketMatches(b: StatBucket, f: StatFilter): boolean;
56
+ /** Cells of `metrics` filtered by the filter's `values` / `statuses`; reserved keys are never yielded. */
57
+ export declare function statCellsOf(metrics: StatMetrics, f: Pick<StatFilter, 'values' | 'statuses'>): Generator<{
58
+ value: string;
59
+ status: string;
60
+ count: number;
61
+ }>;
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.statCellsOf = exports.statBucketMatches = exports.statBucketId = exports.mergeStatCounters = exports.flattenStatTotals = exports.statGaugeAverage = exports.foldStatValue = exports.normalizeStatSeries = exports.normalizeStatMetrics = exports.normalizeStatKey = exports.statCellMetrics = exports.cloneStatMetrics = exports.addStatMetrics = exports.statOwn = exports.statHasOwn = exports.statDict = exports.isStatReservedKey = exports.STAT_RESERVED_KEYS = void 0;
4
+ const stats_constants_1 = require("../stats.constants");
5
+ const stats_types_1 = require("../stats.types");
6
+ /**
7
+ * Keys that would reach `Object.prototype` (or shadow it) when used as a property name. Values and statuses come
8
+ * from callers, so these are dropped at normalization and skipped again wherever a metrics map is built or read.
9
+ */
10
+ exports.STAT_RESERVED_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
11
+ const isStatReservedKey = (key) => exports.STAT_RESERVED_KEYS.has(key);
12
+ exports.isStatReservedKey = isStatReservedKey;
13
+ /**
14
+ * An empty map with no prototype. Every metrics map, cell and counter map is built with it, so no key can reach
15
+ * `Object.prototype` and no read sees an inherited property. `JSON.stringify` writes it like `{}`.
16
+ */
17
+ const statDict = () => Object.create(null);
18
+ exports.statDict = statDict;
19
+ /** Own property check (`Object.hasOwn` is ES2022, the kit compiles against ES2021). */
20
+ const statHasOwn = (o, key) => Object.prototype.hasOwnProperty.call(o, key);
21
+ exports.statHasOwn = statHasOwn;
22
+ /** `o[key]` only when it is an own property. */
23
+ const statOwn = (o, key) => o && (0, exports.statHasOwn)(o, key) ? o[key] : undefined;
24
+ exports.statOwn = statOwn;
25
+ /** target += delta, cell by cell. Mutates and returns `target`. Reserved keys and non-finite counts are skipped. */
26
+ function addStatMetrics(target, delta) {
27
+ for (const [value, statuses] of Object.entries(delta ?? {})) {
28
+ if ((0, exports.isStatReservedKey)(value) || !statuses || typeof statuses !== 'object')
29
+ continue;
30
+ let cell = (0, exports.statOwn)(target, value);
31
+ for (const [status, count] of Object.entries(statuses)) {
32
+ if ((0, exports.isStatReservedKey)(status) || typeof count !== 'number' || !Number.isFinite(count))
33
+ continue;
34
+ if (!cell)
35
+ target[value] = cell = (0, exports.statDict)();
36
+ cell[status] = ((0, exports.statOwn)(cell, status) ?? 0) + count;
37
+ }
38
+ }
39
+ return target;
40
+ }
41
+ exports.addStatMetrics = addStatMetrics;
42
+ /** Deep copy of a metrics object, as prototype-free maps. */
43
+ const cloneStatMetrics = (m) => addStatMetrics((0, exports.statDict)(), m);
44
+ exports.cloneStatMetrics = cloneStatMetrics;
45
+ /** A one-cell metrics map, built without an object literal keyed by caller data. */
46
+ function statCellMetrics(value, status, count) {
47
+ const out = (0, exports.statDict)();
48
+ if ((0, exports.isStatReservedKey)(value) || (0, exports.isStatReservedKey)(status))
49
+ return out;
50
+ const cell = (0, exports.statDict)();
51
+ cell[status] = count;
52
+ out[value] = cell;
53
+ return out;
54
+ }
55
+ exports.statCellMetrics = statCellMetrics;
56
+ /**
57
+ * Values and statuses become JSON keys and Redis hash fields: stringify, replace control chars (the field separator
58
+ * among them) with a space, trim, cap. `null` = drop the cell (rule 7), also for `__proto__` / `constructor` /
59
+ * `prototype` (prototype pollution).
60
+ */
61
+ function normalizeStatKey(raw, max) {
62
+ if (raw === undefined || raw === null || raw === '')
63
+ return null;
64
+ const text = (typeof raw === 'object' ? JSON.stringify(raw) : String(raw))
65
+ // eslint-disable-next-line no-control-regex
66
+ .replace(/[\u0000-\u001f\u007f]/g, ' ')
67
+ .trim()
68
+ .slice(0, max);
69
+ return text && !(0, exports.isStatReservedKey)(text) ? text : null;
70
+ }
71
+ exports.normalizeStatKey = normalizeStatKey;
72
+ /** Normalized cells of a raw increment; `null` when nothing is left. Deltas for one cell are summed. */
73
+ function normalizeStatMetrics(raw) {
74
+ const out = (0, exports.statDict)();
75
+ let any = false;
76
+ for (const [rawValue, statuses] of Object.entries(raw ?? {})) {
77
+ const value = normalizeStatKey(rawValue, stats_constants_1.STAT_LIMITS.value);
78
+ if (value === null || !statuses || typeof statuses !== 'object')
79
+ continue;
80
+ for (const [rawStatus, delta] of Object.entries(statuses)) {
81
+ const status = normalizeStatKey(rawStatus, stats_constants_1.STAT_LIMITS.status);
82
+ if (status === null || typeof delta !== 'number' || !Number.isFinite(delta) || delta === 0)
83
+ continue;
84
+ const cell = (0, exports.statOwn)(out, value) ?? (out[value] = (0, exports.statDict)());
85
+ cell[status] = ((0, exports.statOwn)(cell, status) ?? 0) + delta;
86
+ any = true;
87
+ }
88
+ }
89
+ return any ? out : null;
90
+ }
91
+ exports.normalizeStatMetrics = normalizeStatMetrics;
92
+ /**
93
+ * The series of a write, or `null` when a segment is empty or longer than its column (rule 19): one overlong key
94
+ * would fail its whole store batch on every flush.
95
+ */
96
+ function normalizeStatSeries(p) {
97
+ const series = {
98
+ namespace: p.namespace,
99
+ subjectType: p.subjectType ?? stats_types_1.STAT_SUBJECT_NONE,
100
+ subjectId: p.subjectId === undefined || p.subjectId === '' ? null : p.subjectId,
101
+ seriesKey: p.seriesKey ?? '',
102
+ };
103
+ const ok = typeof series.namespace === 'string' &&
104
+ series.namespace.length > 0 &&
105
+ series.namespace.length <= stats_constants_1.STAT_LIMITS.namespace &&
106
+ typeof series.subjectType === 'string' &&
107
+ series.subjectType.length > 0 &&
108
+ series.subjectType.length <= stats_constants_1.STAT_LIMITS.subjectType &&
109
+ (series.subjectId === null ||
110
+ (typeof series.subjectId === 'string' && series.subjectId.length <= stats_constants_1.STAT_LIMITS.subjectId)) &&
111
+ typeof series.seriesKey === 'string' &&
112
+ series.seriesKey.length <= stats_constants_1.STAT_LIMITS.seriesKey;
113
+ return ok ? series : null;
114
+ }
115
+ exports.normalizeStatSeries = normalizeStatSeries;
116
+ /** Cardinality guard for user-supplied values: a known one or `__other__`. */
117
+ const foldStatValue = (value, allowed) => value === null ? null : allowed.has(value) ? value : stats_constants_1.STAT_OTHER_VALUE;
118
+ exports.foldStatValue = foldStatValue;
119
+ /** Average of a gauge value in one bucket (`{ sum, n }` from `recordGauge`); `null` when it had no samples. */
120
+ function statGaugeAverage(metrics, value) {
121
+ const cell = (0, exports.statOwn)(metrics, value);
122
+ const count = (0, exports.statOwn)(cell, stats_constants_1.STAT_GAUGE_COUNT) ?? 0;
123
+ return count > 0 ? ((0, exports.statOwn)(cell, stats_constants_1.STAT_GAUGE_SUM) ?? 0) / count : null;
124
+ }
125
+ exports.statGaugeAverage = statGaugeAverage;
126
+ function flatten(m) {
127
+ const out = (0, exports.statDict)();
128
+ for (const [value, statuses] of Object.entries(m ?? {})) {
129
+ if ((0, exports.isStatReservedKey)(value) || !statuses)
130
+ continue;
131
+ let sum = 0;
132
+ for (const [status, count] of Object.entries(statuses))
133
+ if (!(0, exports.isStatReservedKey)(status))
134
+ sum += count;
135
+ out[value] = sum;
136
+ }
137
+ return out;
138
+ }
139
+ /** value → sum of its statuses. */
140
+ function flattenStatTotals(totals) {
141
+ return { today: flatten(totals.today), total: flatten(totals.total) };
142
+ }
143
+ exports.flattenStatTotals = flattenStatTotals;
144
+ /** Flat counters of several namespaces of one unit, summed key by key (never object spread). */
145
+ function mergeStatCounters(...parts) {
146
+ const out = { today: (0, exports.statDict)(), total: (0, exports.statDict)() };
147
+ for (const part of parts) {
148
+ for (const period of ['today', 'total']) {
149
+ for (const [key, count] of Object.entries(part?.[period] ?? {})) {
150
+ if (!(0, exports.isStatReservedKey)(key))
151
+ out[period][key] = ((0, exports.statOwn)(out[period], key) ?? 0) + count;
152
+ }
153
+ }
154
+ }
155
+ return out;
156
+ }
157
+ exports.mergeStatCounters = mergeStatCounters;
158
+ /** In-memory identity of a bucket (never parsed back). */
159
+ const statBucketId = (b) => JSON.stringify([b.namespace, b.subjectType, b.subjectId, b.seriesKey, b.granularity, b.periodStart.getTime()]);
160
+ exports.statBucketId = statBucketId;
161
+ /** Same test a store applies in SQL; used for unflushed buckets (S4). */
162
+ function statBucketMatches(b, f) {
163
+ if (b.namespace !== f.namespace || b.granularity !== f.granularity)
164
+ return false;
165
+ if (f.subjectType !== undefined && b.subjectType !== f.subjectType)
166
+ return false;
167
+ if (f.subjectId !== undefined && (b.subjectId ?? null) !== (f.subjectId ?? null))
168
+ return false;
169
+ if (f.seriesKey !== undefined && b.seriesKey !== f.seriesKey)
170
+ return false;
171
+ const t = b.periodStart.getTime();
172
+ if (f.from && t < f.from.getTime())
173
+ return false;
174
+ if (f.to && t >= f.to.getTime())
175
+ return false;
176
+ return true;
177
+ }
178
+ exports.statBucketMatches = statBucketMatches;
179
+ /** Cells of `metrics` filtered by the filter's `values` / `statuses`; reserved keys are never yielded. */
180
+ function* statCellsOf(metrics, f) {
181
+ const values = f.values?.length ? new Set(f.values) : null;
182
+ const statuses = f.statuses?.length ? new Set(f.statuses) : null;
183
+ for (const [value, cell] of Object.entries(metrics ?? {})) {
184
+ if ((0, exports.isStatReservedKey)(value) || !cell || (values && !values.has(value)))
185
+ continue;
186
+ for (const [status, count] of Object.entries(cell)) {
187
+ if ((0, exports.isStatReservedKey)(status) || (statuses && !statuses.has(status)))
188
+ continue;
189
+ yield { value, status, count };
190
+ }
191
+ }
192
+ }
193
+ exports.statCellsOf = statCellsOf;
@@ -0,0 +1,22 @@
1
+ import { StatGranularity } from '../stats.types';
2
+ /** UTC start of the bucket that holds `date`. Week = ISO week, Monday 00:00 UTC. */
3
+ export declare function statPeriodStart(date: Date | number | string, granularity: StatGranularity): Date;
4
+ /** Start of the bucket after the one starting at `start` (which must be a bucket start). */
5
+ export declare function statNextPeriodStart(start: Date, granularity: StatGranularity): Date;
6
+ /**
7
+ * Number of buckets `statPeriodRange(from, to, granularity)` yields without a limit, computed without allocating
8
+ * or looping (fixed-length periods by division, months by calendar arithmetic). Check it before building a range.
9
+ */
10
+ export declare function statPeriodCount(from: Date | string, to: Date | string, granularity: StatGranularity): number;
11
+ /** Bucket starts in [from, to); `from` is floored. Capped at `limit` so a bad request can't allocate millions. */
12
+ export declare function statPeriodRange(from: Date | string, to: Date | string, granularity: StatGranularity, limit?: number): Date[];
13
+ /** The last `n` buckets including the current one: 24 × hour = 24 points, not 25. */
14
+ export declare function statLastPeriods(n: number, granularity: StatGranularity, now?: Date): {
15
+ from: Date;
16
+ to: Date;
17
+ };
18
+ /** [start, end) cut at every bucket boundary of `granularity`: one piece per bucket, each with its own ms. */
19
+ export declare function splitStatSpan(start: Date, end: Date, granularity: StatGranularity): {
20
+ at: Date;
21
+ ms: number;
22
+ }[];
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.splitStatSpan = exports.statLastPeriods = exports.statPeriodRange = exports.statPeriodCount = exports.statNextPeriodStart = exports.statPeriodStart = void 0;
4
+ const stats_types_1 = require("../stats.types");
5
+ const MIN = 60_000;
6
+ const HOUR = 60 * MIN;
7
+ const DAY = 24 * HOUR;
8
+ /** UTC start of the bucket that holds `date`. Week = ISO week, Monday 00:00 UTC. */
9
+ function statPeriodStart(date, granularity) {
10
+ const t = new Date(date).getTime();
11
+ switch (granularity) {
12
+ case stats_types_1.StatGranularity.MINUTE:
13
+ return new Date(Math.floor(t / MIN) * MIN);
14
+ case stats_types_1.StatGranularity.HOUR:
15
+ return new Date(Math.floor(t / HOUR) * HOUR);
16
+ case stats_types_1.StatGranularity.DAY:
17
+ return new Date(Math.floor(t / DAY) * DAY);
18
+ case stats_types_1.StatGranularity.WEEK: {
19
+ const day = new Date(Math.floor(t / DAY) * DAY);
20
+ return new Date(day.getTime() - ((day.getUTCDay() + 6) % 7) * DAY);
21
+ }
22
+ case stats_types_1.StatGranularity.MONTH: {
23
+ const d = new Date(t);
24
+ return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1));
25
+ }
26
+ default:
27
+ throw new Error(`Unknown stat granularity: ${granularity}`);
28
+ }
29
+ }
30
+ exports.statPeriodStart = statPeriodStart;
31
+ /** Start of the bucket after the one starting at `start` (which must be a bucket start). */
32
+ function statNextPeriodStart(start, granularity) {
33
+ switch (granularity) {
34
+ case stats_types_1.StatGranularity.MINUTE:
35
+ return new Date(start.getTime() + MIN);
36
+ case stats_types_1.StatGranularity.HOUR:
37
+ return new Date(start.getTime() + HOUR);
38
+ case stats_types_1.StatGranularity.DAY:
39
+ return new Date(start.getTime() + DAY);
40
+ case stats_types_1.StatGranularity.WEEK:
41
+ return new Date(start.getTime() + 7 * DAY);
42
+ case stats_types_1.StatGranularity.MONTH:
43
+ return new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 1));
44
+ default:
45
+ throw new Error(`Unknown stat granularity: ${granularity}`);
46
+ }
47
+ }
48
+ exports.statNextPeriodStart = statNextPeriodStart;
49
+ /**
50
+ * Number of buckets `statPeriodRange(from, to, granularity)` yields without a limit, computed without allocating
51
+ * or looping (fixed-length periods by division, months by calendar arithmetic). Check it before building a range.
52
+ */
53
+ function statPeriodCount(from, to, granularity) {
54
+ const start = statPeriodStart(from, granularity);
55
+ const end = new Date(to).getTime();
56
+ if (!Number.isFinite(start.getTime()) || !Number.isFinite(end) || end <= start.getTime())
57
+ return 0;
58
+ if (granularity === stats_types_1.StatGranularity.MONTH) {
59
+ const e = new Date(end);
60
+ const months = (e.getUTCFullYear() - start.getUTCFullYear()) * 12 + (e.getUTCMonth() - start.getUTCMonth());
61
+ // `end` inside a month (not at its first instant) adds that month.
62
+ const endAtMonthStart = Date.UTC(e.getUTCFullYear(), e.getUTCMonth(), 1) === end;
63
+ return months + (endAtMonthStart ? 0 : 1);
64
+ }
65
+ const len = granularity === stats_types_1.StatGranularity.MINUTE
66
+ ? MIN
67
+ : granularity === stats_types_1.StatGranularity.HOUR
68
+ ? HOUR
69
+ : granularity === stats_types_1.StatGranularity.DAY
70
+ ? DAY
71
+ : 7 * DAY;
72
+ return Math.ceil((end - start.getTime()) / len);
73
+ }
74
+ exports.statPeriodCount = statPeriodCount;
75
+ /** Bucket starts in [from, to); `from` is floored. Capped at `limit` so a bad request can't allocate millions. */
76
+ function statPeriodRange(from, to, granularity, limit = 5_000) {
77
+ const end = new Date(to).getTime();
78
+ const out = [];
79
+ for (let cur = statPeriodStart(from, granularity); cur.getTime() < end && out.length < limit; cur = statNextPeriodStart(cur, granularity)) {
80
+ out.push(cur);
81
+ }
82
+ return out;
83
+ }
84
+ exports.statPeriodRange = statPeriodRange;
85
+ /** The last `n` buckets including the current one: 24 × hour = 24 points, not 25. */
86
+ function statLastPeriods(n, granularity, now = new Date()) {
87
+ const current = statPeriodStart(now, granularity);
88
+ let from = current;
89
+ for (let i = 1; i < n; i++)
90
+ from = statPeriodStart(new Date(from.getTime() - 1), granularity);
91
+ return { from, to: statNextPeriodStart(current, granularity) };
92
+ }
93
+ exports.statLastPeriods = statLastPeriods;
94
+ /** [start, end) cut at every bucket boundary of `granularity`: one piece per bucket, each with its own ms. */
95
+ function splitStatSpan(start, end, granularity) {
96
+ const pieces = [];
97
+ for (let cur = start; cur.getTime() < end.getTime();) {
98
+ const boundary = statNextPeriodStart(statPeriodStart(cur, granularity), granularity).getTime();
99
+ const next = new Date(Math.min(end.getTime(), boundary));
100
+ pieces.push({ at: cur, ms: next.getTime() - cur.getTime() });
101
+ cur = next;
102
+ }
103
+ return pieces;
104
+ }
105
+ exports.splitStatSpan = splitStatSpan;
@@ -0,0 +1,16 @@
1
+ import type { StatCellRow, StatGranularity, StatTimeline } from '../stats.types';
2
+ /**
3
+ * Timeline projection in code (rule 10): rank values by their total over all statuses, keep the top `limit`
4
+ * (`truncated` when cut), one point per bucket in `buckets`, empty buckets included. Rows of one bucket / value /
5
+ * status may repeat (store + unflushed deltas): they are summed. Rows with a reserved key (`__proto__`, …) are
6
+ * skipped; every map in the result has no prototype.
7
+ */
8
+ export declare function buildStatTimeline(p: {
9
+ namespace: string;
10
+ granularity: StatGranularity;
11
+ buckets: Date[];
12
+ from: Date;
13
+ to: Date;
14
+ rows: StatCellRow[];
15
+ limit?: number;
16
+ }): StatTimeline;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildStatTimeline = void 0;
4
+ const stats_constants_1 = require("../stats.constants");
5
+ const stat_metrics_1 = require("./stat-metrics");
6
+ /** cell += count in a prototype-free map. */
7
+ function addCell(target, value, status, count) {
8
+ const cell = (0, stat_metrics_1.statOwn)(target, value) ?? (target[value] = (0, stat_metrics_1.statDict)());
9
+ cell[status] = ((0, stat_metrics_1.statOwn)(cell, status) ?? 0) + count;
10
+ }
11
+ /**
12
+ * Timeline projection in code (rule 10): rank values by their total over all statuses, keep the top `limit`
13
+ * (`truncated` when cut), one point per bucket in `buckets`, empty buckets included. Rows of one bucket / value /
14
+ * status may repeat (store + unflushed deltas): they are summed. Rows with a reserved key (`__proto__`, …) are
15
+ * skipped; every map in the result has no prototype.
16
+ */
17
+ function buildStatTimeline(p) {
18
+ const rows = p.rows.filter((r) => !(0, stat_metrics_1.isStatReservedKey)(r.value) && !(0, stat_metrics_1.isStatReservedKey)(r.status));
19
+ const totals = (0, stat_metrics_1.statDict)();
20
+ const byValue = new Map();
21
+ const statuses = new Set();
22
+ for (const r of rows) {
23
+ addCell(totals, r.value, r.status, r.count);
24
+ byValue.set(r.value, (byValue.get(r.value) ?? 0) + r.count);
25
+ statuses.add(r.status);
26
+ }
27
+ // Ties keep a stable order by name, so a chart doesn't reshuffle between equal values.
28
+ const ranked = [...byValue.entries()]
29
+ .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
30
+ .map(([v]) => v);
31
+ const values = ranked.slice(0, Math.max(0, p.limit ?? stats_constants_1.STAT_DEFAULT_VALUE_LIMIT));
32
+ const kept = new Set(values);
33
+ const byPeriod = new Map();
34
+ for (const r of rows) {
35
+ if (!kept.has(r.value))
36
+ continue;
37
+ const ms = new Date(r.periodStart).getTime();
38
+ let point = byPeriod.get(ms);
39
+ if (!point)
40
+ byPeriod.set(ms, (point = (0, stat_metrics_1.statDict)()));
41
+ addCell(point, r.value, r.status, r.count);
42
+ }
43
+ const keptTotals = (0, stat_metrics_1.statDict)();
44
+ for (const v of values)
45
+ keptTotals[v] = (0, stat_metrics_1.statOwn)(totals, v) ?? (0, stat_metrics_1.statDict)();
46
+ return {
47
+ namespace: p.namespace,
48
+ granularity: p.granularity,
49
+ from: p.from.toISOString(),
50
+ to: p.to.toISOString(),
51
+ values,
52
+ statuses: [...statuses].sort(),
53
+ totals: keptTotals,
54
+ truncated: ranked.length > values.length,
55
+ points: p.buckets.map((b) => ({ periodStart: b.toISOString(), metrics: byPeriod.get(b.getTime()) ?? (0, stat_metrics_1.statDict)() })),
56
+ };
57
+ }
58
+ exports.buildStatTimeline = buildStatTimeline;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Calendar math in an IANA timezone over `Intl` (no process TZ, no deps). Used by `StatsService.localDays`.
3
+ */
4
+ interface ZonedParts {
5
+ year: number;
6
+ month: number;
7
+ day: number;
8
+ hour: number;
9
+ minute: number;
10
+ second: number;
11
+ }
12
+ export declare function zonedParts(at: Date, timeZone: string): ZonedParts;
13
+ /** Offset of `timeZone` from UTC at the instant `at`, in ms (Kyiv in winter → +7_200_000). */
14
+ export declare function zonedOffsetMs(at: Date, timeZone: string): number;
15
+ /** `YYYY-MM-DD` of the instant in the timezone. */
16
+ export declare function zonedDateKey(at: Date, timeZone: string): string;
17
+ /** The instant of local midnight of the calendar day `year-month-day` (month 1-based; overflow is normalized). */
18
+ export declare function zonedMidnight(year: number, month: number, day: number, timeZone: string): Date;
19
+ export {};
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ /**
3
+ * Calendar math in an IANA timezone over `Intl` (no process TZ, no deps). Used by `StatsService.localDays`.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.zonedMidnight = exports.zonedDateKey = exports.zonedOffsetMs = exports.zonedParts = void 0;
7
+ const formatters = new Map();
8
+ function formatter(timeZone) {
9
+ let f = formatters.get(timeZone);
10
+ if (!f) {
11
+ // Throws RangeError on an unknown zone — that is the validation.
12
+ f = new Intl.DateTimeFormat('en-US', {
13
+ timeZone,
14
+ hourCycle: 'h23',
15
+ year: 'numeric',
16
+ month: '2-digit',
17
+ day: '2-digit',
18
+ hour: '2-digit',
19
+ minute: '2-digit',
20
+ second: '2-digit',
21
+ });
22
+ formatters.set(timeZone, f);
23
+ }
24
+ return f;
25
+ }
26
+ function zonedParts(at, timeZone) {
27
+ const parts = {};
28
+ for (const p of formatter(timeZone).formatToParts(at)) {
29
+ if (p.type !== 'literal')
30
+ parts[p.type] = Number(p.value);
31
+ }
32
+ return {
33
+ year: parts.year,
34
+ month: parts.month,
35
+ day: parts.day,
36
+ hour: parts.hour === 24 ? 0 : parts.hour,
37
+ minute: parts.minute,
38
+ second: parts.second,
39
+ };
40
+ }
41
+ exports.zonedParts = zonedParts;
42
+ /** Offset of `timeZone` from UTC at the instant `at`, in ms (Kyiv in winter → +7_200_000). */
43
+ function zonedOffsetMs(at, timeZone) {
44
+ const p = zonedParts(at, timeZone);
45
+ const asUtc = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second);
46
+ return asUtc - Math.floor(at.getTime() / 1000) * 1000;
47
+ }
48
+ exports.zonedOffsetMs = zonedOffsetMs;
49
+ /** `YYYY-MM-DD` of the instant in the timezone. */
50
+ function zonedDateKey(at, timeZone) {
51
+ const p = zonedParts(at, timeZone);
52
+ return `${p.year}-${String(p.month).padStart(2, '0')}-${String(p.day).padStart(2, '0')}`;
53
+ }
54
+ exports.zonedDateKey = zonedDateKey;
55
+ /** The instant of local midnight of the calendar day `year-month-day` (month 1-based; overflow is normalized). */
56
+ function zonedMidnight(year, month, day, timeZone) {
57
+ const guess = Date.UTC(year, month - 1, day);
58
+ // Two passes: the offset at the guessed instant may differ from the one at the real midnight (DST).
59
+ let t = guess - zonedOffsetMs(new Date(guess), timeZone);
60
+ t = guess - zonedOffsetMs(new Date(t), timeZone);
61
+ return new Date(t);
62
+ }
63
+ exports.zonedMidnight = zonedMidnight;
@@ -0,0 +1,19 @@
1
+ export * from './stats.types';
2
+ export * from './stats.constants';
3
+ export * from './helpers/stat-period';
4
+ export * from './helpers/stat-metrics';
5
+ export * from './helpers/stat-timeline';
6
+ export { zonedDateKey, zonedMidnight, zonedOffsetMs } from './helpers/stat-zoned';
7
+ export * from './ports/stats-buffer';
8
+ export * from './ports/stats-store';
9
+ export * from './buffers/memory-stats-buffer';
10
+ export * from './buffers/redis-stats-buffer';
11
+ export * from './stores/memory/in-memory-stats-store';
12
+ export * from './stores/typeorm/metric-snapshot.entity';
13
+ export * from './stores/typeorm/metric-snapshots.migration';
14
+ export * from './stores/typeorm/typeorm-stats-store';
15
+ export * from './stats.options';
16
+ export * from './stats.service';
17
+ export * from './stats.scheduler';
18
+ export * from './stats.jobs';
19
+ export * from './stats.module';
package/dist/index.js ADDED
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.zonedOffsetMs = exports.zonedMidnight = exports.zonedDateKey = void 0;
18
+ // Stats engine (skill `nestjs-stats`): series × granularity buckets, delta buffer → additive store, timelines.
19
+ __exportStar(require("./stats.types"), exports);
20
+ __exportStar(require("./stats.constants"), exports);
21
+ __exportStar(require("./helpers/stat-period"), exports);
22
+ __exportStar(require("./helpers/stat-metrics"), exports);
23
+ __exportStar(require("./helpers/stat-timeline"), exports);
24
+ var stat_zoned_1 = require("./helpers/stat-zoned");
25
+ Object.defineProperty(exports, "zonedDateKey", { enumerable: true, get: function () { return stat_zoned_1.zonedDateKey; } });
26
+ Object.defineProperty(exports, "zonedMidnight", { enumerable: true, get: function () { return stat_zoned_1.zonedMidnight; } });
27
+ Object.defineProperty(exports, "zonedOffsetMs", { enumerable: true, get: function () { return stat_zoned_1.zonedOffsetMs; } });
28
+ __exportStar(require("./ports/stats-buffer"), exports);
29
+ __exportStar(require("./ports/stats-store"), exports);
30
+ __exportStar(require("./buffers/memory-stats-buffer"), exports);
31
+ __exportStar(require("./buffers/redis-stats-buffer"), exports);
32
+ __exportStar(require("./stores/memory/in-memory-stats-store"), exports);
33
+ __exportStar(require("./stores/typeorm/metric-snapshot.entity"), exports);
34
+ __exportStar(require("./stores/typeorm/metric-snapshots.migration"), exports);
35
+ __exportStar(require("./stores/typeorm/typeorm-stats-store"), exports);
36
+ __exportStar(require("./stats.options"), exports);
37
+ __exportStar(require("./stats.service"), exports);
38
+ __exportStar(require("./stats.scheduler"), exports);
39
+ __exportStar(require("./stats.jobs"), exports);
40
+ __exportStar(require("./stats.module"), exports);
@@ -0,0 +1,37 @@
1
+ import type { StatBucket } from '../stats.types';
2
+ /**
3
+ * Buckets taken out of a buffer for one store write.
4
+ *
5
+ * - `id` is the batch's idempotency key in the store: the same batch may be written again after a crash or a lost
6
+ * ack, and the store must apply it at most once.
7
+ * - `claim` is the current owner's token. A batch taken over by another flusher (`reclaim`) gets a new claim; the
8
+ * old owner's `ack` / `restore` then become no-ops.
9
+ */
10
+ export interface StatFlushBatch {
11
+ id: string;
12
+ claim: string;
13
+ buckets: StatBucket[];
14
+ }
15
+ /**
16
+ * Hot-path buffer port: holds **deltas** (what was written since the last flush), never totals.
17
+ *
18
+ * Contract:
19
+ * - `add` adds deltas to open buckets. It may throw / reject; `StatsService` catches (a write never breaks the
20
+ * caller). No store I/O.
21
+ * - `take` atomically removes up to `maxBuckets` open buckets and returns them as one in-flight batch. A bucket is
22
+ * taken by exactly one caller, even with several processes on one shared buffer. New writes to the same bucket
23
+ * start a fresh delta. Returns `null` when nothing is open.
24
+ * - `reclaim` hands over in-flight batches older than `staleMs` (their flusher died or hangs) under a new claim.
25
+ * - `ack` drops a batch the store has applied. `restore` adds its deltas back into the open buckets (the store
26
+ * definitely did not apply it). Both do nothing and return `false` when the claim is no longer the owner's.
27
+ * - `unflushed` (optional) lists open + in-flight buckets for reads that must include the last unflushed minute
28
+ * (single-process buffers; a shared buffer leaves it out).
29
+ */
30
+ export interface StatsBuffer {
31
+ add(buckets: StatBucket[]): void | Promise<void>;
32
+ take(maxBuckets: number): Promise<StatFlushBatch | null>;
33
+ reclaim(staleMs: number): Promise<StatFlushBatch[]>;
34
+ ack(batch: StatFlushBatch): Promise<boolean>;
35
+ restore(batch: StatFlushBatch): Promise<boolean>;
36
+ unflushed?(): Iterable<StatBucket>;
37
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });