@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,45 @@
1
+ import type { StatCellRow, StatFilter, StatGranularity, StatSeriesCellRow } from '../stats.types';
2
+ import type { StatFlushBatch } from './stats-buffer';
3
+ /** What `fence` found: the batch was applied, or it is now guaranteed never to be applied. */
4
+ export type StatBatchFenceResult = 'applied' | 'fenced';
5
+ /** Thrown by `merge` when the batch id was fenced before: the caller must restore the deltas, not drop them. */
6
+ export declare class StatBatchFencedError extends Error {
7
+ readonly batchId: string;
8
+ constructor(batchId: string);
9
+ }
10
+ /**
11
+ * Durable store port (Postgres in the kit: `TypeOrmStatsStore`; SQLite and others live in the app).
12
+ *
13
+ * **Write side — the store adds, it never replaces.**
14
+ * - `merge(batch)`: in ONE transaction, for every bucket `metrics[value][status] += delta` (a missing row is
15
+ * inserted, a missing cell starts at 0). All buckets of the batch or none. Idempotent per `batch.id`: record the
16
+ * id in a flush log inside the same transaction; an id already recorded as applied → commit nothing and resolve;
17
+ * an id recorded as fenced → throw `StatBatchFencedError`. Buckets inside one batch are unique by series ×
18
+ * granularity × periodStart, but sum duplicates defensively.
19
+ * - `fence(batchId)`: called after `merge` failed, to learn whether it committed anyway (a lost commit ack). It must
20
+ * wait for an in-progress `merge` of the same id and then either report `'applied'`, or record the id as fenced so
21
+ * a late or retried `merge` of it can never apply, and report `'fenced'`. Postgres: `INSERT … ON CONFLICT DO
22
+ * NOTHING` on the flush-log primary key does both (the insert waits on the other transaction's key lock).
23
+ * A store whose commit can't be ambiguous (embedded SQLite with a synchronous driver: `merge` throws only after a
24
+ * rollback) may skip the flush log, apply `merge` unconditionally and return `'fenced'` from `fence` — as long as
25
+ * it is the only writer (one process).
26
+ *
27
+ * **Read side** (all filters: namespace + granularity exact; `subjectType` / `seriesKey` exact when given;
28
+ * `subjectId` exact when given, `null` = global series; `from` inclusive, `to` exclusive on `period_start`;
29
+ * `values` / `statuses` restrict cells):
30
+ * - `sumCells`: cells summed across every matching series, grouped by period start, value, status.
31
+ * - `sumSeries`: cells summed per series (subject type + id + series key), value, status — across periods.
32
+ * - `hasNamespace`: any row of the namespace.
33
+ * - `prune(granularity, before)`: hard-delete rows of that granularity with `period_start < before`; returns rows
34
+ * deleted when known.
35
+ * - `pruneFlushLog(before)` (optional): drop flush-log rows older than `before`.
36
+ */
37
+ export interface StatsStore {
38
+ merge(batch: StatFlushBatch): Promise<void>;
39
+ fence(batchId: string): Promise<StatBatchFenceResult>;
40
+ sumCells(filter: StatFilter): Promise<StatCellRow[]>;
41
+ sumSeries(filter: StatFilter): Promise<StatSeriesCellRow[]>;
42
+ hasNamespace(namespace: string): Promise<boolean>;
43
+ prune(granularity: StatGranularity, before: Date): Promise<number | void>;
44
+ pruneFlushLog?(before: Date): Promise<number | void>;
45
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StatBatchFencedError = void 0;
4
+ /** Thrown by `merge` when the batch id was fenced before: the caller must restore the deltas, not drop them. */
5
+ class StatBatchFencedError extends Error {
6
+ constructor(batchId) {
7
+ super(`stats batch ${batchId} was fenced; restore its deltas`);
8
+ this.batchId = batchId;
9
+ this.name = 'StatBatchFencedError';
10
+ }
11
+ }
12
+ exports.StatBatchFencedError = StatBatchFencedError;
@@ -0,0 +1,31 @@
1
+ import { StatGranularity } from './stats.types';
2
+ /** Fine → coarse. */
3
+ export declare const ALL_STAT_GRANULARITIES: readonly StatGranularity[];
4
+ /** Column widths. An overlong series segment drops the write (rule 19); an overlong value / status is cut (rule 7). */
5
+ export declare const STAT_LIMITS: {
6
+ readonly namespace: 255;
7
+ readonly subjectType: 64;
8
+ readonly subjectId: 255;
9
+ readonly seriesKey: 255;
10
+ readonly value: 128;
11
+ readonly status: 64;
12
+ };
13
+ /** Store retention per granularity in ms; `null` / absent = forever (rule 12). */
14
+ export declare const STAT_DEFAULT_RETENTION_MS: Partial<Record<StatGranularity, number | null>>;
15
+ export declare const STAT_DEFAULT_FLUSH_EVERY_MS = 60000;
16
+ export declare const STAT_DEFAULT_PRUNE_EVERY_MS: number;
17
+ /** Buckets per flush batch (one store transaction). */
18
+ export declare const STAT_DEFAULT_BATCH_SIZE = 500;
19
+ /** Batches one flush call takes at most, so a huge backlog can't hold one flush forever. */
20
+ export declare const STAT_DEFAULT_MAX_BATCHES_PER_FLUSH = 100;
21
+ /** A batch in flight longer than this is taken over by the next flush (its flusher died or hangs). */
22
+ export declare const STAT_DEFAULT_STALE_BATCH_MS: number;
23
+ /** How long the store keeps flush-log rows (idempotency of retried batches). Must outlive in-flight batches. */
24
+ export declare const STAT_DEFAULT_FLUSH_LOG_RETENTION_MS: number;
25
+ export declare const STAT_MAX_TIMELINE_POINTS = 5000;
26
+ export declare const STAT_DEFAULT_VALUE_LIMIT = 50;
27
+ /** Statuses written by `recordGauge`. */
28
+ export declare const STAT_GAUGE_SUM = "sum";
29
+ export declare const STAT_GAUGE_COUNT = "n";
30
+ /** Cardinality guard value for user-supplied values outside the known set (`foldStatValue`). */
31
+ export declare const STAT_OTHER_VALUE = "__other__";
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.STAT_OTHER_VALUE = exports.STAT_GAUGE_COUNT = exports.STAT_GAUGE_SUM = exports.STAT_DEFAULT_VALUE_LIMIT = exports.STAT_MAX_TIMELINE_POINTS = exports.STAT_DEFAULT_FLUSH_LOG_RETENTION_MS = exports.STAT_DEFAULT_STALE_BATCH_MS = exports.STAT_DEFAULT_MAX_BATCHES_PER_FLUSH = exports.STAT_DEFAULT_BATCH_SIZE = exports.STAT_DEFAULT_PRUNE_EVERY_MS = exports.STAT_DEFAULT_FLUSH_EVERY_MS = exports.STAT_DEFAULT_RETENTION_MS = exports.STAT_LIMITS = exports.ALL_STAT_GRANULARITIES = void 0;
4
+ const stats_types_1 = require("./stats.types");
5
+ /** Fine → coarse. */
6
+ exports.ALL_STAT_GRANULARITIES = [
7
+ stats_types_1.StatGranularity.MINUTE,
8
+ stats_types_1.StatGranularity.HOUR,
9
+ stats_types_1.StatGranularity.DAY,
10
+ stats_types_1.StatGranularity.WEEK,
11
+ stats_types_1.StatGranularity.MONTH,
12
+ ];
13
+ /** Column widths. An overlong series segment drops the write (rule 19); an overlong value / status is cut (rule 7). */
14
+ exports.STAT_LIMITS = {
15
+ namespace: 255,
16
+ subjectType: 64,
17
+ subjectId: 255,
18
+ seriesKey: 255,
19
+ value: 128,
20
+ status: 64,
21
+ };
22
+ const MIN_MS = 60_000;
23
+ const HOUR_MS = 60 * MIN_MS;
24
+ const DAY_MS = 24 * HOUR_MS;
25
+ /** Store retention per granularity in ms; `null` / absent = forever (rule 12). */
26
+ exports.STAT_DEFAULT_RETENTION_MS = {
27
+ [stats_types_1.StatGranularity.MINUTE]: 2 * DAY_MS,
28
+ [stats_types_1.StatGranularity.HOUR]: 90 * DAY_MS,
29
+ };
30
+ exports.STAT_DEFAULT_FLUSH_EVERY_MS = MIN_MS;
31
+ exports.STAT_DEFAULT_PRUNE_EVERY_MS = HOUR_MS;
32
+ /** Buckets per flush batch (one store transaction). */
33
+ exports.STAT_DEFAULT_BATCH_SIZE = 500;
34
+ /** Batches one flush call takes at most, so a huge backlog can't hold one flush forever. */
35
+ exports.STAT_DEFAULT_MAX_BATCHES_PER_FLUSH = 100;
36
+ /** A batch in flight longer than this is taken over by the next flush (its flusher died or hangs). */
37
+ exports.STAT_DEFAULT_STALE_BATCH_MS = 5 * MIN_MS;
38
+ /** How long the store keeps flush-log rows (idempotency of retried batches). Must outlive in-flight batches. */
39
+ exports.STAT_DEFAULT_FLUSH_LOG_RETENTION_MS = 30 * DAY_MS;
40
+ exports.STAT_MAX_TIMELINE_POINTS = 5_000;
41
+ exports.STAT_DEFAULT_VALUE_LIMIT = 50;
42
+ /** Statuses written by `recordGauge`. */
43
+ exports.STAT_GAUGE_SUM = 'sum';
44
+ exports.STAT_GAUGE_COUNT = 'n';
45
+ /** Cardinality guard value for user-supplied values outside the known set (`foldStatValue`). */
46
+ exports.STAT_OTHER_VALUE = '__other__';
@@ -0,0 +1,29 @@
1
+ import type { StatsService } from './stats.service';
2
+ /** Job names for an app that runs flush / prune on its BullMQ queue (with `flushEveryMs: false, pruneEveryMs: false`). */
3
+ export declare const STATS_JOB: {
4
+ readonly FLUSH: "stats.flush";
5
+ readonly PRUNE: "stats.prune";
6
+ };
7
+ export type StatsJobName = (typeof STATS_JOB)[keyof typeof STATS_JOB];
8
+ /** The part of a BullMQ 5 `Queue` this helper uses (no bullmq import in the kit entry). */
9
+ export interface StatsJobSchedulerQueue {
10
+ upsertJobScheduler(id: string, repeat: {
11
+ pattern?: string;
12
+ every?: number;
13
+ }, template?: {
14
+ name?: string;
15
+ data?: unknown;
16
+ }): Promise<unknown>;
17
+ }
18
+ /**
19
+ * Registers the two repeat jobs (BullMQ 5 job schedulers, idempotent across instances). The app's own processor
20
+ * calls `runStatsJob`. The queue name must carry the app prefix (rule 21). Flush on shutdown still runs from the
21
+ * module.
22
+ */
23
+ export declare function upsertStatsJobSchedulers(queue: StatsJobSchedulerQueue, o?: {
24
+ flushPattern?: string;
25
+ prunePattern?: string;
26
+ idPrefix?: string;
27
+ }): Promise<void>;
28
+ /** Dispatch a stats job by name; returns false for a name that isn't a stats job. */
29
+ export declare function runStatsJob(stats: StatsService, name: string): Promise<boolean>;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runStatsJob = exports.upsertStatsJobSchedulers = exports.STATS_JOB = void 0;
4
+ /** Job names for an app that runs flush / prune on its BullMQ queue (with `flushEveryMs: false, pruneEveryMs: false`). */
5
+ exports.STATS_JOB = {
6
+ FLUSH: 'stats.flush',
7
+ PRUNE: 'stats.prune',
8
+ };
9
+ /**
10
+ * Registers the two repeat jobs (BullMQ 5 job schedulers, idempotent across instances). The app's own processor
11
+ * calls `runStatsJob`. The queue name must carry the app prefix (rule 21). Flush on shutdown still runs from the
12
+ * module.
13
+ */
14
+ async function upsertStatsJobSchedulers(queue, o = {}) {
15
+ const id = o.idPrefix ?? 'stats';
16
+ await queue.upsertJobScheduler(`${id}-flush`, { pattern: o.flushPattern ?? '* * * * *' }, { name: exports.STATS_JOB.FLUSH });
17
+ await queue.upsertJobScheduler(`${id}-prune`, { pattern: o.prunePattern ?? '17 * * * *' }, { name: exports.STATS_JOB.PRUNE });
18
+ }
19
+ exports.upsertStatsJobSchedulers = upsertStatsJobSchedulers;
20
+ /** Dispatch a stats job by name; returns false for a name that isn't a stats job. */
21
+ async function runStatsJob(stats, name) {
22
+ if (name === exports.STATS_JOB.FLUSH) {
23
+ const r = await stats.flush();
24
+ if (r.error)
25
+ throw new Error(r.error); // let the queue record the failure
26
+ return true;
27
+ }
28
+ if (name === exports.STATS_JOB.PRUNE) {
29
+ await stats.prune();
30
+ return true;
31
+ }
32
+ return false;
33
+ }
34
+ exports.runStatsJob = runStatsJob;
@@ -0,0 +1,14 @@
1
+ import { DynamicModule } from '@nestjs/common';
2
+ import { type StatsModuleAsyncOptions, type StatsModuleOptions } from './stats.options';
3
+ /**
4
+ * Stats engine: `StatsModule.forRoot({ buffer, store })` once (global by default). The app owns the connections it
5
+ * passes in (its stats Redis client, its DataSource), the routes (authenticated, scoped — rule 13) and the
6
+ * migration (`MetricSnapshotsMigrationBase`).
7
+ */
8
+ export declare class StatsModule {
9
+ static forRoot(options: StatsModuleOptions & {
10
+ isGlobal?: boolean;
11
+ }): DynamicModule;
12
+ static forRootAsync(o: StatsModuleAsyncOptions): DynamicModule;
13
+ private static _build;
14
+ }
@@ -0,0 +1,41 @@
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 StatsModule_1;
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.StatsModule = void 0;
11
+ const common_1 = require("@nestjs/common");
12
+ const stats_options_1 = require("./stats.options");
13
+ const stats_scheduler_1 = require("./stats.scheduler");
14
+ const stats_service_1 = require("./stats.service");
15
+ /**
16
+ * Stats engine: `StatsModule.forRoot({ buffer, store })` once (global by default). The app owns the connections it
17
+ * passes in (its stats Redis client, its DataSource), the routes (authenticated, scoped — rule 13) and the
18
+ * migration (`MetricSnapshotsMigrationBase`).
19
+ */
20
+ let StatsModule = StatsModule_1 = class StatsModule {
21
+ static forRoot(options) {
22
+ const { isGlobal, ...o } = options;
23
+ return StatsModule_1._build({ provide: stats_options_1.STATS_MODULE_OPTIONS, useValue: o }, isGlobal, []);
24
+ }
25
+ static forRootAsync(o) {
26
+ return StatsModule_1._build({ provide: stats_options_1.STATS_MODULE_OPTIONS, useFactory: o.useFactory, inject: o.inject ?? [] }, o.isGlobal, o.imports ?? []);
27
+ }
28
+ static _build(options, isGlobal, imports) {
29
+ return {
30
+ module: StatsModule_1,
31
+ global: isGlobal ?? true,
32
+ imports,
33
+ providers: [options, stats_service_1.StatsService, stats_scheduler_1.StatsScheduler],
34
+ exports: [stats_service_1.StatsService, stats_options_1.STATS_MODULE_OPTIONS],
35
+ };
36
+ }
37
+ };
38
+ exports.StatsModule = StatsModule;
39
+ exports.StatsModule = StatsModule = StatsModule_1 = __decorate([
40
+ (0, common_1.Module)({})
41
+ ], StatsModule);
@@ -0,0 +1,35 @@
1
+ import type { ModuleMetadata } from '@nestjs/common';
2
+ import type { StatsBuffer } from './ports/stats-buffer';
3
+ import type { StatsStore } from './ports/stats-store';
4
+ import type { StatGranularity } from './stats.types';
5
+ export declare const STATS_MODULE_OPTIONS: unique symbol;
6
+ export interface StatsModuleOptions {
7
+ /** Hot-path buffer: `RedisStatsBuffer` (several instances) or `MemoryStatsBuffer` (one process). */
8
+ buffer: StatsBuffer;
9
+ /** Durable store: `TypeOrmStatsStore` (Postgres) or the app's own (`StatsStore` port, e.g. SQLite). */
10
+ store: StatsStore;
11
+ /** Granularities an increment writes when the call doesn't name them. Default: all five. */
12
+ granularities?: StatGranularity[];
13
+ /** Store retention per granularity in ms, merged over the defaults (min 2 d, hour 90 d); `null` = forever. */
14
+ retention?: Partial<Record<StatGranularity, number | null>>;
15
+ /** Interval flush in ms; `false` when the app schedules `flush()` itself (BullMQ, cron). Default 60 000. */
16
+ flushEveryMs?: number | false;
17
+ /** Interval prune in ms; `false` to schedule `prune()` yourself. Default 1 h. */
18
+ pruneEveryMs?: number | false;
19
+ /** Flush in `beforeApplicationShutdown` (needs `app.enableShutdownHooks()`). Default true. */
20
+ flushOnShutdown?: boolean;
21
+ /** Buckets per store transaction. Default 500. */
22
+ batchSize?: number;
23
+ /** Batches one flush call writes at most. Default 100. */
24
+ maxBatchesPerFlush?: number;
25
+ /** In-flight batches older than this are taken over by the next flush. Default 5 min. */
26
+ staleBatchMs?: number;
27
+ /** Flush-log rows older than this are pruned. Default 30 d; keep it above the buffer's in-flight TTL. */
28
+ flushLogRetentionMs?: number;
29
+ }
30
+ export interface StatsModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
31
+ inject?: any[];
32
+ useFactory: (...args: any[]) => StatsModuleOptions | Promise<StatsModuleOptions>;
33
+ /** Default true: writers in any module inject `StatsService`. */
34
+ isGlobal?: boolean;
35
+ }
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.STATS_MODULE_OPTIONS = void 0;
4
+ exports.STATS_MODULE_OPTIONS = Symbol('STATS_MODULE_OPTIONS');
@@ -0,0 +1,20 @@
1
+ import { BeforeApplicationShutdown, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
2
+ import { type StatsModuleOptions } from './stats.options';
3
+ import { StatsService } from './stats.service';
4
+ /**
5
+ * Interval flush / prune on every instance (no BullMQ needed: taking buckets is atomic in the buffer, so instances
6
+ * never flush the same bucket) and a final flush in `beforeApplicationShutdown` — which runs before
7
+ * `onApplicationShutdown`, so the app closes its Redis client / DB there, never in `onModuleDestroy`.
8
+ */
9
+ export declare class StatsScheduler implements OnModuleInit, OnModuleDestroy, BeforeApplicationShutdown {
10
+ private readonly _stats;
11
+ private readonly _o;
12
+ private readonly _logger;
13
+ private readonly _timers;
14
+ constructor(_stats: StatsService, _o: StatsModuleOptions);
15
+ onModuleInit(): void;
16
+ onModuleDestroy(): void;
17
+ beforeApplicationShutdown(): Promise<void>;
18
+ private _every;
19
+ private _stop;
20
+ }
@@ -0,0 +1,67 @@
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.StatsScheduler = void 0;
16
+ const common_1 = require("@nestjs/common");
17
+ const stats_constants_1 = require("./stats.constants");
18
+ const stats_options_1 = require("./stats.options");
19
+ const stats_service_1 = require("./stats.service");
20
+ /**
21
+ * Interval flush / prune on every instance (no BullMQ needed: taking buckets is atomic in the buffer, so instances
22
+ * never flush the same bucket) and a final flush in `beforeApplicationShutdown` — which runs before
23
+ * `onApplicationShutdown`, so the app closes its Redis client / DB there, never in `onModuleDestroy`.
24
+ */
25
+ let StatsScheduler = class StatsScheduler {
26
+ constructor(_stats, _o) {
27
+ this._stats = _stats;
28
+ this._o = _o;
29
+ this._logger = new common_1.Logger('StatsScheduler');
30
+ this._timers = [];
31
+ }
32
+ onModuleInit() {
33
+ const flushMs = this._o.flushEveryMs ?? stats_constants_1.STAT_DEFAULT_FLUSH_EVERY_MS;
34
+ const pruneMs = this._o.pruneEveryMs ?? stats_constants_1.STAT_DEFAULT_PRUNE_EVERY_MS;
35
+ if (flushMs !== false && flushMs > 0)
36
+ this._every(flushMs, () => this._stats.flush());
37
+ if (pruneMs !== false && pruneMs > 0)
38
+ this._every(pruneMs, () => this._stats.prune());
39
+ }
40
+ onModuleDestroy() {
41
+ this._stop();
42
+ }
43
+ async beforeApplicationShutdown() {
44
+ this._stop();
45
+ if (this._o.flushOnShutdown === false)
46
+ return;
47
+ const r = await this._stats.flush();
48
+ if (r.error)
49
+ this._logger.warn(`shutdown flush incomplete: ${r.error}`);
50
+ }
51
+ _every(ms, run) {
52
+ const t = setInterval(() => {
53
+ run().catch((e) => this._logger.warn(e?.message));
54
+ }, ms);
55
+ t.unref?.();
56
+ this._timers.push(t);
57
+ }
58
+ _stop() {
59
+ this._timers.splice(0).forEach((t) => clearInterval(t));
60
+ }
61
+ };
62
+ exports.StatsScheduler = StatsScheduler;
63
+ exports.StatsScheduler = StatsScheduler = __decorate([
64
+ (0, common_1.Injectable)(),
65
+ __param(1, (0, common_1.Inject)(stats_options_1.STATS_MODULE_OPTIONS)),
66
+ __metadata("design:paramtypes", [stats_service_1.StatsService, Object])
67
+ ], StatsScheduler);
@@ -0,0 +1,80 @@
1
+ import { Subject } from 'rxjs';
2
+ import { type StatsModuleOptions } from './stats.options';
3
+ import { StatGranularity, type StatDurationIncrement, type StatFilter, type StatFlushResult, type StatGaugeSample, type StatIncrement, type StatLocalDay, type StatsChange, type StatSeriesTotals, type StatTimeline, type StatTimelineQuery, type StatTotals } from './stats.types';
4
+ /** A series without the window: what `totals` / `seriesTotals` / `localDays` take. */
5
+ export type StatSeriesFilter = Omit<StatFilter, 'granularity' | 'from' | 'to'>;
6
+ export interface StatLocalDaysQuery extends StatSeriesFilter {
7
+ /** Local days back, today included. */
8
+ days: number;
9
+ /** IANA zone of the reader (`Europe/Kyiv`), not the process TZ. */
10
+ timeZone: string;
11
+ /**
12
+ * Buckets the days are summed from; the namespace must write and retain it for the span. Default `hour` (exact for
13
+ * whole-hour offsets; use `min` for :30 / :45 zones).
14
+ */
15
+ granularity?: StatGranularity.HOUR | StatGranularity.MINUTE;
16
+ now?: Date;
17
+ }
18
+ /**
19
+ * The stats engine (skill `nestjs-stats`): writes go to the buffer as deltas, `flush()` moves taken deltas into the
20
+ * store, which adds them; reads sum the store plus the buffer's unflushed buckets when it exposes them.
21
+ *
22
+ * Writers inject this service only. `increment` / `recordGauge` / `incrementDuration` never reject: callers may
23
+ * `void` them.
24
+ */
25
+ export declare class StatsService {
26
+ private readonly _o;
27
+ private readonly _logger;
28
+ private readonly _granularities;
29
+ private _flushing;
30
+ /** `write`: an increment was accepted here; `flush`: buckets of these namespaces reached the store. */
31
+ readonly changed$: Subject<StatsChange>;
32
+ constructor(_o: StatsModuleOptions);
33
+ /** Hot path: buffer only, no store I/O. Never rejects (rule 14); a bad key or a buffer outage drops the write. */
34
+ increment(p: StatIncrement): Promise<void>;
35
+ /** A gauge sample: `{ sum: v, n: 1 }` per value in each bucket; read the mean with `statGaugeAverage`. */
36
+ recordGauge({ values, ...rest }: StatGaugeSample): Promise<void>;
37
+ /**
38
+ * A span cut at every bucket boundary of the finest granularity written (rule 24): 23:40–01:10 gives each hour /
39
+ * day only its own seconds; coarser buckets get the sum of their pieces. Default granularities: the module's
40
+ * without `min`. Record closed pieces progressively for long spans (crash = the open piece is lost).
41
+ */
42
+ incrementDuration(p: StatDurationIncrement): Promise<void>;
43
+ /**
44
+ * Moves taken deltas into the store, which adds them. Safe with several instances on one buffer: a bucket is taken
45
+ * by one flusher only, and a batch is applied at most once (store flush log). On a store failure the batch's
46
+ * deltas go back into the buffer (or stay in flight for a retry when the outcome is unknown). Concurrent calls in
47
+ * one process share one run. Never rejects.
48
+ */
49
+ flush(): Promise<StatFlushResult>;
50
+ /** Hard-delete store rows past retention (rule 12) and old flush-log rows. Never rejects. */
51
+ prune(now?: Date): Promise<void>;
52
+ /**
53
+ * Gap-filled timeline (rule 10). Without `subjectType` every series of the namespace is summed (rule 8);
54
+ * `subjectId` without `subjectType` is a 400. At most 5000 points. Scope `subjectType` / `subjectId` to what the
55
+ * caller may see before calling this (rule 13).
56
+ */
57
+ timeline(q: StatTimelineQuery): Promise<StatTimeline>;
58
+ /** Today (UTC day) and all time, from `day` buckets (the namespace must write `day`). */
59
+ totals(series: StatSeriesFilter, now?: Date): Promise<StatTotals>;
60
+ /** Like `totals`, kept per series (rule 27): subject and series key stay in each row. */
61
+ seriesTotals(series: StatSeriesFilter, now?: Date): Promise<StatSeriesTotals>;
62
+ /**
63
+ * The last `days` local days of `timeZone` (today included), summed from UTC `hour` (or `min`) buckets (rule 17).
64
+ * DST-safe. A bucket belongs to the local day of its start, so with `hour` a :30 offset shifts half an hour.
65
+ */
66
+ localDays(q: StatLocalDaysQuery): Promise<StatLocalDay[]>;
67
+ /** Anything of the namespace in the store or still unflushed here (backfill guard, rule 25). */
68
+ hasNamespace(namespace: string): Promise<boolean>;
69
+ /** Normalized buckets of one write, or `null` when the series is rejected (logged) or nothing is left. */
70
+ private _bucketsOf;
71
+ private _write;
72
+ private _flush;
73
+ /** One batch: merge → ack; on failure find out whether it committed, then ack, restore, or leave it in flight. */
74
+ private _apply;
75
+ private _count;
76
+ /** Store cells plus matching unflushed buckets (S4). */
77
+ private _cells;
78
+ private _sum;
79
+ private _seriesCells;
80
+ }