@hotmeshio/hotmesh 0.25.2 → 0.25.5
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/ISSUE.md +53 -0
- package/build/package.json +1 -1
- package/build/services/engine/completion.js +26 -0
- package/build/services/escalations/client.d.ts +10 -0
- package/build/services/escalations/client.js +67 -4
- package/build/services/router/consumption/index.d.ts +7 -1
- package/build/services/router/consumption/index.js +79 -16
- package/build/services/store/index.d.ts +10 -1
- package/build/services/store/providers/postgres/postgres.d.ts +27 -3
- package/build/services/store/providers/postgres/postgres.js +96 -5
- package/build/services/stream/index.d.ts +3 -0
- package/build/services/stream/providers/postgres/messages.d.ts +26 -1
- package/build/services/stream/providers/postgres/messages.js +126 -6
- package/build/services/stream/providers/postgres/postgres.d.ts +16 -0
- package/build/services/stream/providers/postgres/postgres.js +40 -2
- package/build/services/task/index.js +7 -2
- package/build/types/hmsh_escalations.d.ts +13 -0
- package/package.json +1 -1
package/ISSUE.md
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# ADDENDUM — lost condition wakes are NOT restart-dependent (registration-window race)
|
|
2
|
+
|
|
3
|
+
Follow-up to the earlier "Durable wakes lost across process restart" report filed
|
|
4
|
+
tonight (sleep timers + condition signals). New evidence sharpens the condition case.
|
|
5
|
+
|
|
6
|
+
## Reproduced with no restart involved
|
|
7
|
+
|
|
8
|
+
Same environment (hotmesh 0.25.4, Postgres, long-tail 0.7.3), process running
|
|
9
|
+
continuously the whole time:
|
|
10
|
+
|
|
11
|
+
- `13:59:36.204` — pill escalation created (conditionLT atomic park, child
|
|
12
|
+
`...-winddown-gluer-0`).
|
|
13
|
+
- `13:59:36.237` — row **resolved**, 33 ms after creation (a hot consumer was
|
|
14
|
+
already scanning the pond and grabbed it instantly).
|
|
15
|
+
- 15+ minutes later — the awaiting child is still `status > 0`, never woke;
|
|
16
|
+
its parent's `Promise.all` wedged with it.
|
|
17
|
+
|
|
18
|
+
## The pattern across all three observed condition cases
|
|
19
|
+
|
|
20
|
+
Every lost condition wake we have seen shares one property: **the resolve landed
|
|
21
|
+
sub-second after the conditionLT park** (33 ms, 232 ms, ~600 ms). Slow resolves
|
|
22
|
+
(seconds or minutes after park) have never lost a wake across hundreds of
|
|
23
|
+
station-worker resolutions tonight.
|
|
24
|
+
|
|
25
|
+
Hypothesis: a resolve that commits **inside the awaiting workflow's
|
|
26
|
+
wake-registration window** — after the escalation row is visible to consumers
|
|
27
|
+
but before the awaiter's subscription is fully registered — delivers to nobody,
|
|
28
|
+
and nothing ever re-checks the persisted row against sleeping awaiters. The
|
|
29
|
+
restart in the earlier case was likely incidental; the window is the bug.
|
|
30
|
+
|
|
31
|
+
## Suggested repro (tighter than the original)
|
|
32
|
+
|
|
33
|
+
1. Workflow A parks via `conditionLT` (the escalation-creating overload).
|
|
34
|
+
2. A hot loop polls for the row and resolves it the instant it appears
|
|
35
|
+
(sub-100 ms). No process kill needed.
|
|
36
|
+
3. Observe whether A ever wakes. In our runs, a same-process consumer beating
|
|
37
|
+
the registration window wedges A reliably enough to hit twice in one evening.
|
|
38
|
+
|
|
39
|
+
## Suggested direction (unchanged, reinforced)
|
|
40
|
+
|
|
41
|
+
Boot-time AND periodic reconciliation of resolved-rows-with-sleeping-awaiters
|
|
42
|
+
would heal both the restart loss and this race — the row carries the awaiting
|
|
43
|
+
`workflow_id`; the join is cheap. Making the wake itself a stream message
|
|
44
|
+
(liveness-redelivered since 0.25.4) also closes the window, since the message
|
|
45
|
+
persists until reserved and acked.
|
|
46
|
+
|
|
47
|
+
## Our workaround (in production use as of tonight)
|
|
48
|
+
|
|
49
|
+
Settlement guard in the watcher activity: after the row's outcome is known,
|
|
50
|
+
poll `durable.jobs` for the awaiting child's status; if still running ~10s
|
|
51
|
+
after its row resolved, terminate the child by id (terminate purges cleanly
|
|
52
|
+
since 0.25.4) and treat the row's persisted resolver payload as authoritative.
|
|
53
|
+
The parent catches the child's terminate rejection. Ugly but wedge-proof.
|
package/build/package.json
CHANGED
|
@@ -68,6 +68,7 @@ function resolveError(metadata) {
|
|
|
68
68
|
exports.resolveError = resolveError;
|
|
69
69
|
async function interrupt(instance, topic, jobId, options = {}) {
|
|
70
70
|
await instance.store.interrupt(topic, jobId, options);
|
|
71
|
+
await expireStreamMessages(instance, jobId);
|
|
71
72
|
const context = (await instance.getState(topic, jobId));
|
|
72
73
|
const completionOpts = {
|
|
73
74
|
interrupt: options.descend,
|
|
@@ -77,9 +78,34 @@ async function interrupt(instance, topic, jobId, options = {}) {
|
|
|
77
78
|
}
|
|
78
79
|
exports.interrupt = interrupt;
|
|
79
80
|
async function scrub(instance, jobId) {
|
|
81
|
+
await expireStreamMessages(instance, jobId);
|
|
80
82
|
await instance.store.scrub(jobId);
|
|
81
83
|
}
|
|
82
84
|
exports.scrub = scrub;
|
|
85
|
+
/**
|
|
86
|
+
* Soft-deletes the job's stream messages (queued, reserved, and
|
|
87
|
+
* scheduled retries) so no message belonging to a dead job is ever
|
|
88
|
+
* delivered again. Interrupting the job wins or throws before this
|
|
89
|
+
* runs; failures here are logged and absorbed because the delivery
|
|
90
|
+
* liveness guard drops any surviving message at claim time.
|
|
91
|
+
*/
|
|
92
|
+
async function expireStreamMessages(instance, jobId) {
|
|
93
|
+
try {
|
|
94
|
+
const expired = await instance.stream.expireJobMessages?.(jobId);
|
|
95
|
+
if (expired) {
|
|
96
|
+
instance.logger.info('engine-job-stream-messages-expired', {
|
|
97
|
+
jobId,
|
|
98
|
+
expired,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
instance.logger.error('engine-job-stream-expire-error', {
|
|
104
|
+
jobId,
|
|
105
|
+
error,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
83
109
|
/**
|
|
84
110
|
* Orchestrates all post-completion work for a finished job:
|
|
85
111
|
* notify parent, publish to subscribers, schedule cleanup.
|
|
@@ -72,6 +72,16 @@ export declare class EscalationClientService {
|
|
|
72
72
|
private _makeEngineFactory;
|
|
73
73
|
private _hashConnection;
|
|
74
74
|
private _deliverEscalationSignal;
|
|
75
|
+
/**
|
|
76
|
+
* Builds the wake publish as a SQL command so the store can commit it
|
|
77
|
+
* INSIDE the resolve transaction — the wake becomes durable with the
|
|
78
|
+
* resolved row, closing the crash window between resolve commit and
|
|
79
|
+
* post-commit signal delivery. Mirrors `_deliverEscalationSignal`'s
|
|
80
|
+
* topic fallback chain; returns null when no hook rule is deployed
|
|
81
|
+
* for any candidate topic (the caller then keeps post-commit
|
|
82
|
+
* delivery as the only path, preserving prior behavior).
|
|
83
|
+
*/
|
|
84
|
+
private _buildWakeCommand;
|
|
75
85
|
/**
|
|
76
86
|
* Returns all escalation rows matching the given filters. Each row includes
|
|
77
87
|
* a computed `available` field (true = claimable). Supports `sortBy`,
|
|
@@ -3,8 +3,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.EscalationClientService = void 0;
|
|
4
4
|
const enums_1 = require("../../modules/enums");
|
|
5
5
|
const utils_1 = require("../../modules/utils");
|
|
6
|
+
const key_1 = require("../../modules/key");
|
|
6
7
|
const hotmesh_1 = require("../hotmesh");
|
|
7
8
|
const types_1 = require("../../types");
|
|
9
|
+
const stream_1 = require("../../types/stream");
|
|
8
10
|
const factory_1 = require("../durable/schemas/factory");
|
|
9
11
|
/**
|
|
10
12
|
* Standalone client for the `public.hmsh_escalations` signal-pause surface.
|
|
@@ -145,6 +147,46 @@ class EscalationClientService {
|
|
|
145
147
|
catch { }
|
|
146
148
|
return delivered;
|
|
147
149
|
}
|
|
150
|
+
/**
|
|
151
|
+
* Builds the wake publish as a SQL command so the store can commit it
|
|
152
|
+
* INSIDE the resolve transaction — the wake becomes durable with the
|
|
153
|
+
* resolved row, closing the crash window between resolve commit and
|
|
154
|
+
* post-commit signal delivery. Mirrors `_deliverEscalationSignal`'s
|
|
155
|
+
* topic fallback chain; returns null when no hook rule is deployed
|
|
156
|
+
* for any candidate topic (the caller then keeps post-commit
|
|
157
|
+
* delivery as the only path, preserving prior behavior).
|
|
158
|
+
*/
|
|
159
|
+
async _buildWakeCommand(ns, topic, signalKey, data) {
|
|
160
|
+
const hm = await this._engine(null, ns);
|
|
161
|
+
const engine = hm.engine;
|
|
162
|
+
const candidates = [topic, `${ns}.wfs.signal`, `${ns}.wfs.wait`].filter(Boolean);
|
|
163
|
+
for (const candidate of candidates) {
|
|
164
|
+
try {
|
|
165
|
+
const hookRule = await engine.taskService.getHookRule(candidate);
|
|
166
|
+
if (!hookRule)
|
|
167
|
+
continue;
|
|
168
|
+
const [aid] = await engine.getSchema(`.${hookRule.to}`);
|
|
169
|
+
const streamData = {
|
|
170
|
+
type: stream_1.StreamDataType.WEBHOOK,
|
|
171
|
+
status: types_1.StreamStatus.SUCCESS,
|
|
172
|
+
code: 200,
|
|
173
|
+
metadata: { guid: (0, utils_1.guid)(), aid, topic: candidate },
|
|
174
|
+
data: { id: signalKey, data },
|
|
175
|
+
};
|
|
176
|
+
const streamKey = engine.stream.mintKey(key_1.KeyType.STREAMS, {
|
|
177
|
+
topic: null,
|
|
178
|
+
});
|
|
179
|
+
const { sql, params } = engine.stream._publishMessages(streamKey, [
|
|
180
|
+
JSON.stringify(streamData),
|
|
181
|
+
]);
|
|
182
|
+
return { forSignalKey: signalKey, sql, params };
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
/* candidate not deployed — try the next topic */
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
148
190
|
// ─── Public API ─────────────────────────────────────────────────────────────
|
|
149
191
|
/**
|
|
150
192
|
* Returns all escalation rows matching the given filters. Each row includes
|
|
@@ -292,10 +334,19 @@ class EscalationClientService {
|
|
|
292
334
|
const ns = (params.namespace ?? namespace) ?? factory_1.APP_ID;
|
|
293
335
|
const hm = await this._engine(null, ns);
|
|
294
336
|
const store = hm.engine.store;
|
|
295
|
-
|
|
337
|
+
//pre-build the wake so it commits INSIDE the resolve transaction; the
|
|
338
|
+
//row's signal routing (signal_key, topic) is immutable after creation
|
|
339
|
+
let wakeCommand = null;
|
|
340
|
+
const preview = await store.getEscalation(params.id, params.namespace);
|
|
341
|
+
if (preview?.signal_key) {
|
|
342
|
+
wakeCommand = await this._buildWakeCommand(ns, preview.topic, preview.signal_key, params.resolverPayload ?? {});
|
|
343
|
+
}
|
|
344
|
+
const dbResult = await store.resolveEscalation({ id: params.id, resolverPayload: params.resolverPayload, metadata: params.metadata }, wakeCommand ?? undefined);
|
|
296
345
|
if (!dbResult.ok)
|
|
297
346
|
return dbResult;
|
|
298
|
-
if (dbResult.signalKey) {
|
|
347
|
+
if (dbResult.signalKey && !dbResult.wakeEnqueued) {
|
|
348
|
+
//the wake was not part of the commit (no hook rule found, or the
|
|
349
|
+
//enqueue was rolled back to its savepoint) — deliver post-commit
|
|
299
350
|
await this._deliverEscalationSignal(ns, dbResult.topic, {
|
|
300
351
|
id: dbResult.signalKey,
|
|
301
352
|
data: params.resolverPayload ?? {},
|
|
@@ -316,10 +367,22 @@ class EscalationClientService {
|
|
|
316
367
|
const ns = (params.namespace ?? namespace) ?? factory_1.APP_ID;
|
|
317
368
|
const hm = await this._engine(null, ns);
|
|
318
369
|
const store = hm.engine.store;
|
|
319
|
-
|
|
370
|
+
//peek the row the resolve is expected to lock and pre-build its wake;
|
|
371
|
+
//the forSignalKey guard covers the race where a different row wins
|
|
372
|
+
let wakeCommand = null;
|
|
373
|
+
const preview = await store.peekEscalationByMetadata({
|
|
374
|
+
key: params.key,
|
|
375
|
+
value: params.value,
|
|
376
|
+
roles: params.roles,
|
|
377
|
+
namespace: params.namespace,
|
|
378
|
+
});
|
|
379
|
+
if (preview?.signalKey) {
|
|
380
|
+
wakeCommand = await this._buildWakeCommand(ns, preview.topic, preview.signalKey, params.resolverPayload ?? {});
|
|
381
|
+
}
|
|
382
|
+
const dbResult = await store.resolveEscalationByMetadata({ key: params.key, value: params.value, resolverPayload: params.resolverPayload, roles: params.roles, metadata: params.metadata }, wakeCommand ?? undefined);
|
|
320
383
|
if (!dbResult.ok)
|
|
321
384
|
return dbResult;
|
|
322
|
-
if (dbResult.signalKey) {
|
|
385
|
+
if (dbResult.signalKey && !dbResult.wakeEnqueued) {
|
|
323
386
|
await this._deliverEscalationSignal(ns, dbResult.topic, {
|
|
324
387
|
id: dbResult.signalKey,
|
|
325
388
|
data: params.resolverPayload ?? {},
|
|
@@ -30,6 +30,7 @@ export declare class ConsumptionManager<S extends StreamService<ProviderClient,
|
|
|
30
30
|
private duressManager?;
|
|
31
31
|
private onDuressChange?;
|
|
32
32
|
private messagesSinceLastEval;
|
|
33
|
+
private canExtendReservations;
|
|
33
34
|
private adaptiveReservationTimeout;
|
|
34
35
|
private adaptiveBatchSize;
|
|
35
36
|
private lastDepthCheckAt;
|
|
@@ -52,7 +53,12 @@ export declare class ConsumptionManager<S extends StreamService<ProviderClient,
|
|
|
52
53
|
consumeMessages(stream: string, group: string, consumer: string, callback: (streamData: StreamData) => Promise<StreamDataResponse | void>): Promise<void>;
|
|
53
54
|
private consumeWithNotifications;
|
|
54
55
|
private consumeWithPolling;
|
|
55
|
-
|
|
56
|
+
/**
|
|
57
|
+
* Whether reservation heartbeats are available: the provider must
|
|
58
|
+
* implement extendReservation and advertise the capability.
|
|
59
|
+
*/
|
|
60
|
+
private supportsHeartbeat;
|
|
61
|
+
consumeOne(stream: string, group: string, id: string, input: StreamData, callback: (streamData: StreamData) => Promise<StreamDataResponse | void>, consumer?: string): Promise<void>;
|
|
56
62
|
execStreamLeg(input: StreamData, stream: string, id: string, callback: (streamData: StreamData) => Promise<StreamDataResponse | void>): Promise<StreamDataResponse>;
|
|
57
63
|
ackAndDelete(stream: string, group: string, id: string): Promise<void>;
|
|
58
64
|
ackAndDeleteBatch(stream: string, group: string, ids: string[]): Promise<void>;
|
|
@@ -195,7 +195,7 @@ class ConsumptionManager {
|
|
|
195
195
|
if (this.lifecycleManager.isStopped(group, consumer, stream)) {
|
|
196
196
|
return;
|
|
197
197
|
}
|
|
198
|
-
return this.consumeOne(stream, group, message.id, message.data, callback);
|
|
198
|
+
return this.consumeOne(stream, group, message.id, message.data, callback, consumer);
|
|
199
199
|
});
|
|
200
200
|
// Process all messages in parallel
|
|
201
201
|
await Promise.allSettled(processingPromises);
|
|
@@ -212,7 +212,7 @@ class ConsumptionManager {
|
|
|
212
212
|
if (this.lifecycleManager.isStopped(group, consumer, stream)) {
|
|
213
213
|
return;
|
|
214
214
|
}
|
|
215
|
-
await this.consumeOne(stream, group, message.id, message.data, callback);
|
|
215
|
+
await this.consumeOne(stream, group, message.id, message.data, callback, consumer);
|
|
216
216
|
}
|
|
217
217
|
}
|
|
218
218
|
// Check for pending messages if supported and enough time has passed
|
|
@@ -231,7 +231,7 @@ class ConsumptionManager {
|
|
|
231
231
|
if (this.lifecycleManager.isStopped(group, consumer, stream)) {
|
|
232
232
|
return;
|
|
233
233
|
}
|
|
234
|
-
return this.consumeOne(stream, group, message.id, message.data, callback);
|
|
234
|
+
return this.consumeOne(stream, group, message.id, message.data, callback, consumer);
|
|
235
235
|
});
|
|
236
236
|
await Promise.allSettled(reclaimPromises);
|
|
237
237
|
}
|
|
@@ -240,7 +240,7 @@ class ConsumptionManager {
|
|
|
240
240
|
if (this.lifecycleManager.isStopped(group, consumer, stream)) {
|
|
241
241
|
return;
|
|
242
242
|
}
|
|
243
|
-
await this.consumeOne(stream, group, message.id, message.data, callback);
|
|
243
|
+
await this.consumeOne(stream, group, message.id, message.data, callback, consumer);
|
|
244
244
|
}
|
|
245
245
|
}
|
|
246
246
|
}
|
|
@@ -349,7 +349,7 @@ class ConsumptionManager {
|
|
|
349
349
|
if (this.lifecycleManager.isStopped(group, consumer, stream)) {
|
|
350
350
|
return;
|
|
351
351
|
}
|
|
352
|
-
return this.consumeOne(stream, group, message.id, message.data, callback);
|
|
352
|
+
return this.consumeOne(stream, group, message.id, message.data, callback, consumer);
|
|
353
353
|
});
|
|
354
354
|
// Process all messages in parallel
|
|
355
355
|
await Promise.allSettled(processingPromises);
|
|
@@ -366,7 +366,7 @@ class ConsumptionManager {
|
|
|
366
366
|
if (this.lifecycleManager.isStopped(group, consumer, stream)) {
|
|
367
367
|
return;
|
|
368
368
|
}
|
|
369
|
-
await this.consumeOne(stream, group, message.id, message.data, callback);
|
|
369
|
+
await this.consumeOne(stream, group, message.id, message.data, callback, consumer);
|
|
370
370
|
}
|
|
371
371
|
}
|
|
372
372
|
// Check for pending messages if supported and enough time has passed
|
|
@@ -385,7 +385,7 @@ class ConsumptionManager {
|
|
|
385
385
|
if (this.lifecycleManager.isStopped(group, consumer, stream)) {
|
|
386
386
|
return;
|
|
387
387
|
}
|
|
388
|
-
return this.consumeOne(stream, group, message.id, message.data, callback);
|
|
388
|
+
return this.consumeOne(stream, group, message.id, message.data, callback, consumer);
|
|
389
389
|
});
|
|
390
390
|
await Promise.allSettled(reclaimPromises);
|
|
391
391
|
}
|
|
@@ -394,7 +394,7 @@ class ConsumptionManager {
|
|
|
394
394
|
if (this.lifecycleManager.isStopped(group, consumer, stream)) {
|
|
395
395
|
return;
|
|
396
396
|
}
|
|
397
|
-
await this.consumeOne(stream, group, message.id, message.data, callback);
|
|
397
|
+
await this.consumeOne(stream, group, message.id, message.data, callback, consumer);
|
|
398
398
|
}
|
|
399
399
|
}
|
|
400
400
|
}
|
|
@@ -434,7 +434,20 @@ class ConsumptionManager {
|
|
|
434
434
|
};
|
|
435
435
|
consume.call(this);
|
|
436
436
|
}
|
|
437
|
-
|
|
437
|
+
/**
|
|
438
|
+
* Whether reservation heartbeats are available: the provider must
|
|
439
|
+
* implement extendReservation and advertise the capability.
|
|
440
|
+
*/
|
|
441
|
+
supportsHeartbeat() {
|
|
442
|
+
if (this.canExtendReservations === undefined) {
|
|
443
|
+
this.canExtendReservations =
|
|
444
|
+
typeof this.stream.extendReservation === 'function' &&
|
|
445
|
+
this.stream.getProviderSpecificFeatures()
|
|
446
|
+
.supportsReservationExtension === true;
|
|
447
|
+
}
|
|
448
|
+
return this.canExtendReservations;
|
|
449
|
+
}
|
|
450
|
+
async consumeOne(stream, group, id, input, callback, consumer) {
|
|
438
451
|
this.logger.debug(`stream-read-one`, { group, stream, id });
|
|
439
452
|
// Poison message circuit breaker. This is a SAFETY NET that sits above
|
|
440
453
|
// the normal retry mechanism (ErrorHandler.handleRetry / shouldRetry).
|
|
@@ -498,20 +511,67 @@ class ConsumptionManager {
|
|
|
498
511
|
}
|
|
499
512
|
return;
|
|
500
513
|
}
|
|
501
|
-
// Lease
|
|
502
|
-
//
|
|
503
|
-
//
|
|
504
|
-
//
|
|
505
|
-
|
|
514
|
+
// Lease strategy. With heartbeat support (provider capability +
|
|
515
|
+
// consumer identity), the reservation is refreshed at half the base
|
|
516
|
+
// window while the callback runs, so an activity that outlives the
|
|
517
|
+
// window stays leased and executes exactly once; the deadline then
|
|
518
|
+
// acts as a runaway cap (HMSH_RESERVATION_TIMEOUT_MAX_S). A crashed
|
|
519
|
+
// consumer stops heartbeating and its message is rescued within one
|
|
520
|
+
// window through the normal claim path. Providers without extension
|
|
521
|
+
// keep the hard deadline at the reservation timeout (N), with
|
|
522
|
+
// reclaim at N+5s.
|
|
523
|
+
const canHeartbeat = Boolean(consumer) && this.supportsHeartbeat();
|
|
524
|
+
const deadlineS = canHeartbeat
|
|
525
|
+
? config_1.HMSH_RESERVATION_TIMEOUT_MAX_S
|
|
526
|
+
: this.adaptiveReservationTimeout;
|
|
527
|
+
const deadlineMs = deadlineS * 1000;
|
|
506
528
|
let output;
|
|
507
529
|
const telemetry = new telemetry_1.RouterTelemetry(this.appId);
|
|
508
530
|
const processingStart = Date.now();
|
|
509
531
|
try {
|
|
510
532
|
telemetry.startStreamSpan(input, this.role);
|
|
511
533
|
let deadlineTimer;
|
|
534
|
+
let rejectLease;
|
|
512
535
|
const deadlinePromise = new Promise((_, reject) => {
|
|
513
|
-
|
|
536
|
+
rejectLease = reject;
|
|
537
|
+
deadlineTimer = setTimeout(() => reject(new errors_1.LeaseExpiredError(deadlineMs, deadlineS)), deadlineMs);
|
|
514
538
|
});
|
|
539
|
+
// Heartbeat at half the BASE window (adaptive scaling only grows
|
|
540
|
+
// the claim window, so the base cadence always outpaces reclaim
|
|
541
|
+
// eligibility). A beat that reports 0 means the lease is gone —
|
|
542
|
+
// reclaimed by another consumer, acked, or the job was
|
|
543
|
+
// interrupted — so this execution abandons without acking. A beat
|
|
544
|
+
// that errors is transient and retries on the next tick. Fast
|
|
545
|
+
// callbacks settle before the first beat ever fires.
|
|
546
|
+
let heartbeatTimer;
|
|
547
|
+
if (canHeartbeat) {
|
|
548
|
+
const intervalMs = Math.max(1000, Math.floor((config_1.HMSH_RESERVATION_TIMEOUT_S * 1000) / 2));
|
|
549
|
+
heartbeatTimer = setInterval(() => {
|
|
550
|
+
this.stream
|
|
551
|
+
.extendReservation(stream, id, consumer)
|
|
552
|
+
.then((extended) => {
|
|
553
|
+
if (extended === 0) {
|
|
554
|
+
this.logger.warn('stream-lease-lost', {
|
|
555
|
+
group,
|
|
556
|
+
stream,
|
|
557
|
+
id,
|
|
558
|
+
consumer,
|
|
559
|
+
topic: input.metadata?.topic,
|
|
560
|
+
jobId: input.metadata?.jid,
|
|
561
|
+
});
|
|
562
|
+
rejectLease(new errors_1.LeaseExpiredError(deadlineMs, deadlineS));
|
|
563
|
+
}
|
|
564
|
+
})
|
|
565
|
+
.catch((error) => {
|
|
566
|
+
this.logger.warn('stream-lease-extend-error', {
|
|
567
|
+
group,
|
|
568
|
+
stream,
|
|
569
|
+
id,
|
|
570
|
+
error,
|
|
571
|
+
});
|
|
572
|
+
});
|
|
573
|
+
}, intervalMs);
|
|
574
|
+
}
|
|
515
575
|
try {
|
|
516
576
|
output = await Promise.race([
|
|
517
577
|
this.execStreamLeg(input, stream, id, callback.bind(this)),
|
|
@@ -520,6 +580,9 @@ class ConsumptionManager {
|
|
|
520
580
|
}
|
|
521
581
|
finally {
|
|
522
582
|
clearTimeout(deadlineTimer);
|
|
583
|
+
if (heartbeatTimer) {
|
|
584
|
+
clearInterval(heartbeatTimer);
|
|
585
|
+
}
|
|
523
586
|
}
|
|
524
587
|
telemetry.setStreamErrorFromOutput(output);
|
|
525
588
|
this.errorCount = 0;
|
|
@@ -536,7 +599,7 @@ class ConsumptionManager {
|
|
|
536
599
|
stream,
|
|
537
600
|
id,
|
|
538
601
|
deadlineMs,
|
|
539
|
-
reservationTimeoutS:
|
|
602
|
+
reservationTimeoutS: deadlineS,
|
|
540
603
|
topic: input.metadata?.topic,
|
|
541
604
|
activityId: input.metadata?.aid,
|
|
542
605
|
jobId: input.metadata?.jid,
|
|
@@ -68,8 +68,17 @@ declare abstract class StoreService<Provider extends ProviderClient, Transaction
|
|
|
68
68
|
* Leg1: Attempts to set the hook signal. If a pending signal occupies
|
|
69
69
|
* the key (race condition), overwrites it and returns the pending data.
|
|
70
70
|
* When called with a transaction, queues the setnxex (no pending detection).
|
|
71
|
+
*
|
|
72
|
+
* When `redelivery` is provided (the webhook routing for this hook),
|
|
73
|
+
* a consumed pending signal is republished as an engine stream message
|
|
74
|
+
* in the SAME transaction that overwrites the marker — the wake
|
|
75
|
+
* survives a crash at any instant. `pendingData` is then not returned,
|
|
76
|
+
* since the store already owns the redelivery.
|
|
71
77
|
*/
|
|
72
|
-
abstract setHookSignal(hook: HookSignal, transaction?: TransactionProvider
|
|
78
|
+
abstract setHookSignal(hook: HookSignal, transaction?: TransactionProvider, redelivery?: {
|
|
79
|
+
aid: string;
|
|
80
|
+
topic: string;
|
|
81
|
+
}): Promise<{
|
|
73
82
|
success: boolean;
|
|
74
83
|
pendingData?: string;
|
|
75
84
|
}>;
|
|
@@ -128,7 +128,10 @@ declare class PostgresStoreService extends StoreService<ProviderClient, Provider
|
|
|
128
128
|
*
|
|
129
129
|
* In a transaction: queues the setnxex; pending detection deferred.
|
|
130
130
|
*/
|
|
131
|
-
setHookSignal(hook: HookSignal, transaction?: ProviderTransaction
|
|
131
|
+
setHookSignal(hook: HookSignal, transaction?: ProviderTransaction, redelivery?: {
|
|
132
|
+
aid: string;
|
|
133
|
+
topic: string;
|
|
134
|
+
}): Promise<{
|
|
132
135
|
success: boolean;
|
|
133
136
|
pendingData?: string;
|
|
134
137
|
}>;
|
|
@@ -270,13 +273,34 @@ declare class PostgresStoreService extends StoreService<ProviderClient, Provider
|
|
|
270
273
|
claimEscalation(params: import('../../../../types/hmsh_escalations').ClaimEscalationParams): Promise<import('../../../../types/hmsh_escalations').ClaimEscalationResult>;
|
|
271
274
|
claimEscalationByMetadata(params: import('../../../../types/hmsh_escalations').ClaimByMetadataParams): Promise<import('../../../../types/hmsh_escalations').ClaimByMetadataResult>;
|
|
272
275
|
releaseEscalation(params: import('../../../../types/hmsh_escalations').ReleaseEscalationParams): Promise<import('../../../../types/hmsh_escalations').ReleaseEscalationResult>;
|
|
273
|
-
|
|
276
|
+
/**
|
|
277
|
+
* Executes a pre-built wake publish inside the currently open resolve
|
|
278
|
+
* transaction, guarded by a SAVEPOINT so a wake failure can never roll
|
|
279
|
+
* back the resolve itself. Returns true when the wake row committed
|
|
280
|
+
* with the transaction; false means the caller should fall back to
|
|
281
|
+
* post-commit delivery.
|
|
282
|
+
*/
|
|
283
|
+
private enqueueEscalationWake;
|
|
284
|
+
resolveEscalation(params: import('../../../../types/hmsh_escalations').ResolveEscalationParams, wakeCommand?: import('../../../../types/hmsh_escalations').EscalationWakeCommand): Promise<import('../../../../types/hmsh_escalations').ResolveEscalationResult & {
|
|
274
285
|
signalKey?: string | null;
|
|
275
286
|
topic?: string | null;
|
|
287
|
+
wakeEnqueued?: boolean;
|
|
276
288
|
}>;
|
|
277
|
-
|
|
289
|
+
/**
|
|
290
|
+
* Non-locking preview of the row `resolveEscalationByMetadata` would
|
|
291
|
+
* select — used to pre-build the wake command before the resolve
|
|
292
|
+
* transaction opens. The `forSignalKey` guard on the wake command
|
|
293
|
+
* handles the race where a different row wins the lock.
|
|
294
|
+
*/
|
|
295
|
+
peekEscalationByMetadata(params: import('../../../../types/hmsh_escalations').ResolveByMetadataParams): Promise<{
|
|
296
|
+
id: string;
|
|
297
|
+
signalKey: string | null;
|
|
298
|
+
topic: string | null;
|
|
299
|
+
} | null>;
|
|
300
|
+
resolveEscalationByMetadata(params: import('../../../../types/hmsh_escalations').ResolveByMetadataParams, wakeCommand?: import('../../../../types/hmsh_escalations').EscalationWakeCommand): Promise<import('../../../../types/hmsh_escalations').ResolveEscalationResult & {
|
|
278
301
|
signalKey?: string | null;
|
|
279
302
|
topic?: string | null;
|
|
303
|
+
wakeEnqueued?: boolean;
|
|
280
304
|
}>;
|
|
281
305
|
cancelEscalation(id: string, namespace?: string): Promise<import('../../../../types/hmsh_escalations').CancelEscalationResult>;
|
|
282
306
|
escalateEscalationToRole(params: import('../../../../types/hmsh_escalations').EscalateToRoleParams): Promise<import('../../../../types/hmsh_escalations').EscalationEntry | null>;
|
|
@@ -777,7 +777,7 @@ class PostgresStoreService extends __1.StoreService {
|
|
|
777
777
|
*
|
|
778
778
|
* In a transaction: queues the setnxex; pending detection deferred.
|
|
779
779
|
*/
|
|
780
|
-
async setHookSignal(hook, transaction) {
|
|
780
|
+
async setHookSignal(hook, transaction, redelivery) {
|
|
781
781
|
const key = this.mintKey(key_1.KeyType.SIGNALS, { appId: this.appId });
|
|
782
782
|
const { topic, resolved, jobId } = hook;
|
|
783
783
|
const signalKey = `${topic}:${resolved}`;
|
|
@@ -813,6 +813,45 @@ class PostgresStoreService extends __1.StoreService {
|
|
|
813
813
|
const captured = lockResult.rows[0]?.value;
|
|
814
814
|
const wasInsert = lockResult.rows[0]?.inserted;
|
|
815
815
|
const isPending = captured?.startsWith('$pending::');
|
|
816
|
+
if (isPending && redelivery) {
|
|
817
|
+
//consume the marker and commit its redelivery as ONE unit: the
|
|
818
|
+
//pending wake becomes a durable engine stream message in the
|
|
819
|
+
//same transaction that destroys the marker, so the wake
|
|
820
|
+
//survives a crash at any instant. A crash before COMMIT leaves
|
|
821
|
+
//the marker intact for the resume path to consume again.
|
|
822
|
+
const pendingData = captured.slice('$pending::'.length);
|
|
823
|
+
const message = JSON.stringify({
|
|
824
|
+
type: 'webhook',
|
|
825
|
+
status: 'success',
|
|
826
|
+
code: 200,
|
|
827
|
+
metadata: {
|
|
828
|
+
guid: (0, utils_1.guid)(),
|
|
829
|
+
aid: redelivery.aid,
|
|
830
|
+
topic: redelivery.topic,
|
|
831
|
+
},
|
|
832
|
+
data: JSON.parse(pendingData),
|
|
833
|
+
});
|
|
834
|
+
const schemaName = this.kvsql().safeName(this.appId);
|
|
835
|
+
await this.pgClient.query('BEGIN');
|
|
836
|
+
try {
|
|
837
|
+
await this.pgClient.query(`UPDATE ${tableName}
|
|
838
|
+
SET value = $1, expiry = NOW() + INTERVAL '${delay} seconds'
|
|
839
|
+
WHERE key = $2`, [jobId, storedKey]);
|
|
840
|
+
await this.pgClient.query(`INSERT INTO ${schemaName}.engine_streams
|
|
841
|
+
(stream_name, message, priority)
|
|
842
|
+
VALUES ($1, $2, 5)`, [this.appId, message]);
|
|
843
|
+
await this.pgClient.query('COMMIT');
|
|
844
|
+
}
|
|
845
|
+
catch (redeliveryError) {
|
|
846
|
+
await this.pgClient.query('ROLLBACK');
|
|
847
|
+
throw redeliveryError;
|
|
848
|
+
}
|
|
849
|
+
this.logger.warn('hook-signal-pending-redelivered', {
|
|
850
|
+
key: signalKey,
|
|
851
|
+
topic: redelivery.topic,
|
|
852
|
+
});
|
|
853
|
+
return { success: true };
|
|
854
|
+
}
|
|
816
855
|
if (!wasInsert) {
|
|
817
856
|
//step 2: row existed — overwrite with hook value
|
|
818
857
|
await this.pgClient.query(`UPDATE ${tableName}
|
|
@@ -1792,7 +1831,32 @@ class PostgresStoreService extends __1.StoreService {
|
|
|
1792
1831
|
return { ok: false, reason: 'wrong-assignee' };
|
|
1793
1832
|
return { ok: true, entry: row.entry_json };
|
|
1794
1833
|
}
|
|
1795
|
-
|
|
1834
|
+
/**
|
|
1835
|
+
* Executes a pre-built wake publish inside the currently open resolve
|
|
1836
|
+
* transaction, guarded by a SAVEPOINT so a wake failure can never roll
|
|
1837
|
+
* back the resolve itself. Returns true when the wake row committed
|
|
1838
|
+
* with the transaction; false means the caller should fall back to
|
|
1839
|
+
* post-commit delivery.
|
|
1840
|
+
*/
|
|
1841
|
+
async enqueueEscalationWake(wakeCommand, signalKey, escalationId) {
|
|
1842
|
+
if (!wakeCommand || !signalKey || wakeCommand.forSignalKey !== signalKey) {
|
|
1843
|
+
return false;
|
|
1844
|
+
}
|
|
1845
|
+
await this.pgClient.query('SAVEPOINT escalation_wake');
|
|
1846
|
+
try {
|
|
1847
|
+
await this.pgClient.query(wakeCommand.sql, wakeCommand.params);
|
|
1848
|
+
return true;
|
|
1849
|
+
}
|
|
1850
|
+
catch (error) {
|
|
1851
|
+
await this.pgClient.query('ROLLBACK TO SAVEPOINT escalation_wake');
|
|
1852
|
+
this.logger.warn('escalation-wake-enqueue-error', {
|
|
1853
|
+
escalationId,
|
|
1854
|
+
error: error.message,
|
|
1855
|
+
});
|
|
1856
|
+
return false;
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
async resolveEscalation(params, wakeCommand) {
|
|
1796
1860
|
const { id, namespace, resolverPayload, metadata } = params;
|
|
1797
1861
|
const payloadJson = resolverPayload ? JSON.stringify(resolverPayload) : null;
|
|
1798
1862
|
// metaJson is bound at a fixed index; the CASE no-ops when null so resolution
|
|
@@ -1835,15 +1899,41 @@ class PostgresStoreService extends __1.StoreService {
|
|
|
1835
1899
|
await this.pgClient.query('ROLLBACK');
|
|
1836
1900
|
return { ok: false, reason: 'already-resolved' };
|
|
1837
1901
|
}
|
|
1902
|
+
//the wake commits WITH the resolve: a crash after COMMIT leaves both
|
|
1903
|
+
//the resolved row and its wake message durable; a crash before
|
|
1904
|
+
//leaves neither. The engine_streams INSERT trigger emits the
|
|
1905
|
+
//delivery NOTIFY on commit.
|
|
1906
|
+
const wakeEnqueued = await this.enqueueEscalationWake(wakeCommand, signal_key, id);
|
|
1838
1907
|
await this.pgClient.query('COMMIT');
|
|
1839
|
-
return { ok: true, entry: updateResult.rows[0], signalKey: signal_key, topic };
|
|
1908
|
+
return { ok: true, entry: updateResult.rows[0], signalKey: signal_key, topic, wakeEnqueued };
|
|
1840
1909
|
}
|
|
1841
1910
|
catch (e) {
|
|
1842
1911
|
await this.pgClient.query('ROLLBACK');
|
|
1843
1912
|
throw e;
|
|
1844
1913
|
}
|
|
1845
1914
|
}
|
|
1846
|
-
|
|
1915
|
+
/**
|
|
1916
|
+
* Non-locking preview of the row `resolveEscalationByMetadata` would
|
|
1917
|
+
* select — used to pre-build the wake command before the resolve
|
|
1918
|
+
* transaction opens. The `forSignalKey` guard on the wake command
|
|
1919
|
+
* handles the race where a different row wins the lock.
|
|
1920
|
+
*/
|
|
1921
|
+
async peekEscalationByMetadata(params) {
|
|
1922
|
+
const { key, value, namespace, roles } = params;
|
|
1923
|
+
const filter = JSON.stringify({ [key]: value });
|
|
1924
|
+
const result = await this.pgClient.query(`SELECT id, signal_key, topic FROM public.hmsh_escalations
|
|
1925
|
+
WHERE ${namespace ? 'namespace = $3 AND' : ''}
|
|
1926
|
+
metadata @> $1::jsonb
|
|
1927
|
+
AND ($2::text[] IS NULL OR role = ANY($2::text[]))
|
|
1928
|
+
AND status IN ('pending', 'cancelled')
|
|
1929
|
+
ORDER BY priority ASC, created_at ASC
|
|
1930
|
+
LIMIT 1`, namespace ? [filter, roles ?? null, namespace] : [filter, roles ?? null]);
|
|
1931
|
+
const row = result.rows[0];
|
|
1932
|
+
if (!row)
|
|
1933
|
+
return null;
|
|
1934
|
+
return { id: row.id, signalKey: row.signal_key, topic: row.topic };
|
|
1935
|
+
}
|
|
1936
|
+
async resolveEscalationByMetadata(params, wakeCommand) {
|
|
1847
1937
|
const { key, value, namespace, resolverPayload, roles, metadata } = params;
|
|
1848
1938
|
const filter = JSON.stringify({ [key]: value });
|
|
1849
1939
|
const payloadJson = resolverPayload ? JSON.stringify(resolverPayload) : null;
|
|
@@ -1878,8 +1968,9 @@ class PostgresStoreService extends __1.StoreService {
|
|
|
1878
1968
|
await this.pgClient.query('ROLLBACK');
|
|
1879
1969
|
return { ok: false, reason: 'already-resolved' };
|
|
1880
1970
|
}
|
|
1971
|
+
const wakeEnqueued = await this.enqueueEscalationWake(wakeCommand, signal_key, id);
|
|
1881
1972
|
await this.pgClient.query('COMMIT');
|
|
1882
|
-
return { ok: true, entry: updateResult.rows[0], signalKey: signal_key, topic };
|
|
1973
|
+
return { ok: true, entry: updateResult.rows[0], signalKey: signal_key, topic, wakeEnqueued };
|
|
1883
1974
|
}
|
|
1884
1975
|
catch (e) {
|
|
1885
1976
|
await this.pgClient.query('ROLLBACK');
|
|
@@ -66,10 +66,13 @@ export declare abstract class StreamService<ClientProvider extends ProviderClien
|
|
|
66
66
|
supportsRetry: boolean;
|
|
67
67
|
supportsNotifications?: boolean;
|
|
68
68
|
supportsParallelProcessing?: boolean;
|
|
69
|
+
supportsReservationExtension?: boolean;
|
|
69
70
|
maxMessageSize: number;
|
|
70
71
|
maxBatchSize: number;
|
|
71
72
|
};
|
|
72
73
|
deadLetterMessages?(streamName: string, groupName: string, messageIds: string[]): Promise<number>;
|
|
74
|
+
expireJobMessages?(jid: string): Promise<number>;
|
|
75
|
+
extendReservation?(streamName: string, messageId: string, consumerName: string): Promise<number>;
|
|
73
76
|
stopNotificationConsumer?(streamName: string, groupName: string): Promise<void>;
|
|
74
77
|
cleanup?(): Promise<void>;
|
|
75
78
|
}
|
|
@@ -19,6 +19,31 @@ export declare function buildPublishSQL(tableName: string, streamName: string, i
|
|
|
19
19
|
sql: string;
|
|
20
20
|
params: any[];
|
|
21
21
|
};
|
|
22
|
+
/**
|
|
23
|
+
* Job-liveness context for the delivery guard. `keyPrefix` is the minted
|
|
24
|
+
* job-key prefix (`hmsh:<app>:j:`) so `keyPrefix || jid` addresses the
|
|
25
|
+
* jobs row. `enabled` is mutated to false (self-disable) when the jobs
|
|
26
|
+
* table is not visible from the stream connection.
|
|
27
|
+
*/
|
|
28
|
+
export interface JobLivenessContext {
|
|
29
|
+
jobsTable: string;
|
|
30
|
+
keyPrefix: string;
|
|
31
|
+
enabled: boolean;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Soft-delete every live stream row that belongs to a job. Called when a
|
|
35
|
+
* job is interrupted so its queued, reserved, and scheduled-retry
|
|
36
|
+
* messages are never delivered again. Uses the partial jid indexes
|
|
37
|
+
* (idx_*_streams_jid_created); runs once per interrupt.
|
|
38
|
+
*/
|
|
39
|
+
export declare function expireJobMessages(client: PostgresClientType & ProviderClient, tableNames: string[], jid: string, logger: ILogger): Promise<number>;
|
|
40
|
+
/**
|
|
41
|
+
* Refresh an owned reservation (heartbeat). Scoped to the owning
|
|
42
|
+
* consumer and to live rows: a message that was reclaimed by another
|
|
43
|
+
* consumer, acked, or expired (job interrupted) reports 0 so the
|
|
44
|
+
* stale consumer can abandon its execution.
|
|
45
|
+
*/
|
|
46
|
+
export declare function extendReservation(client: PostgresClientType & ProviderClient, tableName: string, streamName: string, messageId: string, consumerName: string, logger: ILogger): Promise<number>;
|
|
22
47
|
/**
|
|
23
48
|
* Fetch messages from the stream with optional exponential backoff.
|
|
24
49
|
* Uses SKIP LOCKED for high-concurrency consumption.
|
|
@@ -33,7 +58,7 @@ export declare function fetchMessages(client: PostgresClientType & ProviderClien
|
|
|
33
58
|
initialBackoff?: number;
|
|
34
59
|
maxBackoff?: number;
|
|
35
60
|
maxRetries?: number;
|
|
36
|
-
}, logger: ILogger): Promise<StreamMessage[]>;
|
|
61
|
+
}, logger: ILogger, liveness?: JobLivenessContext): Promise<StreamMessage[]>;
|
|
37
62
|
/**
|
|
38
63
|
* Acknowledge messages (no-op for PostgreSQL - uses soft delete pattern).
|
|
39
64
|
*/
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.retryMessages = exports.deadLetterMessages = exports.ackAndDelete = exports.deleteMessages = exports.acknowledgeMessages = exports.fetchMessages = exports.buildPublishSQL = exports.publishMessages = exports.getMessagePriority = void 0;
|
|
3
|
+
exports.retryMessages = exports.deadLetterMessages = exports.ackAndDelete = exports.deleteMessages = exports.acknowledgeMessages = exports.fetchMessages = exports.extendReservation = exports.expireJobMessages = exports.buildPublishSQL = exports.publishMessages = exports.getMessagePriority = void 0;
|
|
4
4
|
const enums_1 = require("../../../../modules/enums");
|
|
5
5
|
const utils_1 = require("../../../../modules/utils");
|
|
6
6
|
const stream_1 = require("../../../../types/stream");
|
|
@@ -203,12 +203,121 @@ function buildPublishSQL(tableName, streamName, isEngine, messages, options) {
|
|
|
203
203
|
};
|
|
204
204
|
}
|
|
205
205
|
exports.buildPublishSQL = buildPublishSQL;
|
|
206
|
+
/**
|
|
207
|
+
* Soft-delete every live stream row that belongs to a job. Called when a
|
|
208
|
+
* job is interrupted so its queued, reserved, and scheduled-retry
|
|
209
|
+
* messages are never delivered again. Uses the partial jid indexes
|
|
210
|
+
* (idx_*_streams_jid_created); runs once per interrupt.
|
|
211
|
+
*/
|
|
212
|
+
async function expireJobMessages(client, tableNames, jid, logger) {
|
|
213
|
+
if (!jid)
|
|
214
|
+
return 0;
|
|
215
|
+
let total = 0;
|
|
216
|
+
for (const tableName of tableNames) {
|
|
217
|
+
try {
|
|
218
|
+
const res = await client.query(`UPDATE ${tableName}
|
|
219
|
+
SET expired_at = NOW()
|
|
220
|
+
WHERE jid = $1 AND expired_at IS NULL`, [jid]);
|
|
221
|
+
total += res.rowCount ?? 0;
|
|
222
|
+
}
|
|
223
|
+
catch (error) {
|
|
224
|
+
logger.error(`postgres-stream-expire-job-error`, {
|
|
225
|
+
tableName,
|
|
226
|
+
jid,
|
|
227
|
+
error,
|
|
228
|
+
});
|
|
229
|
+
throw error;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return total;
|
|
233
|
+
}
|
|
234
|
+
exports.expireJobMessages = expireJobMessages;
|
|
235
|
+
/**
|
|
236
|
+
* Refresh an owned reservation (heartbeat). Scoped to the owning
|
|
237
|
+
* consumer and to live rows: a message that was reclaimed by another
|
|
238
|
+
* consumer, acked, or expired (job interrupted) reports 0 so the
|
|
239
|
+
* stale consumer can abandon its execution.
|
|
240
|
+
*/
|
|
241
|
+
async function extendReservation(client, tableName, streamName, messageId, consumerName, logger) {
|
|
242
|
+
try {
|
|
243
|
+
const res = await client.query(`UPDATE ${tableName}
|
|
244
|
+
SET reserved_at = NOW()
|
|
245
|
+
WHERE stream_name = $1 AND id = $2
|
|
246
|
+
AND reserved_by = $3 AND expired_at IS NULL`, [streamName, parseInt(messageId), consumerName]);
|
|
247
|
+
return res.rowCount ?? 0;
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
logger.error(`postgres-stream-extend-error-${streamName}`, {
|
|
251
|
+
messageId,
|
|
252
|
+
error,
|
|
253
|
+
});
|
|
254
|
+
throw error;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
exports.extendReservation = extendReservation;
|
|
258
|
+
/**
|
|
259
|
+
* Delivery liveness guard. Scoped to messages that are REDELIVERIES
|
|
260
|
+
* (a prior reservation lapsed) or RETRIES (retry_attempt > 0) — zombie
|
|
261
|
+
* messages of interrupted jobs only resurface through those paths, so
|
|
262
|
+
* first deliveries (the steady-state hot path) pay zero extra cost.
|
|
263
|
+
* A suspect whose job exists, is live, and has status <= 0 is expired
|
|
264
|
+
* in place and dropped from the batch. A missing job row still delivers
|
|
265
|
+
* (job-creating messages precede the row). Fails open on any error;
|
|
266
|
+
* self-disables when the jobs table is not visible (42P01).
|
|
267
|
+
*/
|
|
268
|
+
async function dropDeadJobMessages(client, tableName, streamName, rows, liveness, logger) {
|
|
269
|
+
const deadIds = new Set();
|
|
270
|
+
const suspects = rows.filter((row) => row.jid && (row.redelivered || row.retry_attempt > 0));
|
|
271
|
+
if (suspects.length === 0) {
|
|
272
|
+
return deadIds;
|
|
273
|
+
}
|
|
274
|
+
try {
|
|
275
|
+
const res = await client.query(`UPDATE ${tableName} t
|
|
276
|
+
SET expired_at = NOW()
|
|
277
|
+
FROM ${liveness.jobsTable} j
|
|
278
|
+
WHERE t.stream_name = $1
|
|
279
|
+
AND t.id = ANY($2::bigint[])
|
|
280
|
+
AND j.key = $3 || t.jid
|
|
281
|
+
AND j.is_live
|
|
282
|
+
AND j.status <= 0
|
|
283
|
+
RETURNING t.id`, [streamName, suspects.map((row) => row.id), liveness.keyPrefix]);
|
|
284
|
+
for (const row of res.rows) {
|
|
285
|
+
deadIds.add(row.id.toString());
|
|
286
|
+
}
|
|
287
|
+
if (deadIds.size > 0) {
|
|
288
|
+
logger.warn(`postgres-stream-zombie-dropped-${streamName}`, {
|
|
289
|
+
count: deadIds.size,
|
|
290
|
+
jids: [
|
|
291
|
+
...new Set(suspects
|
|
292
|
+
.filter((row) => deadIds.has(row.id.toString()))
|
|
293
|
+
.map((row) => row.jid)),
|
|
294
|
+
],
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
catch (error) {
|
|
299
|
+
if (error?.code === '42P01') {
|
|
300
|
+
//jobs table is not visible from this connection; the guard cannot
|
|
301
|
+
//run here — interrupt-time purging (expireJobMessages) still applies
|
|
302
|
+
liveness.enabled = false;
|
|
303
|
+
logger.info('postgres-stream-liveness-guard-disabled', {
|
|
304
|
+
jobsTable: liveness.jobsTable,
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
else {
|
|
308
|
+
logger.error(`postgres-stream-liveness-guard-error-${streamName}`, {
|
|
309
|
+
error,
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return deadIds;
|
|
314
|
+
}
|
|
206
315
|
/**
|
|
207
316
|
* Fetch messages from the stream with optional exponential backoff.
|
|
208
317
|
* Uses SKIP LOCKED for high-concurrency consumption.
|
|
209
318
|
* No group_name filter needed - the table itself determines engine vs worker.
|
|
210
319
|
*/
|
|
211
|
-
async function fetchMessages(client, tableName, streamName, isEngine, consumerName, options = {}, logger) {
|
|
320
|
+
async function fetchMessages(client, tableName, streamName, isEngine, consumerName, options = {}, logger, liveness) {
|
|
212
321
|
const enableBackoff = options?.enableBackoff ?? false;
|
|
213
322
|
const initialBackoff = options?.initialBackoff ?? 100;
|
|
214
323
|
const maxBackoff = options?.maxBackoff ?? 3000;
|
|
@@ -217,10 +326,11 @@ async function fetchMessages(client, tableName, streamName, isEngine, consumerNa
|
|
|
217
326
|
let retries = 0;
|
|
218
327
|
// Include workflow_name in RETURNING for worker streams. Columns are
|
|
219
328
|
// qualified with the update target's alias because the claim UPDATE
|
|
220
|
-
// joins a CTE that also exposes an id column.
|
|
329
|
+
// joins a CTE that also exposes an id column. Worker streams also
|
|
330
|
+
// return jid and the pre-claim redelivery flag for the liveness guard.
|
|
221
331
|
const returningClause = isEngine
|
|
222
332
|
? 't.id, t.message, t.max_retry_attempts, t.backoff_coefficient, t.maximum_interval_seconds, t.retry_attempt'
|
|
223
|
-
: 't.id, t.message, t.workflow_name, t.max_retry_attempts, t.backoff_coefficient, t.maximum_interval_seconds, t.retry_attempt';
|
|
333
|
+
: 't.id, t.message, t.workflow_name, t.max_retry_attempts, t.backoff_coefficient, t.maximum_interval_seconds, t.retry_attempt, t.jid, candidates.redelivered';
|
|
224
334
|
try {
|
|
225
335
|
while (retries < maxRetries) {
|
|
226
336
|
retries++;
|
|
@@ -232,8 +342,11 @@ async function fetchMessages(client, tableName, streamName, isEngine, consumerNa
|
|
|
232
342
|
// reserves MORE rows than LIMIT. The UPDATE repeats stream_name so
|
|
233
343
|
// the planner prunes to a single hash partition and joins on the
|
|
234
344
|
// (stream_name, id) primary key.
|
|
345
|
+
// candidates exposes the PRE-claim reservation state: a non-null
|
|
346
|
+
// reserved_at at claim time means a prior reservation lapsed
|
|
347
|
+
// (redelivery) — the trigger condition for the liveness guard.
|
|
235
348
|
const res = await client.query(`WITH candidates AS MATERIALIZED (
|
|
236
|
-
SELECT id FROM ${tableName}
|
|
349
|
+
SELECT id, (reserved_at IS NOT NULL) AS redelivered FROM ${tableName}
|
|
237
350
|
WHERE stream_name = $1
|
|
238
351
|
AND (reserved_at IS NULL OR reserved_at < NOW() - INTERVAL '${reservationTimeout} seconds')
|
|
239
352
|
AND expired_at IS NULL
|
|
@@ -247,7 +360,14 @@ async function fetchMessages(client, tableName, streamName, isEngine, consumerNa
|
|
|
247
360
|
FROM candidates
|
|
248
361
|
WHERE t.stream_name = $1 AND t.id = candidates.id
|
|
249
362
|
RETURNING ${returningClause}`, [streamName, batchSize, consumerName]);
|
|
250
|
-
|
|
363
|
+
let rows = res.rows;
|
|
364
|
+
if (!isEngine && liveness?.enabled && rows.length > 0) {
|
|
365
|
+
const deadIds = await dropDeadJobMessages(client, tableName, streamName, rows, liveness, logger);
|
|
366
|
+
if (deadIds.size > 0) {
|
|
367
|
+
rows = rows.filter((row) => !deadIds.has(row.id.toString()));
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
const messages = rows.map((row) => {
|
|
251
371
|
const data = (0, utils_1.parseStreamMessage)(row.message);
|
|
252
372
|
const hasDefaultRetryPolicy = (row.max_retry_attempts === 3 || row.max_retry_attempts === 5) &&
|
|
253
373
|
parseFloat(row.backoff_coefficient) === 10 &&
|
|
@@ -31,6 +31,7 @@ declare class PostgresStreamService extends StreamService<PostgresClientType & P
|
|
|
31
31
|
*/
|
|
32
32
|
securedMode: boolean;
|
|
33
33
|
private scoutManager;
|
|
34
|
+
private liveness;
|
|
34
35
|
private notificationManager;
|
|
35
36
|
constructor(streamClient: PostgresClientType & ProviderClient, storeClient: ProviderClient, config?: StreamConfig);
|
|
36
37
|
init(namespace: string, appId: string, logger: ILogger): Promise<void>;
|
|
@@ -91,6 +92,20 @@ declare class PostgresStreamService extends StreamService<PostgresClientType & P
|
|
|
91
92
|
private setupNotificationConsumer;
|
|
92
93
|
stopNotificationConsumer(streamName: string, groupName: string): Promise<void>;
|
|
93
94
|
private fetchMessages;
|
|
95
|
+
/**
|
|
96
|
+
* Refreshes an owned reservation (heartbeat). Called by the consumer
|
|
97
|
+
* while an activity callback is still running so the message stays
|
|
98
|
+
* leased past the base reservation window. Returns 0 when the lease
|
|
99
|
+
* is no longer this consumer's to hold (reclaimed, acked, or expired).
|
|
100
|
+
*/
|
|
101
|
+
extendReservation(streamName: string, messageId: string, consumerName: string): Promise<number>;
|
|
102
|
+
/**
|
|
103
|
+
* Soft-deletes every live stream row that belongs to a job, across the
|
|
104
|
+
* worker and engine stream tables. Called by the engine when a job is
|
|
105
|
+
* interrupted or scrubbed so its queued, reserved, and scheduled-retry
|
|
106
|
+
* messages are never delivered again.
|
|
107
|
+
*/
|
|
108
|
+
expireJobMessages(jid: string): Promise<number>;
|
|
94
109
|
ackAndDelete(streamName: string, groupName: string, messageIds: string[]): Promise<number>;
|
|
95
110
|
deadLetterMessages(streamName: string, groupName: string, messageIds: string[]): Promise<number>;
|
|
96
111
|
acknowledgeMessages(streamName: string, groupName: string, messageIds: string[], options?: StringAnyType): Promise<number>;
|
|
@@ -118,6 +133,7 @@ declare class PostgresStreamService extends StreamService<PostgresClientType & P
|
|
|
118
133
|
exactLimit?: boolean;
|
|
119
134
|
}): Promise<number>;
|
|
120
135
|
getProviderSpecificFeatures(): {
|
|
136
|
+
supportsReservationExtension: boolean;
|
|
121
137
|
supportsBatching: boolean;
|
|
122
138
|
supportsDeadLetterQueue: boolean;
|
|
123
139
|
supportsOrdering: boolean;
|
|
@@ -62,6 +62,14 @@ class PostgresStreamService extends index_1.StreamService {
|
|
|
62
62
|
// and never need direct table access.
|
|
63
63
|
if (!this.securedMode) {
|
|
64
64
|
await (0, kvtables_1.deploySchema)(this.streamClient, this.appId, this.logger);
|
|
65
|
+
//delivery liveness guard: drops redelivered/retried worker messages
|
|
66
|
+
//whose job is dead. Secured workers cannot read the jobs table —
|
|
67
|
+
//interrupt-time purging (expireJobMessages) covers them instead.
|
|
68
|
+
this.liveness = {
|
|
69
|
+
jobsTable: `${this.safeName(this.appId)}.jobs`,
|
|
70
|
+
keyPrefix: this.mintKey(key_1.KeyType.JOB_STATE, { jobId: '' }),
|
|
71
|
+
enabled: true,
|
|
72
|
+
};
|
|
65
73
|
}
|
|
66
74
|
// Initialize scout manager (skipped in secured mode — roles table inaccessible)
|
|
67
75
|
this.scoutManager = this.securedMode ? null : new scout_1.ScoutManager(this.streamClient, this.appId, this.getEngineTableName.bind(this), this.mintKey.bind(this), this.logger);
|
|
@@ -285,7 +293,32 @@ class PostgresStreamService extends index_1.StreamService {
|
|
|
285
293
|
return Secured.fetchMessagesSecured(this.streamClient, this.safeName(this.appId), target.streamName, consumerName, options || {}, this.logger);
|
|
286
294
|
}
|
|
287
295
|
const target = this.resolveStreamTarget(streamName);
|
|
288
|
-
return Messages.fetchMessages(this.streamClient, target.tableName, target.streamName, target.isEngine, consumerName, options || {}, this.logger);
|
|
296
|
+
return Messages.fetchMessages(this.streamClient, target.tableName, target.streamName, target.isEngine, consumerName, options || {}, this.logger, this.liveness);
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Refreshes an owned reservation (heartbeat). Called by the consumer
|
|
300
|
+
* while an activity callback is still running so the message stays
|
|
301
|
+
* leased past the base reservation window. Returns 0 when the lease
|
|
302
|
+
* is no longer this consumer's to hold (reclaimed, acked, or expired).
|
|
303
|
+
*/
|
|
304
|
+
async extendReservation(streamName, messageId, consumerName) {
|
|
305
|
+
if (this.securedMode) {
|
|
306
|
+
return 0;
|
|
307
|
+
}
|
|
308
|
+
const target = this.resolveStreamTarget(streamName);
|
|
309
|
+
return Messages.extendReservation(this.streamClient, target.tableName, target.streamName, messageId, consumerName, this.logger);
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Soft-deletes every live stream row that belongs to a job, across the
|
|
313
|
+
* worker and engine stream tables. Called by the engine when a job is
|
|
314
|
+
* interrupted or scrubbed so its queued, reserved, and scheduled-retry
|
|
315
|
+
* messages are never delivered again.
|
|
316
|
+
*/
|
|
317
|
+
async expireJobMessages(jid) {
|
|
318
|
+
if (this.securedMode) {
|
|
319
|
+
return 0;
|
|
320
|
+
}
|
|
321
|
+
return Messages.expireJobMessages(this.streamClient, [this.getEngineTableName(), this.getWorkerTableName()], jid, this.logger);
|
|
289
322
|
}
|
|
290
323
|
async ackAndDelete(streamName, groupName, messageIds) {
|
|
291
324
|
if (this.securedMode) {
|
|
@@ -355,7 +388,12 @@ class PostgresStreamService extends index_1.StreamService {
|
|
|
355
388
|
return Stats.trimStream(this.streamClient, target.tableName, target.streamName, options, this.logger);
|
|
356
389
|
}
|
|
357
390
|
getProviderSpecificFeatures() {
|
|
358
|
-
return
|
|
391
|
+
return {
|
|
392
|
+
...Stats.getProviderSpecificFeatures(this.config),
|
|
393
|
+
//heartbeat lease extension uses direct table access; secured
|
|
394
|
+
//workers use stored procedures and keep hard-deadline leases
|
|
395
|
+
supportsReservationExtension: !this.securedMode,
|
|
396
|
+
};
|
|
359
397
|
}
|
|
360
398
|
async cleanup() {
|
|
361
399
|
if (this.scoutManager) {
|
|
@@ -73,8 +73,13 @@ class TaskService {
|
|
|
73
73
|
expire,
|
|
74
74
|
};
|
|
75
75
|
//called standalone (no transaction) so the single CTE query can
|
|
76
|
-
//atomically detect and return pending signal data on collision
|
|
77
|
-
|
|
76
|
+
//atomically detect and return pending signal data on collision.
|
|
77
|
+
//the redelivery routing lets the store republish a consumed
|
|
78
|
+
//pending signal durably, in the same transaction that consumes it
|
|
79
|
+
const result = await this.store.setHookSignal(hook, undefined, {
|
|
80
|
+
aid: hookRule.to,
|
|
81
|
+
topic,
|
|
82
|
+
});
|
|
78
83
|
if (result.pendingData) {
|
|
79
84
|
this.logger.warn('task-signal-race-pending-consumed', {
|
|
80
85
|
topic,
|
|
@@ -105,6 +105,19 @@ export type ResolveEscalationResult = {
|
|
|
105
105
|
ok: false;
|
|
106
106
|
reason: 'not-found' | 'already-resolved' | 'already-cancelled' | 'already-expired';
|
|
107
107
|
};
|
|
108
|
+
/**
|
|
109
|
+
* A pre-built wake publish, executed INSIDE the resolve transaction so the
|
|
110
|
+
* awaiting workflow's wake commits atomically with `status='resolved'`. The
|
|
111
|
+
* SQL is a stream INSERT produced by the stream provider; `forSignalKey`
|
|
112
|
+
* pins the command to the row it was built for — the store executes it only
|
|
113
|
+
* when the locked row's `signal_key` matches (a mismatched row falls back
|
|
114
|
+
* to post-commit delivery).
|
|
115
|
+
*/
|
|
116
|
+
export interface EscalationWakeCommand {
|
|
117
|
+
forSignalKey: string;
|
|
118
|
+
sql: string;
|
|
119
|
+
params: unknown[];
|
|
120
|
+
}
|
|
108
121
|
export type ReleaseEscalationResult = {
|
|
109
122
|
ok: true;
|
|
110
123
|
entry: EscalationEntry;
|