@hotmeshio/hotmesh 0.31.0 → 0.31.2

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hotmeshio/hotmesh",
3
- "version": "0.31.0",
3
+ "version": "0.31.2",
4
4
  "description": "Durable Workflow",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -288,7 +288,8 @@ export declare class EscalationClientService {
288
288
  * Adds are claim-agnostic by default; pass `assertClaim` for the same
289
289
  * claim-lock assertion as `resolve()` on the container row. Pass
290
290
  * `metadata` to merge an outcome patch into the container's GIN-indexed
291
- * metadata in the same UPDATE (reserved accumulate keys are rejected).
291
+ * metadata in the same UPDATE, and `reciprocal.metadata` to merge one
292
+ * into the reciprocal's (reserved accumulate keys are rejected).
292
293
  * A repeated key answers `duplicate-item` without touching the row
293
294
  * unless the accumulator was declared `unique: false`, which replaces
294
295
  * the entry in place.
@@ -696,7 +696,8 @@ class EscalationClientService {
696
696
  * Adds are claim-agnostic by default; pass `assertClaim` for the same
697
697
  * claim-lock assertion as `resolve()` on the container row. Pass
698
698
  * `metadata` to merge an outcome patch into the container's GIN-indexed
699
- * metadata in the same UPDATE (reserved accumulate keys are rejected).
699
+ * metadata in the same UPDATE, and `reciprocal.metadata` to merge one
700
+ * into the reciprocal's (reserved accumulate keys are rejected).
700
701
  * A repeated key answers `duplicate-item` without touching the row
701
702
  * unless the accumulator was declared `unique: false`, which replaces
702
703
  * the entry in place.
@@ -707,6 +708,7 @@ class EscalationClientService {
707
708
  }
708
709
  (0, accumulate_1.assertAccumulateItemKey)(params.itemKey);
709
710
  this._assertAccumulatePatch(params.metadata);
711
+ this._assertAccumulatePatch(params.reciprocal?.metadata);
710
712
  const ns = params.namespace ?? namespace ?? factory_1.APP_ID;
711
713
  const hm = await this._engine(null, ns);
712
714
  const store = hm.engine.store;
@@ -723,6 +725,7 @@ class EscalationClientService {
723
725
  async accumulateItemByMetadata(params, namespace) {
724
726
  (0, accumulate_1.assertAccumulateItemKey)(params.itemKey);
725
727
  this._assertAccumulatePatch(params.metadata);
728
+ this._assertAccumulatePatch(params.reciprocal?.metadata);
726
729
  const ns = params.namespace ?? namespace ?? factory_1.APP_ID;
727
730
  const hm = await this._engine(null, ns);
728
731
  const store = hm.engine.store;
@@ -63,6 +63,8 @@ export interface AccumulateStatementInput {
63
63
  payload: Record<string, unknown> | null;
64
64
  reciprocalPayload: Record<string, unknown> | null;
65
65
  metadata: Record<string, unknown> | null;
66
+ /** Merged into the reciprocal row's metadata, as `metadata` is into the container's. */
67
+ reciprocalMetadata?: Record<string, unknown> | null;
66
68
  actor: string | null;
67
69
  assertClaim: string | null;
68
70
  wakes: AccumulateWake[];
@@ -204,6 +204,7 @@ function buildAccumulateStatement(input) {
204
204
  const expected = p.add(input.reciprocal ? 2 : 1);
205
205
  const head = targetCtes(input.primary, input.reciprocal, input.namespace, p, itemKey, payload, rPayload);
206
206
  const { ctes: wakeSql, counts: wakeCounts } = wakeCtes(input.wakes, input.appId, input.schemaName, p);
207
+ const rMeta = p.add(input.reciprocalMetadata ? JSON.stringify(input.reciprocalMetadata) : null);
207
208
  const newKeys = `CASE WHEN s.keys ? s.item_key THEN s.keys ELSE s.keys || to_jsonb(s.item_key) END`;
208
209
  const newCount = `jsonb_array_length(${newKeys})`;
209
210
  const entry = `jsonb_build_object('at', to_jsonb(NOW()))
@@ -230,7 +231,7 @@ function buildAccumulateStatement(input) {
230
231
  SET envelope = COALESCE(e.envelope, '{}'::jsonb)
231
232
  || jsonb_build_object('${ITEMS}', ${newItems}),
232
233
  metadata = COALESCE(e.metadata, '{}'::jsonb)
233
- || CASE WHEN s.is_primary THEN COALESCE(${meta}::jsonb, '{}'::jsonb) ELSE '{}'::jsonb END
234
+ || COALESCE(CASE WHEN s.is_primary THEN ${meta}::jsonb ELSE ${rMeta}::jsonb END, '{}'::jsonb)
234
235
  || jsonb_build_object('${KEYS}', ${newKeys}, '${COUNT}', ${newCount}),
235
236
  status = CASE WHEN ${complete} THEN 'resolved' ELSE e.status END,
236
237
  resolved_at = CASE WHEN ${complete} THEN NOW() ELSE e.resolved_at END,
@@ -2440,6 +2440,7 @@ class PostgresStoreService extends __1.StoreService {
2440
2440
  payload: params.payload ?? null,
2441
2441
  reciprocalPayload: params.reciprocal?.payload ?? null,
2442
2442
  metadata: params.metadata ?? null,
2443
+ reciprocalMetadata: params.reciprocal?.metadata ?? null,
2443
2444
  actor: params.actor ?? null,
2444
2445
  assertClaim: params.assertClaim ?? null,
2445
2446
  wakes,
@@ -4,7 +4,32 @@ exports.getNotificationChannelName = exports.deploySchema = void 0;
4
4
  const enums_1 = require("../../../../modules/enums");
5
5
  const utils_1 = require("../../../../modules/utils");
6
6
  const procedures_1 = require("./procedures");
7
+ // Deploys already run (or running) per client and appId. Every engine and
8
+ // worker init calls deploySchema, so a process booting many workers would
9
+ // otherwise repeat the full DDL pass once per worker.
10
+ const deployments = new WeakMap();
7
11
  async function deploySchema(streamClient, appId, logger) {
12
+ let byApp = deployments.get(streamClient);
13
+ if (!byApp) {
14
+ byApp = new Map();
15
+ deployments.set(streamClient, byApp);
16
+ }
17
+ const existing = byApp.get(appId);
18
+ if (existing) {
19
+ return existing;
20
+ }
21
+ const deployment = runDeploySchema(streamClient, appId, logger);
22
+ byApp.set(appId, deployment);
23
+ //a failed deploy is retried by the next caller
24
+ deployment.catch(() => {
25
+ if (byApp.get(appId) === deployment) {
26
+ byApp.delete(appId);
27
+ }
28
+ });
29
+ return deployment;
30
+ }
31
+ exports.deploySchema = deploySchema;
32
+ async function runDeploySchema(streamClient, appId, logger) {
8
33
  const isPool = streamClient?.totalCount !== undefined &&
9
34
  streamClient?.idleCount !== undefined;
10
35
  const client = isPool ? await streamClient.connect() : streamClient;
@@ -69,7 +94,6 @@ async function deploySchema(streamClient, appId, logger) {
69
94
  }
70
95
  }
71
96
  }
72
- exports.deploySchema = deploySchema;
73
97
  function getAdvisoryLockId(appId) {
74
98
  return hashStringToInt(appId);
75
99
  }
@@ -128,28 +152,24 @@ async function waitForTablesCreation(streamClient, lockId, schemaName, logger) {
128
152
  throw new Error('Timeout waiting for stream table creation');
129
153
  }
130
154
  /**
131
- * Ensure correct indexes exist on existing databases. Drops stale
132
- * PR #169 split indexes that can't serve the single-pass OR query,
155
+ * Ensure correct indexes exist on existing databases. Drops legacy
156
+ * indexes, rebuilds a live index only when its definition is stale,
133
157
  * then creates the correct indexes via IF NOT EXISTS.
134
158
  */
135
159
  async function ensureIndexes(client, schemaName) {
136
160
  const engineTable = `${schemaName}.engine_streams`;
137
161
  const workerTable = `${schemaName}.worker_streams`;
138
- // Drop legacy indexes that don't include the priority column, plus
139
- // redundant ones: idx_*_expired_at duplicates the partial
140
- // idx_*_processed_volume for the retention purge, and
141
- // idx_*_stream_name_expired_at duplicates the leading column and
142
- // predicate of idx_*_message_fetch. Every index here is maintained on
143
- // each message's INSERT plus two non-HOT UPDATEs (reserve, ack).
162
+ // Drop legacy indexes: the PR #169 split indexes, plus redundant ones:
163
+ // idx_*_expired_at duplicates the partial idx_*_processed_volume for
164
+ // the retention purge, and idx_*_stream_name_expired_at duplicates the
165
+ // leading column and predicate of idx_*_message_fetch. Every index here
166
+ // is maintained on each message's INSERT plus two non-HOT UPDATEs
167
+ // (reserve, ack).
144
168
  for (const idx of [
145
169
  'idx_engine_streams_dequeue',
146
170
  'idx_engine_streams_stale_reservations',
147
171
  'idx_worker_streams_dequeue',
148
172
  'idx_worker_streams_stale_reservations',
149
- 'idx_engine_streams_active_messages',
150
- 'idx_engine_streams_message_fetch',
151
- 'idx_worker_streams_active_messages',
152
- 'idx_worker_streams_message_fetch',
153
173
  'idx_engine_streams_expired_at',
154
174
  'idx_engine_stream_name_expired_at',
155
175
  'idx_worker_streams_expired_at',
@@ -157,6 +177,24 @@ async function ensureIndexes(client, schemaName) {
157
177
  ]) {
158
178
  await client.query(`DROP INDEX IF EXISTS ${schemaName}.${idx}`);
159
179
  }
180
+ // Drop a live index only when its columns predate the current shape.
181
+ // Dropping a current index locks the stream tables and rebuilds from a
182
+ // full heap scan while every consumer is blocked.
183
+ const activeColumns = '(stream_name, priority DESC, visible_at, id)';
184
+ const fetchColumns = '(stream_name, priority DESC, id)';
185
+ const liveIndexColumns = {
186
+ idx_engine_streams_active_messages: activeColumns,
187
+ idx_engine_streams_message_fetch: fetchColumns,
188
+ idx_worker_streams_active_messages: activeColumns,
189
+ idx_worker_streams_message_fetch: fetchColumns,
190
+ };
191
+ const { rows: liveIndexes } = await client.query(`SELECT indexname, indexdef FROM pg_indexes
192
+ WHERE schemaname = lower($1) AND indexname = ANY($2::text[])`, [schemaName, Object.keys(liveIndexColumns)]);
193
+ for (const { indexname, indexdef } of liveIndexes) {
194
+ if (!indexdef.includes(liveIndexColumns[indexname])) {
195
+ await client.query(`DROP INDEX IF EXISTS ${schemaName}.${indexname}`);
196
+ }
197
+ }
160
198
  // Recreate with priority-aware ordering for priority DESC, id ASC dequeue
161
199
  await client.query(`
162
200
  CREATE INDEX IF NOT EXISTS idx_engine_streams_active_messages
@@ -579,6 +579,12 @@ export interface AccumulateReciprocalSelector {
579
579
  roles?: string[];
580
580
  /** Stored as the reciprocal entry's payload. */
581
581
  payload?: Record<string, unknown>;
582
+ /**
583
+ * Merged into the reciprocal row's GIN-indexed metadata in the same
584
+ * UPDATE, as `metadata` is into the container's. Reserved accumulate
585
+ * keys are rejected.
586
+ */
587
+ metadata?: Record<string, unknown>;
582
588
  }
583
589
  /**
584
590
  * Outcome of an `accumulateItem()` call.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hotmeshio/hotmesh",
3
- "version": "0.31.0",
3
+ "version": "0.31.2",
4
4
  "description": "Durable Workflow",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",