@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,33 @@
1
+ import type { StatGranularity, StatMetrics } from '../../stats.types';
2
+ export declare const METRIC_SNAPSHOTS_TABLE = "metric_snapshots";
3
+ export declare const METRIC_SNAPSHOT_FLUSHES_TABLE = "metric_snapshot_flushes";
4
+ export declare const METRIC_SNAPSHOTS_UNIQUE = "uq_metric_snapshots_series_period";
5
+ /**
6
+ * One bucket's totals. Add it to the app's TypeORM `entities` (or `autoLoadEntities` via `TypeOrmModule.forFeature`).
7
+ *
8
+ * No `@Unique` on purpose: TypeORM can't express `NULLS NOT DISTINCT`, and a decorator would make
9
+ * `migration:generate` write a plain UNIQUE (global series would duplicate on every flush, rule 9). The constraint
10
+ * lives in the migration (`MetricSnapshotsMigrationBase`); `migration:generate` proposes dropping it each time —
11
+ * delete those lines (rule 23). No soft delete: snapshots are derived data.
12
+ */
13
+ export declare class MetricSnapshotEntity {
14
+ id: string;
15
+ namespace: string;
16
+ subjectType: string;
17
+ /** Polymorphic ref, no FK. */
18
+ subjectId: string | null;
19
+ seriesKey: string;
20
+ granularity: StatGranularity;
21
+ periodStart: Date;
22
+ metrics: StatMetrics;
23
+ snapshotAt: Date;
24
+ createdAt: Date;
25
+ updatedAt: Date;
26
+ }
27
+ /** Flush log: one row per applied (or fenced) batch id — what makes an additive flush safe to retry. */
28
+ export declare class MetricSnapshotFlushEntity {
29
+ id: string;
30
+ /** `applied` | `fenced`. */
31
+ state: 'applied' | 'fenced';
32
+ createdAt: Date;
33
+ }
@@ -0,0 +1,95 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.MetricSnapshotFlushEntity = exports.MetricSnapshotEntity = exports.METRIC_SNAPSHOTS_UNIQUE = exports.METRIC_SNAPSHOT_FLUSHES_TABLE = exports.METRIC_SNAPSHOTS_TABLE = void 0;
13
+ const typeorm_1 = require("typeorm");
14
+ exports.METRIC_SNAPSHOTS_TABLE = 'metric_snapshots';
15
+ exports.METRIC_SNAPSHOT_FLUSHES_TABLE = 'metric_snapshot_flushes';
16
+ exports.METRIC_SNAPSHOTS_UNIQUE = 'uq_metric_snapshots_series_period';
17
+ /**
18
+ * One bucket's totals. Add it to the app's TypeORM `entities` (or `autoLoadEntities` via `TypeOrmModule.forFeature`).
19
+ *
20
+ * No `@Unique` on purpose: TypeORM can't express `NULLS NOT DISTINCT`, and a decorator would make
21
+ * `migration:generate` write a plain UNIQUE (global series would duplicate on every flush, rule 9). The constraint
22
+ * lives in the migration (`MetricSnapshotsMigrationBase`); `migration:generate` proposes dropping it each time —
23
+ * delete those lines (rule 23). No soft delete: snapshots are derived data.
24
+ */
25
+ let MetricSnapshotEntity = class MetricSnapshotEntity {
26
+ };
27
+ exports.MetricSnapshotEntity = MetricSnapshotEntity;
28
+ __decorate([
29
+ (0, typeorm_1.PrimaryGeneratedColumn)('uuid'),
30
+ __metadata("design:type", String)
31
+ ], MetricSnapshotEntity.prototype, "id", void 0);
32
+ __decorate([
33
+ (0, typeorm_1.Column)({ type: 'varchar', length: 255 }),
34
+ __metadata("design:type", String)
35
+ ], MetricSnapshotEntity.prototype, "namespace", void 0);
36
+ __decorate([
37
+ (0, typeorm_1.Column)({ name: 'subject_type', type: 'varchar', length: 64 }),
38
+ __metadata("design:type", String)
39
+ ], MetricSnapshotEntity.prototype, "subjectType", void 0);
40
+ __decorate([
41
+ (0, typeorm_1.Column)({ name: 'subject_id', type: 'varchar', length: 255, nullable: true }),
42
+ __metadata("design:type", String)
43
+ ], MetricSnapshotEntity.prototype, "subjectId", void 0);
44
+ __decorate([
45
+ (0, typeorm_1.Column)({ name: 'series_key', type: 'varchar', length: 255, default: '' }),
46
+ __metadata("design:type", String)
47
+ ], MetricSnapshotEntity.prototype, "seriesKey", void 0);
48
+ __decorate([
49
+ (0, typeorm_1.Column)({ type: 'varchar', length: 16 }),
50
+ __metadata("design:type", String)
51
+ ], MetricSnapshotEntity.prototype, "granularity", void 0);
52
+ __decorate([
53
+ (0, typeorm_1.Column)({ name: 'period_start', type: 'timestamptz' }),
54
+ __metadata("design:type", Date)
55
+ ], MetricSnapshotEntity.prototype, "periodStart", void 0);
56
+ __decorate([
57
+ (0, typeorm_1.Column)({ type: 'jsonb', default: () => `'{}'` }),
58
+ __metadata("design:type", Object)
59
+ ], MetricSnapshotEntity.prototype, "metrics", void 0);
60
+ __decorate([
61
+ (0, typeorm_1.Column)({ name: 'snapshot_at', type: 'timestamptz', default: () => 'NOW()' }),
62
+ __metadata("design:type", Date)
63
+ ], MetricSnapshotEntity.prototype, "snapshotAt", void 0);
64
+ __decorate([
65
+ (0, typeorm_1.CreateDateColumn)({ name: 'created_at', type: 'timestamptz' }),
66
+ __metadata("design:type", Date)
67
+ ], MetricSnapshotEntity.prototype, "createdAt", void 0);
68
+ __decorate([
69
+ (0, typeorm_1.UpdateDateColumn)({ name: 'updated_at', type: 'timestamptz' }),
70
+ __metadata("design:type", Date)
71
+ ], MetricSnapshotEntity.prototype, "updatedAt", void 0);
72
+ exports.MetricSnapshotEntity = MetricSnapshotEntity = __decorate([
73
+ (0, typeorm_1.Entity)(exports.METRIC_SNAPSHOTS_TABLE),
74
+ (0, typeorm_1.Index)('idx_metric_snapshots_ns_period', ['namespace', 'granularity', 'periodStart']),
75
+ (0, typeorm_1.Index)('idx_metric_snapshots_subject', ['subjectType', 'subjectId', 'namespace', 'granularity', 'periodStart'])
76
+ ], MetricSnapshotEntity);
77
+ /** Flush log: one row per applied (or fenced) batch id — what makes an additive flush safe to retry. */
78
+ let MetricSnapshotFlushEntity = class MetricSnapshotFlushEntity {
79
+ };
80
+ exports.MetricSnapshotFlushEntity = MetricSnapshotFlushEntity;
81
+ __decorate([
82
+ (0, typeorm_1.PrimaryColumn)({ type: 'varchar', length: 64 }),
83
+ __metadata("design:type", String)
84
+ ], MetricSnapshotFlushEntity.prototype, "id", void 0);
85
+ __decorate([
86
+ (0, typeorm_1.Column)({ type: 'varchar', length: 16 }),
87
+ __metadata("design:type", String)
88
+ ], MetricSnapshotFlushEntity.prototype, "state", void 0);
89
+ __decorate([
90
+ (0, typeorm_1.CreateDateColumn)({ name: 'created_at', type: 'timestamptz' }),
91
+ __metadata("design:type", Date)
92
+ ], MetricSnapshotFlushEntity.prototype, "createdAt", void 0);
93
+ exports.MetricSnapshotFlushEntity = MetricSnapshotFlushEntity = __decorate([
94
+ (0, typeorm_1.Entity)(exports.METRIC_SNAPSHOT_FLUSHES_TABLE)
95
+ ], MetricSnapshotFlushEntity);
@@ -0,0 +1,20 @@
1
+ import type { MigrationInterface, QueryRunner } from 'typeorm';
2
+ /** PostgreSQL 15+ (`NULLS NOT DISTINCT`). */
3
+ export declare const METRIC_SNAPSHOTS_UP_SQL: string[];
4
+ /** The flush log alone — for an app that already has `metric_snapshots` (webhooxy). */
5
+ export declare const METRIC_SNAPSHOT_FLUSHES_UP_SQL: string[];
6
+ export declare const METRIC_SNAPSHOTS_DOWN_SQL: string[];
7
+ /**
8
+ * Migration template. The app adds one file with its own timestamp:
9
+ *
10
+ * ```ts
11
+ * export class MetricSnapshots1764300000000 extends MetricSnapshotsMigrationBase {
12
+ * name = 'MetricSnapshots1764300000000';
13
+ * }
14
+ * ```
15
+ */
16
+ export declare abstract class MetricSnapshotsMigrationBase implements MigrationInterface {
17
+ abstract name: string;
18
+ up(q: QueryRunner): Promise<void>;
19
+ down(q: QueryRunner): Promise<void>;
20
+ }
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MetricSnapshotsMigrationBase = exports.METRIC_SNAPSHOTS_DOWN_SQL = exports.METRIC_SNAPSHOT_FLUSHES_UP_SQL = exports.METRIC_SNAPSHOTS_UP_SQL = void 0;
4
+ const metric_snapshot_entity_1 = require("./metric-snapshot.entity");
5
+ /** PostgreSQL 15+ (`NULLS NOT DISTINCT`). */
6
+ exports.METRIC_SNAPSHOTS_UP_SQL = [
7
+ `CREATE TABLE IF NOT EXISTS ${metric_snapshot_entity_1.METRIC_SNAPSHOTS_TABLE} (
8
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
9
+ namespace VARCHAR(255) NOT NULL,
10
+ subject_type VARCHAR(64) NOT NULL,
11
+ subject_id VARCHAR(255) NULL,
12
+ series_key VARCHAR(255) NOT NULL DEFAULT '',
13
+ granularity VARCHAR(16) NOT NULL,
14
+ period_start TIMESTAMPTZ NOT NULL,
15
+ metrics JSONB NOT NULL DEFAULT '{}',
16
+ snapshot_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
17
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
18
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
19
+ CONSTRAINT ${metric_snapshot_entity_1.METRIC_SNAPSHOTS_UNIQUE} UNIQUE NULLS NOT DISTINCT
20
+ (namespace, subject_type, subject_id, series_key, granularity, period_start)
21
+ )`,
22
+ `CREATE INDEX IF NOT EXISTS idx_metric_snapshots_ns_period
23
+ ON ${metric_snapshot_entity_1.METRIC_SNAPSHOTS_TABLE} (namespace, granularity, period_start)`,
24
+ `CREATE INDEX IF NOT EXISTS idx_metric_snapshots_subject
25
+ ON ${metric_snapshot_entity_1.METRIC_SNAPSHOTS_TABLE} (subject_type, subject_id, namespace, granularity, period_start)`,
26
+ ];
27
+ /** The flush log alone — for an app that already has `metric_snapshots` (webhooxy). */
28
+ exports.METRIC_SNAPSHOT_FLUSHES_UP_SQL = [
29
+ `CREATE TABLE IF NOT EXISTS ${metric_snapshot_entity_1.METRIC_SNAPSHOT_FLUSHES_TABLE} (
30
+ id VARCHAR(64) PRIMARY KEY,
31
+ state VARCHAR(16) NOT NULL,
32
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
33
+ )`,
34
+ `CREATE INDEX IF NOT EXISTS idx_metric_snapshot_flushes_created
35
+ ON ${metric_snapshot_entity_1.METRIC_SNAPSHOT_FLUSHES_TABLE} (created_at)`,
36
+ ];
37
+ exports.METRIC_SNAPSHOTS_DOWN_SQL = [
38
+ `DROP TABLE IF EXISTS ${metric_snapshot_entity_1.METRIC_SNAPSHOT_FLUSHES_TABLE}`,
39
+ `DROP TABLE IF EXISTS ${metric_snapshot_entity_1.METRIC_SNAPSHOTS_TABLE}`,
40
+ ];
41
+ /**
42
+ * Migration template. The app adds one file with its own timestamp:
43
+ *
44
+ * ```ts
45
+ * export class MetricSnapshots1764300000000 extends MetricSnapshotsMigrationBase {
46
+ * name = 'MetricSnapshots1764300000000';
47
+ * }
48
+ * ```
49
+ */
50
+ class MetricSnapshotsMigrationBase {
51
+ async up(q) {
52
+ for (const sql of [...exports.METRIC_SNAPSHOTS_UP_SQL, ...exports.METRIC_SNAPSHOT_FLUSHES_UP_SQL])
53
+ await q.query(sql);
54
+ }
55
+ async down(q) {
56
+ for (const sql of exports.METRIC_SNAPSHOTS_DOWN_SQL)
57
+ await q.query(sql);
58
+ }
59
+ }
60
+ exports.MetricSnapshotsMigrationBase = MetricSnapshotsMigrationBase;
@@ -0,0 +1,48 @@
1
+ import type { StatFlushBatch } from '../../ports/stats-buffer';
2
+ import { type StatBatchFenceResult, type StatsStore } from '../../ports/stats-store';
3
+ import type { StatCellRow, StatFilter, StatGranularity, StatSeriesCellRow } from '../../stats.types';
4
+ /** What the store needs from a TypeORM `DataSource` / `EntityManager` (raw SQL only). */
5
+ export interface StatsSqlRunner {
6
+ query(sql: string, params?: unknown[]): Promise<any>;
7
+ }
8
+ export interface StatsSqlDataSource extends StatsSqlRunner {
9
+ transaction<T>(run: (manager: StatsSqlRunner) => Promise<T>): Promise<T>;
10
+ }
11
+ export interface TypeOrmStatsStoreOptions {
12
+ /** Default `metric_snapshots`. Schema-qualified names are fine (`stats.metric_snapshots`). */
13
+ table?: string;
14
+ /** Default `metric_snapshot_flushes`. */
15
+ flushLogTable?: string;
16
+ /** Rows per INSERT statement inside the one merge transaction. Default 500. */
17
+ chunkSize?: number;
18
+ }
19
+ /**
20
+ * PostgreSQL 15+ store over TypeORM's `DataSource` (raw SQL: the query builder can't join set-returning functions).
21
+ *
22
+ * `merge` adds per cell in the `ON CONFLICT` clause — `metrics[value][status] = old + delta`, cells of either side
23
+ * kept — so a total never goes down whatever the buffer lost. The flush-log row for the batch id is written in the
24
+ * same transaction: a retried batch is applied once, a fenced one is refused.
25
+ */
26
+ export declare class TypeOrmStatsStore implements StatsStore {
27
+ private readonly _db;
28
+ private readonly _table;
29
+ private readonly _log;
30
+ private readonly _chunk;
31
+ constructor(_db: StatsSqlDataSource, options?: TypeOrmStatsStoreOptions);
32
+ merge(batch: StatFlushBatch): Promise<void>;
33
+ fence(batchId: string): Promise<StatBatchFenceResult>;
34
+ sumCells(f: StatFilter): Promise<StatCellRow[]>;
35
+ sumSeries(f: StatFilter): Promise<StatSeriesCellRow[]>;
36
+ hasNamespace(namespace: string): Promise<boolean>;
37
+ /** Hard delete (snapshots are derived data). */
38
+ prune(granularity: StatGranularity, before: Date): Promise<number>;
39
+ pruneFlushLog(before: Date): Promise<number>;
40
+ private _upsert;
41
+ /** Sum duplicates (one statement can't touch a row twice) and sort, so concurrent merges lock rows in one order. */
42
+ private _dedupe;
43
+ private _where;
44
+ private _stateOf;
45
+ /** TypeORM returns rows for SELECT / RETURNING, `[rows, affected]` for UPDATE / DELETE on postgres. */
46
+ private _rows;
47
+ private _affected;
48
+ }
@@ -0,0 +1,190 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TypeOrmStatsStore = void 0;
4
+ const stats_store_1 = require("../../ports/stats-store");
5
+ const stat_metrics_1 = require("../../helpers/stat-metrics");
6
+ const metric_snapshot_entity_1 = require("./metric-snapshot.entity");
7
+ const UPSERT_COLS = 7;
8
+ const IDENT = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/;
9
+ // jsonb_each_text on a non-object fails the whole statement; legacy rows may hold scalars.
10
+ const OBJ = (expr) => `CASE WHEN jsonb_typeof(${expr}) = 'object' THEN ${expr} ELSE '{}'::jsonb END`;
11
+ /**
12
+ * PostgreSQL 15+ store over TypeORM's `DataSource` (raw SQL: the query builder can't join set-returning functions).
13
+ *
14
+ * `merge` adds per cell in the `ON CONFLICT` clause — `metrics[value][status] = old + delta`, cells of either side
15
+ * kept — so a total never goes down whatever the buffer lost. The flush-log row for the batch id is written in the
16
+ * same transaction: a retried batch is applied once, a fenced one is refused.
17
+ */
18
+ class TypeOrmStatsStore {
19
+ constructor(_db, options = {}) {
20
+ this._db = _db;
21
+ this._table = options.table ?? metric_snapshot_entity_1.METRIC_SNAPSHOTS_TABLE;
22
+ this._log = options.flushLogTable ?? metric_snapshot_entity_1.METRIC_SNAPSHOT_FLUSHES_TABLE;
23
+ if (!IDENT.test(this._table) || !IDENT.test(this._log)) {
24
+ throw new Error('TypeOrmStatsStore: table names must be plain identifiers');
25
+ }
26
+ this._chunk = Math.max(1, options.chunkSize ?? 500);
27
+ }
28
+ async merge(batch) {
29
+ const rows = this._dedupe(batch.buckets);
30
+ await this._db.transaction(async (m) => {
31
+ const inserted = await m.query(`INSERT INTO ${this._log} (id, state) VALUES ($1, 'applied') ON CONFLICT (id) DO NOTHING RETURNING id`, [batch.id]);
32
+ if (!this._rows(inserted).length) {
33
+ const state = await this._stateOf(m, batch.id);
34
+ if (state === 'fenced')
35
+ throw new stats_store_1.StatBatchFencedError(batch.id);
36
+ return; // applied before (a retry after a lost ack): nothing to add
37
+ }
38
+ for (let i = 0; i < rows.length; i += this._chunk)
39
+ await this._upsert(m, rows.slice(i, i + this._chunk));
40
+ });
41
+ }
42
+ async fence(batchId) {
43
+ // Waits on the key lock of a merge of the same id still in progress, then either sees its row or burns the id.
44
+ const inserted = await this._db.query(`INSERT INTO ${this._log} (id, state) VALUES ($1, 'fenced') ON CONFLICT (id) DO NOTHING RETURNING id`, [batchId]);
45
+ if (this._rows(inserted).length)
46
+ return 'fenced';
47
+ return (await this._stateOf(this._db, batchId)) ?? 'fenced';
48
+ }
49
+ async sumCells(f) {
50
+ const { where, params } = this._where(f);
51
+ const raw = await this._db.query(`SELECT s.period_start, v.key AS value, st.key AS status, SUM(st.value::numeric) AS count
52
+ FROM ${this._table} s
53
+ CROSS JOIN LATERAL jsonb_each(${OBJ('s.metrics')}) v
54
+ CROSS JOIN LATERAL jsonb_each_text(${OBJ('v.value')}) st
55
+ WHERE ${where}
56
+ GROUP BY s.period_start, v.key, st.key
57
+ ORDER BY s.period_start`, params);
58
+ return this._rows(raw).map((r) => ({
59
+ periodStart: new Date(r.period_start).toISOString(),
60
+ value: r.value,
61
+ status: r.status,
62
+ count: Number(r.count),
63
+ }));
64
+ }
65
+ async sumSeries(f) {
66
+ const { where, params } = this._where(f);
67
+ const raw = await this._db.query(`SELECT s.subject_type, s.subject_id, s.series_key, v.key AS value, st.key AS status,
68
+ SUM(st.value::numeric) AS count
69
+ FROM ${this._table} s
70
+ CROSS JOIN LATERAL jsonb_each(${OBJ('s.metrics')}) v
71
+ CROSS JOIN LATERAL jsonb_each_text(${OBJ('v.value')}) st
72
+ WHERE ${where}
73
+ GROUP BY s.subject_type, s.subject_id, s.series_key, v.key, st.key`, params);
74
+ return this._rows(raw).map((r) => ({
75
+ subjectType: r.subject_type,
76
+ subjectId: r.subject_id ?? null,
77
+ seriesKey: r.series_key,
78
+ value: r.value,
79
+ status: r.status,
80
+ count: Number(r.count),
81
+ }));
82
+ }
83
+ async hasNamespace(namespace) {
84
+ const raw = await this._db.query(`SELECT 1 FROM ${this._table} WHERE namespace = $1 LIMIT 1`, [namespace]);
85
+ return this._rows(raw).length > 0;
86
+ }
87
+ /** Hard delete (snapshots are derived data). */
88
+ async prune(granularity, before) {
89
+ const raw = await this._db.query(`DELETE FROM ${this._table} WHERE granularity = $1 AND period_start < $2`, [
90
+ granularity,
91
+ before.toISOString(),
92
+ ]);
93
+ return this._affected(raw);
94
+ }
95
+ async pruneFlushLog(before) {
96
+ const raw = await this._db.query(`DELETE FROM ${this._log} WHERE created_at < $1`, [before.toISOString()]);
97
+ return this._affected(raw);
98
+ }
99
+ async _upsert(m, rows) {
100
+ const values = rows
101
+ .map((_, i) => {
102
+ const p = (n) => `$${i * UPSERT_COLS + n}`;
103
+ return `(${p(1)}, ${p(2)}, ${p(3)}, ${p(4)}, ${p(5)}, ${p(6)}::timestamptz, ${p(7)}::jsonb, NOW())`;
104
+ })
105
+ .join(', ');
106
+ const params = rows.flatMap((r) => [
107
+ r.namespace,
108
+ r.subjectType,
109
+ r.subjectId ?? null,
110
+ r.seriesKey ?? '',
111
+ r.granularity,
112
+ r.periodStart.toISOString(),
113
+ JSON.stringify(r.metrics),
114
+ ]);
115
+ // Additive per cell: unnest old + new, sum per (value, status), fold back into value → status → n.
116
+ await m.query(`INSERT INTO ${this._table} AS s
117
+ (namespace, subject_type, subject_id, series_key, granularity, period_start, metrics, snapshot_at)
118
+ VALUES ${values}
119
+ ON CONFLICT (namespace, subject_type, subject_id, series_key, granularity, period_start)
120
+ DO UPDATE SET
121
+ metrics = (
122
+ SELECT COALESCE(jsonb_object_agg(c.value, c.cells), '{}'::jsonb)
123
+ FROM (
124
+ SELECT x.value, jsonb_object_agg(x.status, x.total) AS cells
125
+ FROM (
126
+ SELECT v.key AS value, st.key AS status, SUM(st.value::numeric) AS total
127
+ FROM (SELECT s.metrics AS m UNION ALL SELECT EXCLUDED.metrics) src
128
+ CROSS JOIN LATERAL jsonb_each(${OBJ('src.m')}) v
129
+ CROSS JOIN LATERAL jsonb_each_text(${OBJ('v.value')}) st
130
+ GROUP BY v.key, st.key
131
+ ) x
132
+ GROUP BY x.value
133
+ ) c
134
+ ),
135
+ snapshot_at = NOW(),
136
+ updated_at = NOW()`, params);
137
+ }
138
+ /** Sum duplicates (one statement can't touch a row twice) and sort, so concurrent merges lock rows in one order. */
139
+ _dedupe(buckets) {
140
+ const byKey = new Map();
141
+ for (const b of buckets) {
142
+ if (!Object.keys(b.metrics).length)
143
+ continue;
144
+ const k = (0, stat_metrics_1.statBucketId)(b);
145
+ const cur = byKey.get(k);
146
+ if (cur)
147
+ (0, stat_metrics_1.addStatMetrics)(cur.metrics, b.metrics);
148
+ else
149
+ byKey.set(k, { ...b, metrics: (0, stat_metrics_1.cloneStatMetrics)(b.metrics) });
150
+ }
151
+ return [...byKey.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([, v]) => v);
152
+ }
153
+ _where(f) {
154
+ const params = [f.namespace, f.granularity];
155
+ const where = ['s.namespace = $1', 's.granularity = $2'];
156
+ if (f.from)
157
+ where.push(`s.period_start >= $${params.push(f.from.toISOString())}`);
158
+ if (f.to)
159
+ where.push(`s.period_start < $${params.push(f.to.toISOString())}`);
160
+ if (f.subjectType !== undefined)
161
+ where.push(`s.subject_type = $${params.push(f.subjectType)}`);
162
+ if (f.subjectId === null)
163
+ where.push('s.subject_id IS NULL');
164
+ else if (f.subjectId !== undefined)
165
+ where.push(`s.subject_id = $${params.push(f.subjectId)}`);
166
+ if (f.seriesKey !== undefined)
167
+ where.push(`s.series_key = $${params.push(f.seriesKey)}`);
168
+ if (f.values?.length)
169
+ where.push(`v.key = ANY($${params.push(f.values)})`);
170
+ if (f.statuses?.length)
171
+ where.push(`st.key = ANY($${params.push(f.statuses)})`);
172
+ return { where: where.join(' AND '), params };
173
+ }
174
+ async _stateOf(m, id) {
175
+ const raw = await m.query(`SELECT state FROM ${this._log} WHERE id = $1`, [id]);
176
+ return this._rows(raw)[0]?.state;
177
+ }
178
+ /** TypeORM returns rows for SELECT / RETURNING, `[rows, affected]` for UPDATE / DELETE on postgres. */
179
+ _rows(raw) {
180
+ if (Array.isArray(raw) && raw.length === 2 && Array.isArray(raw[0]) && typeof raw[1] === 'number')
181
+ return raw[0];
182
+ return Array.isArray(raw) ? raw : (raw?.rows ?? []);
183
+ }
184
+ _affected(raw) {
185
+ if (Array.isArray(raw) && typeof raw[1] === 'number')
186
+ return raw[1];
187
+ return typeof raw?.rowCount === 'number' ? raw.rowCount : 0;
188
+ }
189
+ }
190
+ exports.TypeOrmStatsStore = TypeOrmStatsStore;
package/package.json CHANGED
@@ -1,6 +1,89 @@
1
1
  {
2
2
  "name": "@my-nestjs-kit/stats",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-dev.20261129010337",
4
+ "description": "Stats engine for NestJS: series x granularity buckets, a delta buffer (Redis or memory) flushed into an additive store (TypeORM / Postgres or memory), timelines.",
5
+ "keywords": [
6
+ "nestjs",
7
+ "nest",
8
+ "stats",
9
+ "metrics",
10
+ "timeseries",
11
+ "analytics"
12
+ ],
13
+ "license": "MIT",
14
+ "homepage": "https://github.com/sabationok/my-nestjs-kit/tree/main/packages/stats#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/sabationok/my-nestjs-kit/issues"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/sabationok/my-nestjs-kit.git",
21
+ "directory": "packages/stats"
22
+ },
23
+ "engines": {
24
+ "node": ">=18"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "main": "dist/index.js",
30
+ "types": "dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "require": "./dist/index.js",
35
+ "default": "./dist/index.js"
36
+ },
37
+ "./package.json": "./package.json"
38
+ },
39
+ "files": [
40
+ "dist",
41
+ "!dist/**/*.spec.*",
42
+ "!dist/**/*.tsbuildinfo",
43
+ "README.md",
44
+ "LICENSE"
45
+ ],
46
+ "peerDependencies": {
47
+ "@nestjs/common": "^10.4.1",
48
+ "rxjs": "^7.8.1",
49
+ "typeorm": "^0.3.28"
50
+ },
51
+ "devDependencies": {
52
+ "@nestjs/common": "10.4.20",
53
+ "@nestjs/core": "10.4.1",
54
+ "@nestjs/testing": "10.4.1",
55
+ "@types/jest": "29.5.12",
56
+ "@types/node": "20.11.28",
57
+ "ioredis": "5.8.2",
58
+ "jest": "29.7.0",
59
+ "reflect-metadata": "0.2.2",
60
+ "rxjs": "7.8.1",
61
+ "ts-jest": "29.1.2",
62
+ "typeorm": "0.3.28",
63
+ "typescript": "5.4.2"
64
+ },
65
+ "jest": {
66
+ "moduleFileExtensions": [
67
+ "js",
68
+ "json",
69
+ "ts"
70
+ ],
71
+ "rootDir": "src",
72
+ "testRegex": ".*\\.spec\\.ts$",
73
+ "transform": {
74
+ "^.+\\.ts$": [
75
+ "ts-jest",
76
+ {
77
+ "tsconfig": "<rootDir>/../tsconfig.spec.json"
78
+ }
79
+ ]
80
+ },
81
+ "testEnvironment": "node"
82
+ },
83
+ "scripts": {
84
+ "build": "rm -rf dist && tsc -p tsconfig.json",
85
+ "build:watch": "tsc -p tsconfig.json --watch",
86
+ "typecheck": "tsc -p tsconfig.spec.json",
87
+ "test": "jest"
88
+ }
6
89
  }