@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sabationok
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,166 @@
1
- # Temporary Holding Version
1
+ # @my-nestjs-kit/stats — stats engine
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ```sh
4
+ npm i @my-nestjs-kit/stats
5
+ ```
6
+
7
+ Peers: `@nestjs/common`, `rxjs`, `typeorm` (the TypeORM store and its entities are part of the entry). Implements the global skill `nestjs-stats`, with one deliberate change:
8
+ the flush moves **deltas** and the store **adds** them (see "Flush" below).
9
+
10
+ A domain-free timeline engine. Any module records `namespace + subject + value → status → number`; a buffer holds
11
+ the deltas; a scheduled flush adds them into one store table; reads turn the table into gap-filled timelines. The
12
+ engine knows no business words: the app picks namespaces, values and statuses.
13
+
14
+ ## Model
15
+
16
+ | Term | Meaning |
17
+ |---|---|
18
+ | namespace | free string; defines what values / statuses mean and their unit (one unit per namespace) |
19
+ | subject | `subjectType` + `subjectId` (polymorphic, no FK); `none` + `null` = global |
20
+ | seriesKey | optional extra split inside one subject; `''` when unused |
21
+ | metrics | `Record<value, Record<status, number>>` per bucket |
22
+ | granularity | `min` · `hour` · `day` · `week` (ISO, Monday) · `month`, all UTC |
23
+ | bucket | series × granularity × `periodStart` |
24
+
25
+ ## Wiring
26
+
27
+ One engine, two ports. Pick the buffer by how many processes write, the store by where totals live.
28
+
29
+ ```ts
30
+ // Several instances (Redis + Postgres)
31
+ StatsModule.forRootAsync({
32
+ inject: [STATS_REDIS, DataSource, ConfigService],
33
+ useFactory: (redis: Redis, ds: DataSource, cfg: ConfigService) => ({
34
+ buffer: new RedisStatsBuffer(redis, { prefix: `${cfg.getOrThrow('REDIS_PREFIX')}:stats` }),
35
+ store: new TypeOrmStatsStore(ds),
36
+ granularities: [StatGranularity.HOUR, StatGranularity.DAY], // default for writes that don't name them
37
+ }),
38
+ });
39
+
40
+ // One process (memory + the app's own store, e.g. SQLite)
41
+ StatsModule.forRoot({ buffer: new MemoryStatsBuffer(), store: new SqliteStatsStore(db) });
42
+ ```
43
+
44
+ - **Redis client:** a dedicated one (`new Redis(url, { enableOfflineQueue: false, maxRetriesPerRequest: 1 })`), so
45
+ an outage drops metrics instead of buffering them; the app opens it and closes it in `onApplicationShutdown`. The
46
+ kit never opens connections. Redis must not evict (`maxmemory-policy noeviction`); AOF on is still advised (a
47
+ crash loses the unflushed minute, it no longer corrupts totals).
48
+ - **Prefix:** required, from `REDIS_PREFIX` (skill `local-infra`): `webhooxy:stats` → `webhooxy:stats:b:…`,
49
+ `…:dirty`, `…:inflight`, `…:claims`, `…:batch:<id>`. On Redis Cluster wrap it in a hash tag (`{webhooxy:stats}`).
50
+ - **Entity + migration (Postgres 15+):** add `MetricSnapshotEntity` and `MetricSnapshotFlushEntity` to the
51
+ DataSource, and one migration file in the app:
52
+ `export class MetricSnapshots1764300000000 extends MetricSnapshotsMigrationBase { name = 'MetricSnapshots1764300000000' }`.
53
+ An app that already has `metric_snapshots` runs only `METRIC_SNAPSHOT_FLUSHES_UP_SQL`. `migration:generate`
54
+ can't see `NULLS NOT DISTINCT` and proposes dropping the unique constraint: delete those lines.
55
+ - **Shutdown:** `app.enableShutdownHooks()` in `main.ts`; the module flushes in `beforeApplicationShutdown`. Exit
56
+ paths send `SIGTERM` / `await app.close()`, never `process.exit()`.
57
+
58
+ ### Options (`StatsModuleOptions`)
59
+
60
+ | Option | Default | |
61
+ |---|---|---|
62
+ | `buffer`, `store` | required | port instances |
63
+ | `granularities` | all five | for writes that don't name theirs |
64
+ | `retention` | `{ min: 2 d, hour: 90 d }` | ms per granularity, merged over defaults; `null` = forever |
65
+ | `flushEveryMs` | `60_000` | `false` when the app schedules `flush()` (BullMQ) |
66
+ | `pruneEveryMs` | 1 h | `false` to schedule `prune()` yourself |
67
+ | `flushOnShutdown` | `true` | |
68
+ | `batchSize` / `maxBatchesPerFlush` | 500 / 100 | buckets per store transaction / batches per flush call |
69
+ | `staleBatchMs` | 5 min | in-flight batches older than this are taken over |
70
+ | `flushLogRetentionMs` | 30 d | flush-log rows kept for idempotency |
71
+
72
+ `isGlobal` (default true) on `forRoot` / `forRootAsync`.
73
+
74
+ **BullMQ instead of the interval:** `flushEveryMs: false, pruneEveryMs: false`, then `upsertStatsJobSchedulers(queue)`
75
+ once and `runStatsJob(stats, job.name)` in the app's processor. The queue name carries the app prefix. No BullMQ is
76
+ needed for correctness: every instance may run the interval.
77
+
78
+ ## `StatsService`
79
+
80
+ | Method | |
81
+ |---|---|
82
+ | `increment({ namespace, subjectType?, subjectId?, seriesKey?, metrics, granularities?, at? })` | hot path, buffer only; never rejects |
83
+ | `recordGauge({ …series, values: { cpu: 37 } })` | writes `{ sum, n }`; read with `statGaugeAverage(metrics, 'cpu')` |
84
+ | `incrementDuration({ …series, value, status = 'seconds', start, end })` | split by `splitStatSpan`, each bucket gets its own seconds |
85
+ | `flush()` → `{ batches, buckets, error? }` | never rejects; concurrent calls in one process share one run |
86
+ | `prune(now?)` | retention + flush-log cleanup |
87
+ | `timeline({ namespace, granularity, from, to, subjectType?, subjectId?, seriesKey?, values?, statuses?, limit? })` | gap-filled, top-N + `truncated`, max 5000 points; 400 on `subjectId` without `subjectType` |
88
+ | `totals(series, now?)` / `seriesTotals(series, now?)` | today (UTC) + all time from `day` buckets; per series for rule 27 |
89
+ | `localDays({ …series, days, timeZone, granularity?, now? })` | days of an IANA zone from `hour` (or `min`) buckets |
90
+ | `hasNamespace(ns)` | backfill guard |
91
+ | `changed$` | `{ type: 'write' \| 'flush', namespaces }` |
92
+
93
+ Values and statuses are normalized (control chars → space, trimmed, capped 128 / 64); a series segment longer than
94
+ its column (namespace 255, subjectType 64, subjectId 255, seriesKey 255) drops the write. Reads include the
95
+ buffer's unflushed buckets when it exposes them (`MemoryStatsBuffer` does; the Redis buffer doesn't, so a cluster's
96
+ charts lag by up to one flush interval). Authenticate and scope the read routes in the app (rule 13).
97
+
98
+ Untrusted keys: a value or status of `__proto__`, `constructor` or `prototype` (`STAT_RESERVED_KEYS`) is dropped
99
+ at normalization and skipped wherever cells are folded or read (buffer parse, store rows, timeline). Every metrics
100
+ or counter map the entry returns has no prototype (`statDict()`, `Object.create(null)`), and reads check own
101
+ properties only (`statOwn`). It serializes to JSON like a plain object, but has no `hasOwnProperty` / `toString` methods of its own.
102
+ A SQLite store in an app builds its maps the same way (`cloneStatMetrics`, `addStatMetrics`).
103
+
104
+ Caps: `timeline` and `localDays` count their buckets by arithmetic (`statPeriodCount`) before building a range or
105
+ looping, and reject more than 5000 (`STAT_MAX_TIMELINE_POINTS`) with a 400: `localDays` allows at most 208 days on
106
+ `hour`, 3 on `min`.
107
+
108
+ Helpers: `statPeriodStart / statNextPeriodStart / statPeriodRange / statPeriodCount / statLastPeriods`,
109
+ `splitStatSpan`, `addStatMetrics`, `cloneStatMetrics`, `statDict`, `statOwn`, `isStatReservedKey`,
110
+ `normalizeStatKey`, `foldStatValue`, `statGaugeAverage`, `flattenStatTotals`,
111
+ `mergeStatCounters`, `buildStatTimeline`, `zonedMidnight / zonedDateKey / zonedOffsetMs`.
112
+
113
+ ## Flush: deltas, added, applied once
114
+
115
+ 1. **Take.** `buffer.take(n)` removes up to `n` buckets atomically and returns them as a batch with a fresh `id`
116
+ and `claim`. Redis: one Lua script `SPOP`s the dirty set and moves each bucket's hash into `…:batch:<id>`, then
117
+ deletes the bucket; a write after that starts a new delta. Two instances never take the same bucket, so there
118
+ is no global flush lock.
119
+ 2. **Merge.** `store.merge(batch)` runs one transaction: insert `id` into the flush log, then for every bucket
120
+ `metrics[value][status] = old + delta` (`ON CONFLICT … DO UPDATE` sums both sides cell by cell). A row is never
121
+ overwritten with the buffer's value, so a restarted / evicted Redis or a late `at` can't make a total go down.
122
+ 3. **Ack.** Success → `buffer.ack(batch)` deletes the in-flight batch.
123
+ 4. **Failure.** `store.fence(id)` tells whether the commit happened anyway (a lost ack): it waits for any merge of
124
+ that id and then either finds it applied (→ ack, no double count) or records the id as fenced (→
125
+ `buffer.restore(batch)` adds the deltas back into the open buckets next to newer writes). If even the fence
126
+ fails, the batch stays in flight.
127
+ 5. **Reclaim.** Each flush first takes over in-flight batches older than `staleBatchMs` (a crashed or hung
128
+ flusher) under a new claim and merges them with the **same id**: the flush log skips an applied one and refuses
129
+ a fenced one (which is then restored). The old owner's `ack` / `restore` become no-ops.
130
+
131
+ ## Store port (`StatsStore`) — writing your own (e.g. SQLite)
132
+
133
+ The kit ships `TypeOrmStatsStore` (Postgres) and `InMemoryStatsStore` (tests, reference behaviour). A
134
+ single-process app on SQLite implements the port itself. Contract, in short (full text in
135
+ `ports/stats-store.ts`):
136
+
137
+ - `merge(batch)`: one transaction; per bucket `old + delta` per cell; all buckets or none. Record `batch.id` in a
138
+ flush log in the same transaction; an id already applied → no-op, an id fenced → throw `StatBatchFencedError`.
139
+ - `fence(id)`: `'applied'` if that id committed; otherwise record it as fenced and return `'fenced'`.
140
+ - `sumCells(filter)` → `{ periodStart (ISO), value, status, count }[]` summed across matching series per bucket;
141
+ `sumSeries(filter)` → summed per series × value × status; `hasNamespace(ns)`; `prune(granularity, before)`;
142
+ optional `pruneFlushLog(before)`.
143
+ - Filter: namespace + granularity exact; `subjectType` / `seriesKey` exact when given; `subjectId` exact when given,
144
+ `null` = global series; `from` inclusive, `to` exclusive on `period_start`; `values` / `statuses` restrict cells.
145
+
146
+ SQLite schema (primary key instead of a nullable unique: a NULL never conflicts):
147
+
148
+ ```sql
149
+ CREATE TABLE IF NOT EXISTS metric_snapshots (
150
+ namespace TEXT NOT NULL, subject_type TEXT NOT NULL,
151
+ subject_id TEXT NOT NULL DEFAULT '', series_key TEXT NOT NULL DEFAULT '',
152
+ granularity TEXT NOT NULL, period_start TEXT NOT NULL, -- ISO UTC
153
+ metrics TEXT NOT NULL, updated_at TEXT NOT NULL,
154
+ PRIMARY KEY (namespace, subject_type, subject_id, series_key, granularity, period_start)
155
+ );
156
+ CREATE TABLE IF NOT EXISTS metric_snapshot_flushes (id TEXT PRIMARY KEY, state TEXT NOT NULL, created_at TEXT NOT NULL);
157
+ ```
158
+
159
+ `merge` with a synchronous driver (`node:sqlite` / `@my-nestjs-kit/sqlite`): `BEGIN IMMEDIATE`; check / insert
160
+ the flush-log row; for each bucket `SELECT metrics` → `addStatMetrics(old, delta)` → `INSERT … ON CONFLICT (pk) DO
161
+ UPDATE SET metrics = excluded.metrics`; `COMMIT` (rollback + rethrow on error). Map `subjectId: null` ↔ `''` on
162
+ write and read. Reads: `json_each(m.metrics) v, json_each(v.value) s` grouped like the Postgres store. With a
163
+ synchronous local commit, `merge` can only fail after a rollback, so a store used by one process may skip the
164
+ flush log and return `'fenced'` from `fence`; keep the log anyway if it costs nothing.
165
+
166
+ Do not use an additive store over a network DB without the flush log: a lost commit ack plus a retry double-counts.
@@ -0,0 +1,21 @@
1
+ import type { StatFlushBatch, StatsBuffer } from '../ports/stats-buffer';
2
+ import type { StatBucket } from '../stats.types';
3
+ /**
4
+ * Buffer for exactly one process (desktop agent, CLI daemon, single-instance service): deltas in a Map, no I/O.
5
+ * Up to one flush interval is lost on a crash (S6); a clean stop flushes. Reads include its unflushed buckets.
6
+ */
7
+ export declare class MemoryStatsBuffer implements StatsBuffer {
8
+ private readonly _now;
9
+ private _open;
10
+ private readonly _inFlight;
11
+ constructor(_now?: () => number);
12
+ add(buckets: StatBucket[]): void;
13
+ take(maxBuckets: number): Promise<StatFlushBatch | null>;
14
+ reclaim(staleMs: number): Promise<StatFlushBatch[]>;
15
+ ack(batch: StatFlushBatch): Promise<boolean>;
16
+ restore(batch: StatFlushBatch): Promise<boolean>;
17
+ unflushed(): Iterable<StatBucket>;
18
+ /** Open + in-flight bucket count (for health / tests). */
19
+ get size(): number;
20
+ private _addOne;
21
+ }
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MemoryStatsBuffer = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const stat_metrics_1 = require("../helpers/stat-metrics");
6
+ /**
7
+ * Buffer for exactly one process (desktop agent, CLI daemon, single-instance service): deltas in a Map, no I/O.
8
+ * Up to one flush interval is lost on a crash (S6); a clean stop flushes. Reads include its unflushed buckets.
9
+ */
10
+ class MemoryStatsBuffer {
11
+ constructor(_now = Date.now) {
12
+ this._now = _now;
13
+ this._open = new Map();
14
+ this._inFlight = new Map();
15
+ }
16
+ add(buckets) {
17
+ for (const b of buckets)
18
+ this._addOne(b);
19
+ }
20
+ async take(maxBuckets) {
21
+ if (!this._open.size)
22
+ return null;
23
+ const buckets = [];
24
+ // Swap before any await: writes after this line start fresh deltas (S3).
25
+ for (const [key, b] of this._open) {
26
+ if (buckets.length >= maxBuckets)
27
+ break;
28
+ buckets.push(b);
29
+ this._open.delete(key);
30
+ }
31
+ const batch = { id: (0, crypto_1.randomUUID)(), claim: (0, crypto_1.randomUUID)(), buckets };
32
+ this._inFlight.set(batch.id, { claim: batch.claim, since: this._now(), buckets });
33
+ return batch;
34
+ }
35
+ async reclaim(staleMs) {
36
+ const out = [];
37
+ const now = this._now();
38
+ for (const [id, f] of this._inFlight) {
39
+ if (now - f.since < staleMs)
40
+ continue;
41
+ f.claim = (0, crypto_1.randomUUID)();
42
+ f.since = now;
43
+ out.push({ id, claim: f.claim, buckets: f.buckets });
44
+ }
45
+ return out;
46
+ }
47
+ async ack(batch) {
48
+ const f = this._inFlight.get(batch.id);
49
+ if (!f || f.claim !== batch.claim)
50
+ return false;
51
+ this._inFlight.delete(batch.id);
52
+ return true;
53
+ }
54
+ async restore(batch) {
55
+ const f = this._inFlight.get(batch.id);
56
+ if (!f || f.claim !== batch.claim)
57
+ return false;
58
+ this._inFlight.delete(batch.id);
59
+ for (const b of f.buckets)
60
+ this._addOne(b); // the open map may already hold new writes: add, don't replace
61
+ return true;
62
+ }
63
+ *unflushed() {
64
+ yield* this._open.values();
65
+ for (const f of this._inFlight.values())
66
+ yield* f.buckets;
67
+ }
68
+ /** Open + in-flight bucket count (for health / tests). */
69
+ get size() {
70
+ let n = this._open.size;
71
+ for (const f of this._inFlight.values())
72
+ n += f.buckets.length;
73
+ return n;
74
+ }
75
+ _addOne(b) {
76
+ const key = (0, stat_metrics_1.statBucketId)(b);
77
+ const cur = this._open.get(key);
78
+ if (cur)
79
+ (0, stat_metrics_1.addStatMetrics)(cur.metrics, b.metrics);
80
+ else
81
+ this._open.set(key, { ...b, metrics: (0, stat_metrics_1.cloneStatMetrics)(b.metrics) });
82
+ }
83
+ }
84
+ exports.MemoryStatsBuffer = MemoryStatsBuffer;
@@ -0,0 +1,79 @@
1
+ import type { StatFlushBatch, StatsBuffer } from '../ports/stats-buffer';
2
+ import { StatGranularity, type StatBucket, type StatBucketRef } from '../stats.types';
3
+ /** The subset of an ioredis pipeline the buffer uses. */
4
+ export interface StatsRedisPipeline {
5
+ hincrbyfloat(key: string, field: string, increment: number | string): unknown;
6
+ expire(key: string, seconds: number): unknown;
7
+ sadd(key: string, ...members: string[]): unknown;
8
+ exec(): Promise<[Error | null, unknown][] | null>;
9
+ }
10
+ /**
11
+ * The subset of an ioredis client the buffer uses. Give stats its **own** connection with
12
+ * `enableOfflineQueue: false` (rule 14), so an outage drops writes instead of queueing them in memory; the app opens
13
+ * and closes it (close in `onApplicationShutdown`, after the shutdown flush). `eval` only runs the constant scripts
14
+ * below; values go as ARGV.
15
+ */
16
+ export interface StatsRedisClient {
17
+ pipeline(): StatsRedisPipeline;
18
+ eval(script: string, numKeys: number, ...args: (string | number)[]): Promise<unknown>;
19
+ hgetall(key: string): Promise<Record<string, string>>;
20
+ }
21
+ export interface RedisStatsBufferOptions {
22
+ /**
23
+ * Key prefix, required: the app's `REDIS_PREFIX` plus a stats segment, e.g. `webhooxy:stats` (skill `local-infra`,
24
+ * rule 21). Never a bare `stats` on a shared Redis. May contain `:`; on Redis Cluster wrap it in a hash tag
25
+ * (`{webhooxy:stats}`) so every key lands on one slot — the scripts touch keys they compute.
26
+ */
27
+ prefix: string;
28
+ /** Seconds an open delta bucket lives without a flush, per granularity. Refreshed on every write. */
29
+ ttlSec?: Partial<Record<StatGranularity, number>>;
30
+ /** Seconds a taken batch lives in flight before Redis drops it. Default 7 days; keep it below the store's flush-log retention. */
31
+ inFlightTtlSec?: number;
32
+ /** Batches one `reclaim` call takes over at most. Default 10. */
33
+ reclaimLimit?: number;
34
+ }
35
+ /**
36
+ * Open delta buckets: the period plus a day of grace. Redis holds only what was written since the last flush, so an
37
+ * expired bucket loses one unflushed delta — it can no longer shrink a stored total.
38
+ */
39
+ export declare const STAT_REDIS_BUFFER_TTL_SEC: Record<StatGranularity, number>;
40
+ export declare const buildStatMetricField: (value: string, status: string) => string;
41
+ export declare function parseStatMetricField(field: string): {
42
+ value: string;
43
+ status: string;
44
+ } | null;
45
+ /**
46
+ * Buffer for any number of instances on one Redis. Hot path: one pipeline of `HINCRBYFLOAT` per cell (rule 16) +
47
+ * `EXPIRE` + `SADD dirty` per bucket. Flush side: atomic take (Lua), so two instances never take the same bucket;
48
+ * taken batches stay in Redis until the store acks them, so a crashed flusher loses nothing (`reclaim`).
49
+ *
50
+ * Keys (`{p}` = `prefix`):
51
+ * - `{p}:b:{gran}:{periodStartMs}:{ns}:{subjectType}:{subjectId|-}:{seriesKey|-}` HASH `value␟status` → delta
52
+ * - `{p}:dirty` SET of bucket keys written since they were last taken
53
+ * - `{p}:inflight` ZSET batch id → claimed-at ms; `{p}:claims` HASH batch id → claim; `{p}:batch:{id}` HASH
54
+ *
55
+ * Redis must not evict these keys (`maxmemory-policy noeviction`) and should run with AOF; with deltas a lost key
56
+ * loses at most its unflushed delta, it never shrinks a stored total.
57
+ */
58
+ export declare class RedisStatsBuffer implements StatsBuffer {
59
+ private readonly _redis;
60
+ private readonly _now;
61
+ private readonly _prefix;
62
+ private readonly _bucketPrefix;
63
+ private readonly _ttl;
64
+ private readonly _batchTtl;
65
+ private readonly _reclaimLimit;
66
+ constructor(_redis: StatsRedisClient, options: RedisStatsBufferOptions, _now?: () => number);
67
+ get dirtyKey(): string;
68
+ get inFlightKey(): string;
69
+ private get _claimsKey();
70
+ private _batchKey;
71
+ bucketKey(ref: StatBucketRef): string;
72
+ parseBucketKey(key: string): StatBucketRef | null;
73
+ add(buckets: StatBucket[]): Promise<void>;
74
+ take(maxBuckets: number): Promise<StatFlushBatch | null>;
75
+ reclaim(staleMs: number): Promise<StatFlushBatch[]>;
76
+ ack(batch: StatFlushBatch): Promise<boolean>;
77
+ restore(batch: StatFlushBatch): Promise<boolean>;
78
+ private _parseBatch;
79
+ }
@@ -0,0 +1,261 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RedisStatsBuffer = exports.parseStatMetricField = exports.buildStatMetricField = exports.STAT_REDIS_BUFFER_TTL_SEC = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const stat_metrics_1 = require("../helpers/stat-metrics");
6
+ const stats_constants_1 = require("../stats.constants");
7
+ const stats_types_1 = require("../stats.types");
8
+ const HOUR_S = 3_600;
9
+ const DAY_S = 24 * HOUR_S;
10
+ /**
11
+ * Open delta buckets: the period plus a day of grace. Redis holds only what was written since the last flush, so an
12
+ * expired bucket loses one unflushed delta — it can no longer shrink a stored total.
13
+ */
14
+ exports.STAT_REDIS_BUFFER_TTL_SEC = {
15
+ [stats_types_1.StatGranularity.MINUTE]: 60 + DAY_S,
16
+ [stats_types_1.StatGranularity.HOUR]: HOUR_S + DAY_S,
17
+ [stats_types_1.StatGranularity.DAY]: 2 * DAY_S,
18
+ [stats_types_1.StatGranularity.WEEK]: 8 * DAY_S,
19
+ [stats_types_1.StatGranularity.MONTH]: 32 * DAY_S,
20
+ };
21
+ const BATCH_TTL_S = 7 * DAY_S;
22
+ const NONE = '-';
23
+ const FIELD_SEP = '\u001f'; // value ␟ status inside one bucket hash
24
+ const KEY_SEP = '\u001e'; // bucket key ␞ field inside a batch hash
25
+ // Rule 6: every free-form segment encoded; '-' too, since a lone '-' marks null / empty.
26
+ const enc = (v) => (v === null || v === '' ? NONE : encodeURIComponent(v).replace(/-/g, '%2D'));
27
+ const dec = (v) => (v === NONE ? null : decodeURIComponent(v));
28
+ const buildStatMetricField = (value, status) => `${value}${FIELD_SEP}${status}`;
29
+ exports.buildStatMetricField = buildStatMetricField;
30
+ function parseStatMetricField(field) {
31
+ const i = field.lastIndexOf(FIELD_SEP);
32
+ return i === -1 ? null : { value: field.slice(0, i), status: field.slice(i + 1) };
33
+ }
34
+ exports.parseStatMetricField = parseStatMetricField;
35
+ /**
36
+ * Take up to ARGV[1] dirty buckets: each one's cells move into one batch hash and the bucket is deleted, all in one
37
+ * atomic step — a bucket is taken by exactly one flusher, and a write after this starts a fresh delta.
38
+ * KEYS: dirty, inflight (zset id → claimed-at ms), claims (hash id → claim), batch.
39
+ * ARGV: max, now, batch id, claim, batch ttl.
40
+ */
41
+ const TAKE = `
42
+ local SEP = string.char(30)
43
+ local members = redis.call('SPOP', KEYS[1], tonumber(ARGV[1]))
44
+ local n = 0
45
+ for _, k in ipairs(members) do
46
+ local h = redis.call('HGETALL', k)
47
+ if #h > 0 then
48
+ for i = 1, #h, 2 do redis.call('HSET', KEYS[4], k .. SEP .. h[i], h[i + 1]) end
49
+ redis.call('DEL', k)
50
+ n = n + 1
51
+ end
52
+ end
53
+ if n == 0 then return {} end
54
+ redis.call('EXPIRE', KEYS[4], tonumber(ARGV[5]))
55
+ redis.call('ZADD', KEYS[2], tonumber(ARGV[2]), ARGV[3])
56
+ redis.call('HSET', KEYS[3], ARGV[3], ARGV[4])
57
+ return redis.call('HGETALL', KEYS[4])`;
58
+ /** KEYS: inflight, claims. ARGV: stale-before ms, now, new claim, limit. Returns the ids taken over. */
59
+ const RECLAIM = `
60
+ local ids = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', ARGV[1], 'LIMIT', 0, tonumber(ARGV[4]))
61
+ for _, id in ipairs(ids) do
62
+ redis.call('ZADD', KEYS[1], tonumber(ARGV[2]), id)
63
+ redis.call('HSET', KEYS[2], id, ARGV[3])
64
+ end
65
+ return ids`;
66
+ /** KEYS: inflight, claims, batch. ARGV: id, claim. */
67
+ const ACK = `
68
+ if redis.call('HGET', KEYS[2], ARGV[1]) ~= ARGV[2] then return 0 end
69
+ redis.call('DEL', KEYS[3])
70
+ redis.call('ZREM', KEYS[1], ARGV[1])
71
+ redis.call('HDEL', KEYS[2], ARGV[1])
72
+ return 1`;
73
+ /**
74
+ * Put a batch's deltas back into the open buckets (HINCRBYFLOAT, so writes made meanwhile are kept) and mark them
75
+ * dirty again. KEYS: inflight, claims, batch, dirty. ARGV: id, claim, bucket key prefix, then granularity / ttl pairs.
76
+ */
77
+ const RESTORE = `
78
+ if redis.call('HGET', KEYS[2], ARGV[1]) ~= ARGV[2] then return 0 end
79
+ local SEP = string.char(30)
80
+ local ttl = {}
81
+ for i = 4, #ARGV, 2 do ttl[ARGV[i]] = tonumber(ARGV[i + 1]) end
82
+ local plen = string.len(ARGV[3])
83
+ local h = redis.call('HGETALL', KEYS[3])
84
+ local touched = {}
85
+ for i = 1, #h, 2 do
86
+ local sep = string.find(h[i], SEP, 1, true)
87
+ if sep then
88
+ local k = string.sub(h[i], 1, sep - 1)
89
+ redis.call('HINCRBYFLOAT', k, string.sub(h[i], sep + 1), h[i + 1])
90
+ touched[k] = true
91
+ end
92
+ end
93
+ for k in pairs(touched) do
94
+ local g = string.match(string.sub(k, plen + 1), '^([^:]+)')
95
+ redis.call('EXPIRE', k, ttl[g] or 86400)
96
+ redis.call('SADD', KEYS[4], k)
97
+ end
98
+ redis.call('DEL', KEYS[3])
99
+ redis.call('ZREM', KEYS[1], ARGV[1])
100
+ redis.call('HDEL', KEYS[2], ARGV[1])
101
+ return 1`;
102
+ /**
103
+ * Buffer for any number of instances on one Redis. Hot path: one pipeline of `HINCRBYFLOAT` per cell (rule 16) +
104
+ * `EXPIRE` + `SADD dirty` per bucket. Flush side: atomic take (Lua), so two instances never take the same bucket;
105
+ * taken batches stay in Redis until the store acks them, so a crashed flusher loses nothing (`reclaim`).
106
+ *
107
+ * Keys (`{p}` = `prefix`):
108
+ * - `{p}:b:{gran}:{periodStartMs}:{ns}:{subjectType}:{subjectId|-}:{seriesKey|-}` HASH `value␟status` → delta
109
+ * - `{p}:dirty` SET of bucket keys written since they were last taken
110
+ * - `{p}:inflight` ZSET batch id → claimed-at ms; `{p}:claims` HASH batch id → claim; `{p}:batch:{id}` HASH
111
+ *
112
+ * Redis must not evict these keys (`maxmemory-policy noeviction`) and should run with AOF; with deltas a lost key
113
+ * loses at most its unflushed delta, it never shrinks a stored total.
114
+ */
115
+ class RedisStatsBuffer {
116
+ constructor(_redis, options, _now = Date.now) {
117
+ this._redis = _redis;
118
+ this._now = _now;
119
+ // eslint-disable-next-line no-control-regex
120
+ if (!options?.prefix || /[\u0000-\u001f\s]/.test(options.prefix)) {
121
+ throw new Error('RedisStatsBuffer: options.prefix is required (e.g. `${REDIS_PREFIX}:stats`), no spaces / control chars');
122
+ }
123
+ this._prefix = options.prefix;
124
+ this._bucketPrefix = `${options.prefix}:b:`;
125
+ this._ttl = { ...exports.STAT_REDIS_BUFFER_TTL_SEC, ...(options.ttlSec ?? {}) };
126
+ this._batchTtl = options.inFlightTtlSec ?? BATCH_TTL_S;
127
+ this._reclaimLimit = options.reclaimLimit ?? 10;
128
+ }
129
+ get dirtyKey() {
130
+ return `${this._prefix}:dirty`;
131
+ }
132
+ get inFlightKey() {
133
+ return `${this._prefix}:inflight`;
134
+ }
135
+ get _claimsKey() {
136
+ return `${this._prefix}:claims`;
137
+ }
138
+ _batchKey(id) {
139
+ return `${this._prefix}:batch:${id}`;
140
+ }
141
+ bucketKey(ref) {
142
+ return (this._bucketPrefix +
143
+ [
144
+ ref.granularity,
145
+ ref.periodStart.getTime(),
146
+ enc(ref.namespace),
147
+ enc(ref.subjectType),
148
+ enc(ref.subjectId),
149
+ enc(ref.seriesKey),
150
+ ].join(':'));
151
+ }
152
+ parseBucketKey(key) {
153
+ if (!key.startsWith(this._bucketPrefix))
154
+ return null;
155
+ const p = key.slice(this._bucketPrefix.length).split(':');
156
+ if (p.length !== 6)
157
+ return null;
158
+ const [g, ms, ns, st, sid, sk] = p;
159
+ if (!stats_constants_1.ALL_STAT_GRANULARITIES.includes(g))
160
+ return null;
161
+ const startMs = Number(ms);
162
+ if (!Number.isFinite(startMs))
163
+ return null;
164
+ try {
165
+ const namespace = dec(ns);
166
+ const subjectType = dec(st);
167
+ if (!namespace || !subjectType)
168
+ return null;
169
+ return {
170
+ granularity: g,
171
+ periodStart: new Date(startMs),
172
+ namespace,
173
+ subjectType,
174
+ subjectId: dec(sid),
175
+ seriesKey: dec(sk) ?? '',
176
+ };
177
+ }
178
+ catch {
179
+ return null; // malformed percent-encoding
180
+ }
181
+ }
182
+ async add(buckets) {
183
+ if (!buckets.length)
184
+ return;
185
+ const pipe = this._redis.pipeline();
186
+ for (const b of buckets) {
187
+ const key = this.bucketKey(b);
188
+ let cells = 0;
189
+ for (const { value, status, count } of (0, stat_metrics_1.statCellsOf)(b.metrics, {})) {
190
+ pipe.hincrbyfloat(key, (0, exports.buildStatMetricField)(value, status), count);
191
+ cells++;
192
+ }
193
+ if (!cells)
194
+ continue;
195
+ pipe.expire(key, this._ttl[b.granularity]);
196
+ pipe.sadd(this.dirtyKey, key);
197
+ }
198
+ // exec() resolves even when commands failed: the errors are in the tuples.
199
+ const results = (await pipe.exec()) ?? [];
200
+ const failed = results.find(([err]) => err);
201
+ if (failed)
202
+ throw failed[0];
203
+ }
204
+ async take(maxBuckets) {
205
+ const id = (0, crypto_1.randomUUID)();
206
+ const claim = (0, crypto_1.randomUUID)();
207
+ const flat = (await this._redis.eval(TAKE, 4, this.dirtyKey, this.inFlightKey, this._claimsKey, this._batchKey(id), Math.max(1, Math.floor(maxBuckets)), this._now(), id, claim, this._batchTtl));
208
+ if (!flat?.length)
209
+ return null;
210
+ const hash = (0, stat_metrics_1.statDict)();
211
+ for (let i = 0; i < flat.length; i += 2)
212
+ hash[flat[i]] = flat[i + 1];
213
+ return { id, claim, buckets: this._parseBatch(hash) };
214
+ }
215
+ async reclaim(staleMs) {
216
+ const now = this._now();
217
+ const claim = (0, crypto_1.randomUUID)();
218
+ const ids = (await this._redis.eval(RECLAIM, 2, this.inFlightKey, this._claimsKey, now - staleMs, now, claim, this._reclaimLimit));
219
+ const out = [];
220
+ for (const id of ids ?? []) {
221
+ // An expired batch hash comes back empty: the service acks it away and reports the loss.
222
+ const hash = await this._redis.hgetall(this._batchKey(id));
223
+ out.push({ id, claim, buckets: this._parseBatch(hash ?? {}) });
224
+ }
225
+ return out;
226
+ }
227
+ async ack(batch) {
228
+ const r = await this._redis.eval(ACK, 3, this.inFlightKey, this._claimsKey, this._batchKey(batch.id), batch.id, batch.claim);
229
+ return Number(r) === 1;
230
+ }
231
+ async restore(batch) {
232
+ const ttlArgs = stats_constants_1.ALL_STAT_GRANULARITIES.flatMap((g) => [g, this._ttl[g]]);
233
+ const r = await this._redis.eval(RESTORE, 4, this.inFlightKey, this._claimsKey, this._batchKey(batch.id), this.dirtyKey, batch.id, batch.claim, this._bucketPrefix, ...ttlArgs);
234
+ return Number(r) === 1;
235
+ }
236
+ _parseBatch(hash) {
237
+ const byKey = new Map();
238
+ for (const [field, raw] of Object.entries(hash)) {
239
+ const i = field.indexOf(KEY_SEP);
240
+ if (i === -1)
241
+ continue;
242
+ const key = field.slice(0, i);
243
+ const cell = parseStatMetricField(field.slice(i + 1));
244
+ const n = Number(raw);
245
+ if (!cell || !Number.isFinite(n) || (0, stat_metrics_1.isStatReservedKey)(cell.value) || (0, stat_metrics_1.isStatReservedKey)(cell.status))
246
+ continue;
247
+ let b = byKey.get(key);
248
+ if (!b) {
249
+ const ref = this.parseBucketKey(key);
250
+ if (!ref)
251
+ continue;
252
+ b = { ...ref, metrics: (0, stat_metrics_1.statDict)() };
253
+ byKey.set(key, b);
254
+ }
255
+ const c = (0, stat_metrics_1.statOwn)(b.metrics, cell.value) ?? (b.metrics[cell.value] = (0, stat_metrics_1.statDict)());
256
+ c[cell.status] = ((0, stat_metrics_1.statOwn)(c, cell.status) ?? 0) + n;
257
+ }
258
+ return [...byKey.values()];
259
+ }
260
+ }
261
+ exports.RedisStatsBuffer = RedisStatsBuffer;