@venturekit/data 0.0.47 → 0.0.50

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.
package/README.md CHANGED
@@ -164,6 +164,29 @@ const rows = q
164
164
  : [];
165
165
  ```
166
166
 
167
+ ## Publish on change
168
+
169
+ `@venturekit/data/outbox` — a fact measured on a schedule (a month's usage, a
170
+ readiness report) goes out only when it says something new. `publishIfChanged`
171
+ keeps one fingerprint per aggregate and key in `vk_outbox_fingerprints` and
172
+ calls `publish` only when the payload's differs, recording it first in the
173
+ caller's transaction, so a concurrent pass publishes nothing twice and a
174
+ `publish` that throws takes the fingerprint back with it.
175
+
176
+ ```typescript
177
+ import { publishIfChanged, appendToOutboxIfChanged } from '@venturekit/data/outbox';
178
+
179
+ await withTransaction(async (tx) => {
180
+ const report = await measureMonth(tx, tenantId, month);
181
+ await publishIfChanged(tx.query,
182
+ { aggregateType: 'usage', aggregateId: tenantId, key: month, tenantId, payload: report, ignore: ['reportedAt'] },
183
+ () => recordEvent(tx, { type: 'usage.reported', payload: report })); // your outbox, or:
184
+ await appendToOutboxIfChanged(tx.query, event, { key: month, ignore: ['reportedAt'] }); // vk_outbox
185
+ });
186
+ ```
187
+
188
+ `initial: false` publishes only a change to something already published.
189
+
167
190
  ## API Reference
168
191
 
169
192
  See the [API reference](https://venturekit.dev/api-reference/data) for full documentation.
@@ -0,0 +1,82 @@
1
+ /**
2
+ * @venturekit/data — publish on change.
3
+ *
4
+ * A fact a service measures on a schedule — a tenant's month of usage, a readiness report
5
+ * recomputed every five minutes — is worth an event only when it says something new. Without
6
+ * a place to keep "what did we last say", every product grows its own: a hash column on a
7
+ * projection row here, a table keyed by month there, each comparing by hand, each with its own
8
+ * idea of what the payload's timestamp does to the comparison.
9
+ *
10
+ * {@link publishIfChanged} keeps one fingerprint per aggregate and key in
11
+ * `vk_outbox_fingerprints` (`0000_vk_data_outbox_fingerprints.sql`) and calls `publish` only
12
+ * when the payload's differs from the one last recorded. {@link appendToOutboxIfChanged} is the
13
+ * same over this package's own outbox.
14
+ *
15
+ * ### One transaction, record first
16
+ *
17
+ * The fingerprint is written with `INSERT … ON CONFLICT … DO UPDATE … WHERE … IS DISTINCT FROM
18
+ * … RETURNING`, which takes the row's lock until the transaction ends. A second pass for the
19
+ * same key running concurrently waits on it, then finds the fingerprint the first one committed
20
+ * and publishes nothing — the same change goes out once. That is why the record comes before
21
+ * `publish`, and why `querier` must be the transaction's: on the pool, a `publish` that failed
22
+ * would leave a change recorded and never sent. A `publish` that throws rolls both back.
23
+ */
24
+ import type { Querier } from '../query/index.js';
25
+ import type { AppendOutboxInput } from './postgres.js';
26
+ /** Default table name, created by `0000_vk_data_outbox_fingerprints.sql`. */
27
+ export declare const DEFAULT_FINGERPRINT_TABLE = "vk_outbox_fingerprints";
28
+ /**
29
+ * What a payload says, as a sha-256 hex digest of its canonical JSON. `ignore` names top-level
30
+ * fields left out — the instant a report was made, which changes on every pass and says nothing.
31
+ */
32
+ export declare function payloadFingerprint(payload: unknown, ignore?: readonly string[]): string;
33
+ export interface PublishIfChangedInput {
34
+ aggregateType: string;
35
+ aggregateId: string;
36
+ /** What is compared within the aggregate — a month, a report kind. Default `''`: the aggregate has one. */
37
+ key?: string;
38
+ /** Recorded with the fingerprint, for a tenant guard on the table. */
39
+ tenantId?: string | null;
40
+ payload: unknown;
41
+ /** Top-level payload fields left out of the comparison ({@link payloadFingerprint}). */
42
+ ignore?: readonly string[];
43
+ /**
44
+ * Whether a first payload — nothing recorded yet for this key — is published. Default `true`.
45
+ * `false` publishes only a change to something already published: a month nothing happened in
46
+ * is not worth a first report, but one that went quiet after a report is.
47
+ */
48
+ initial?: boolean;
49
+ }
50
+ export interface FingerprintOptions {
51
+ /** Table name. Validated as an identifier, since it is interpolated. */
52
+ tableName?: string;
53
+ }
54
+ export interface PublishIfChangedResult {
55
+ published: boolean;
56
+ fingerprint: string;
57
+ }
58
+ /**
59
+ * Call `publish` when `payload` differs from the last one recorded for its aggregate and key,
60
+ * and record it — on the caller's transaction (see the module's notes).
61
+ *
62
+ * ```ts
63
+ * await withTransaction(async (tx) => {
64
+ * const report = await measure(tx);
65
+ * await publishIfChanged(tx.query, { aggregateType: 'usage', aggregateId: tenantId, key: month, tenantId, payload: report, ignore: ['reportedAt'] },
66
+ * () => recordEvent(tx, { type: 'usage.reported', payload: report, ... }));
67
+ * });
68
+ * ```
69
+ */
70
+ export declare function publishIfChanged(querier: Querier, input: PublishIfChangedInput, publish: () => unknown, options?: FingerprintOptions): Promise<PublishIfChangedResult>;
71
+ export interface AppendIfChangedOptions extends Pick<PublishIfChangedInput, 'key' | 'ignore' | 'initial'> {
72
+ /** The outbox table ({@link appendToOutbox}'s `tableName`). */
73
+ tableName?: string;
74
+ /** The fingerprints table ({@link FingerprintOptions.tableName}). */
75
+ fingerprintTableName?: string;
76
+ }
77
+ /**
78
+ * {@link appendToOutbox} when the event's payload differs from the last one appended for its
79
+ * aggregate and `key` — {@link publishIfChanged} over this package's outbox.
80
+ */
81
+ export declare function appendToOutboxIfChanged(querier: Querier, event: AppendOutboxInput, options?: AppendIfChangedOptions): Promise<PublishIfChangedResult>;
82
+ //# sourceMappingURL=fingerprints.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fingerprints.d.ts","sourceRoot":"","sources":["../../src/outbox/fingerprints.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAGH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAGjD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAEvD,6EAA6E;AAC7E,eAAO,MAAM,yBAAyB,2BAA2B,CAAC;AAelE;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,GAAE,SAAS,MAAM,EAAO,GAAG,MAAM,CAM3F;AAED,MAAM,WAAW,qBAAqB;IACpC,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,2GAA2G;IAC3G,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,sEAAsE;IACtE,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,OAAO,EAAE,OAAO,CAAC;IACjB,wFAAwF;IACxF,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3B;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,kBAAkB;IACjC,wEAAwE;IACxE,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,sBAAsB;IACrC,SAAS,EAAE,OAAO,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,gBAAgB,CACpC,OAAO,EAAE,OAAO,EAChB,KAAK,EAAE,qBAAqB,EAC5B,OAAO,EAAE,MAAM,OAAO,EACtB,OAAO,GAAE,kBAAuB,GAC/B,OAAO,CAAC,sBAAsB,CAAC,CAyBjC;AAED,MAAM,WAAW,sBAAuB,SAAQ,IAAI,CAAC,qBAAqB,EAAE,KAAK,GAAG,QAAQ,GAAG,SAAS,CAAC;IACvG,+DAA+D;IAC/D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,qEAAqE;IACrE,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC/B;AAED;;;GAGG;AACH,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,OAAO,EAChB,KAAK,EAAE,iBAAiB,EACxB,OAAO,GAAE,sBAA2B,GACnC,OAAO,CAAC,sBAAsB,CAAC,CAejC"}
@@ -0,0 +1,100 @@
1
+ /**
2
+ * @venturekit/data — publish on change.
3
+ *
4
+ * A fact a service measures on a schedule — a tenant's month of usage, a readiness report
5
+ * recomputed every five minutes — is worth an event only when it says something new. Without
6
+ * a place to keep "what did we last say", every product grows its own: a hash column on a
7
+ * projection row here, a table keyed by month there, each comparing by hand, each with its own
8
+ * idea of what the payload's timestamp does to the comparison.
9
+ *
10
+ * {@link publishIfChanged} keeps one fingerprint per aggregate and key in
11
+ * `vk_outbox_fingerprints` (`0000_vk_data_outbox_fingerprints.sql`) and calls `publish` only
12
+ * when the payload's differs from the one last recorded. {@link appendToOutboxIfChanged} is the
13
+ * same over this package's own outbox.
14
+ *
15
+ * ### One transaction, record first
16
+ *
17
+ * The fingerprint is written with `INSERT … ON CONFLICT … DO UPDATE … WHERE … IS DISTINCT FROM
18
+ * … RETURNING`, which takes the row's lock until the transaction ends. A second pass for the
19
+ * same key running concurrently waits on it, then finds the fingerprint the first one committed
20
+ * and publishes nothing — the same change goes out once. That is why the record comes before
21
+ * `publish`, and why `querier` must be the transaction's: on the pool, a `publish` that failed
22
+ * would leave a change recorded and never sent. A `publish` that throws rolls both back.
23
+ */
24
+ import { createHash } from 'node:crypto';
25
+ import { assertSqlIdentifier } from '../internal/identifier.js';
26
+ import { appendToOutbox } from './postgres.js';
27
+ /** Default table name, created by `0000_vk_data_outbox_fingerprints.sql`. */
28
+ export const DEFAULT_FINGERPRINT_TABLE = 'vk_outbox_fingerprints';
29
+ /** Object keys in order at every depth, so two payloads that say the same thing hash the same however they were built. */
30
+ function canonical(value) {
31
+ if (value !== null && typeof value === 'object' && typeof value.toJSON === 'function') {
32
+ return canonical(value.toJSON());
33
+ }
34
+ if (Array.isArray(value))
35
+ return value.map(canonical);
36
+ if (value !== null && typeof value === 'object') {
37
+ const source = value;
38
+ return Object.fromEntries(Object.keys(source).sort().map((k) => [k, canonical(source[k])]));
39
+ }
40
+ return value;
41
+ }
42
+ /**
43
+ * What a payload says, as a sha-256 hex digest of its canonical JSON. `ignore` names top-level
44
+ * fields left out — the instant a report was made, which changes on every pass and says nothing.
45
+ */
46
+ export function payloadFingerprint(payload, ignore = []) {
47
+ let said = payload;
48
+ if (ignore.length > 0 && payload !== null && typeof payload === 'object' && !Array.isArray(payload)) {
49
+ said = Object.fromEntries(Object.entries(payload).filter(([k]) => !ignore.includes(k)));
50
+ }
51
+ return createHash('sha256').update(JSON.stringify(canonical(said)) ?? 'undefined').digest('hex');
52
+ }
53
+ /**
54
+ * Call `publish` when `payload` differs from the last one recorded for its aggregate and key,
55
+ * and record it — on the caller's transaction (see the module's notes).
56
+ *
57
+ * ```ts
58
+ * await withTransaction(async (tx) => {
59
+ * const report = await measure(tx);
60
+ * await publishIfChanged(tx.query, { aggregateType: 'usage', aggregateId: tenantId, key: month, tenantId, payload: report, ignore: ['reportedAt'] },
61
+ * () => recordEvent(tx, { type: 'usage.reported', payload: report, ... }));
62
+ * });
63
+ * ```
64
+ */
65
+ export async function publishIfChanged(querier, input, publish, options = {}) {
66
+ const table = options.tableName ?? DEFAULT_FINGERPRINT_TABLE;
67
+ assertSqlIdentifier(table, 'publishIfChanged.tableName');
68
+ const fingerprint = payloadFingerprint(input.payload, input.ignore);
69
+ const key = input.key ?? '';
70
+ const changed = input.initial === false
71
+ ? await querier(`UPDATE ${table} SET fingerprint = $4, published_at = now()
72
+ WHERE aggregate_type = $1 AND aggregate_id = $2 AND key = $3 AND fingerprint IS DISTINCT FROM $4
73
+ RETURNING 1 AS changed`, [input.aggregateType, input.aggregateId, key, fingerprint])
74
+ : await querier(`INSERT INTO ${table} (aggregate_type, aggregate_id, key, tenant_id, fingerprint)
75
+ VALUES ($1, $2, $3, $4, $5)
76
+ ON CONFLICT (aggregate_type, aggregate_id, key) DO UPDATE
77
+ SET fingerprint = EXCLUDED.fingerprint, tenant_id = EXCLUDED.tenant_id, published_at = now()
78
+ WHERE ${table}.fingerprint IS DISTINCT FROM EXCLUDED.fingerprint
79
+ RETURNING 1 AS changed`, [input.aggregateType, input.aggregateId, key, input.tenantId ?? null, fingerprint]);
80
+ if (changed.length === 0)
81
+ return { published: false, fingerprint };
82
+ await publish();
83
+ return { published: true, fingerprint };
84
+ }
85
+ /**
86
+ * {@link appendToOutbox} when the event's payload differs from the last one appended for its
87
+ * aggregate and `key` — {@link publishIfChanged} over this package's outbox.
88
+ */
89
+ export async function appendToOutboxIfChanged(querier, event, options = {}) {
90
+ return publishIfChanged(querier, {
91
+ aggregateType: event.aggregateType,
92
+ aggregateId: event.aggregateId,
93
+ key: options.key,
94
+ tenantId: event.tenantId,
95
+ payload: event.payload,
96
+ ignore: options.ignore,
97
+ initial: options.initial,
98
+ }, () => appendToOutbox(querier, event, { tableName: options.tableName }), { tableName: options.fingerprintTableName });
99
+ }
100
+ //# sourceMappingURL=fingerprints.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fingerprints.js","sourceRoot":"","sources":["../../src/outbox/fingerprints.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAG/C,6EAA6E;AAC7E,MAAM,CAAC,MAAM,yBAAyB,GAAG,wBAAwB,CAAC;AAElE,0HAA0H;AAC1H,SAAS,SAAS,CAAC,KAAc;IAC/B,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAQ,KAA8B,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;QAChH,OAAO,SAAS,CAAE,KAAmC,CAAC,MAAM,EAAE,CAAC,CAAC;IAClE,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACtD,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAChD,MAAM,MAAM,GAAG,KAAgC,CAAC;QAChD,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAA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. See
5
- * `./postgres.ts`.
5
+ * `./postgres.ts`; publish-on-change is `./fingerprints.ts`.
6
6
  */
7
7
  export { createPostgresOutboxStore, appendToOutbox, discardOutboxEvent, DEFAULT_OUTBOX_TABLE, } from './postgres.js';
8
8
  export type { EventActor, OutboxRow, OutboxFailure, AppendOutboxInput, PostgresOutboxStore, PostgresOutboxStoreOptions, } from './postgres.js';
9
+ export { publishIfChanged, appendToOutboxIfChanged, payloadFingerprint, DEFAULT_FINGERPRINT_TABLE, } from './fingerprints.js';
10
+ export type { PublishIfChangedInput, PublishIfChangedResult, FingerprintOptions, AppendIfChangedOptions, } from './fingerprints.js';
9
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/outbox/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,yBAAyB,EACzB,cAAc,EACd,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,eAAe,CAAC;AAEvB,YAAY,EACV,UAAU,EACV,SAAS,EACT,aAAa,EACb,iBAAiB,EACjB,mBAAmB,EACnB,0BAA0B,GAC3B,MAAM,eAAe,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/outbox/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,yBAAyB,EACzB,cAAc,EACd,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,eAAe,CAAC;AAEvB,YAAY,EACV,UAAU,EACV,SAAS,EACT,aAAa,EACb,iBAAiB,EACjB,mBAAmB,EACnB,0BAA0B,GAC3B,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,gBAAgB,EAChB,uBAAuB,EACvB,kBAAkB,EAClB,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAE3B,YAAY,EACV,qBAAqB,EACrB,sBAAsB,EACtB,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,mBAAmB,CAAC"}
@@ -2,7 +2,8 @@
2
2
  * @venturekit/data — Postgres outbox store.
3
3
  *
4
4
  * The storage half of `@venturekit/runtime/patterns`' transactional outbox. See
5
- * `./postgres.ts`.
5
+ * `./postgres.ts`; publish-on-change is `./fingerprints.ts`.
6
6
  */
7
7
  export { createPostgresOutboxStore, appendToOutbox, discardOutboxEvent, DEFAULT_OUTBOX_TABLE, } from './postgres.js';
8
+ export { publishIfChanged, appendToOutboxIfChanged, payloadFingerprint, DEFAULT_FINGERPRINT_TABLE, } from './fingerprints.js';
8
9
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/outbox/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,yBAAyB,EACzB,cAAc,EACd,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,eAAe,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/outbox/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,yBAAyB,EACzB,cAAc,EACd,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,eAAe,CAAC;AAWvB,OAAO,EACL,gBAAgB,EAChB,uBAAuB,EACvB,kBAAkB,EAClB,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venturekit/data",
3
- "version": "0.0.47",
3
+ "version": "0.0.50",
4
4
  "description": "Database and data layer for VentureKit",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -58,7 +58,7 @@
58
58
  },
59
59
  "dependencies": {
60
60
  "@aws-sdk/client-secrets-manager": "^3.1126.0",
61
- "@venturekit/core": "0.0.47",
61
+ "@venturekit/core": "0.0.50",
62
62
  "pg": "^8.12.0"
63
63
  },
64
64
  "devDependencies": {
@@ -0,0 +1,39 @@
1
+ -- @venturekit/data — publish on change.
2
+ --
3
+ -- Table created by this migration:
4
+ -- vk_outbox_fingerprints — the fingerprint of the last payload published, per aggregate and key
5
+ --
6
+ -- Backs `publishIfChanged()` / `appendToOutboxIfChanged()` (`src/outbox/fingerprints.ts`). A
7
+ -- fact a service measures on a schedule — a month's usage, a readiness report — is worth an
8
+ -- event only when it says something new; this is where "what did we last say" is kept, so the
9
+ -- comparison and the event commit in the same transaction.
10
+ --
11
+ -- # Why the `0000_` filename prefix
12
+ --
13
+ -- A tenant-scoped product guards this table from its own migrations — a foreign key to its
14
+ -- tenants, `vk_install_tenant_guards()` — exactly as it does `vk_push_devices`, and for the
15
+ -- same reason `0000_vk_notify_push_devices.sql` takes the prefix: the runner applies every
16
+ -- directory's files in name order, so a `vk_data_006_*` name would sort after the consumer's
17
+ -- `0xxx_*` file that alters it. Sorting after `0000_vk_data_foundation.sql` is incidental;
18
+ -- nothing here calls its functions.
19
+ --
20
+ -- Additive: one new table, no existing file edited, and nothing writes to it until a project
21
+ -- calls `publishIfChanged()`. No RLS policy is installed — `vk_install_tenant_guards()` needs
22
+ -- your application role; call it if you scope by `tenant_id`.
23
+
24
+ CREATE TABLE IF NOT EXISTS vk_outbox_fingerprints (
25
+ aggregate_type text NOT NULL,
26
+ aggregate_id text NOT NULL,
27
+ -- What is compared within the aggregate — a month, a report kind. '' when it has one.
28
+ key text NOT NULL DEFAULT '',
29
+ -- NULL for platform-global facts. Not part of the key: aggregate ids are unique on their own,
30
+ -- and this is the column a tenant guard reads.
31
+ tenant_id uuid,
32
+ -- sha-256 (hex) of the payload's canonical JSON, the fields named in `ignore` left out.
33
+ fingerprint text NOT NULL,
34
+ published_at timestamptz NOT NULL DEFAULT now(),
35
+ PRIMARY KEY (aggregate_type, aggregate_id, key)
36
+ );
37
+
38
+ COMMENT ON TABLE vk_outbox_fingerprints IS
39
+ 'The fingerprint of the last payload published per aggregate and key. publishIfChanged() publishes only when it differs, in the caller''s transaction.';