@hotmeshio/hotmesh 0.29.1 → 0.31.0
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 +43 -0
- package/build/index.d.ts +2 -1
- package/build/index.js +3 -1
- package/build/modules/enums.d.ts +35 -0
- package/build/modules/enums.js +41 -1
- package/build/modules/errors.d.ts +26 -2
- package/build/modules/errors.js +82 -1
- package/build/modules/utils.d.ts +8 -0
- package/build/modules/utils.js +19 -1
- package/build/package.json +1 -1
- package/build/services/activities/trigger.js +3 -1
- package/build/services/connector/health.d.ts +42 -0
- package/build/services/connector/health.js +100 -0
- package/build/services/connector/index.js +2 -1
- package/build/services/connector/providers/postgres-resilient-client.d.ts +95 -0
- package/build/services/connector/providers/postgres-resilient-client.js +446 -0
- package/build/services/connector/providers/postgres.d.ts +6 -0
- package/build/services/connector/providers/postgres.js +72 -14
- package/build/services/durable/client.js +11 -3
- package/build/services/durable/handle.js +101 -41
- package/build/services/durable/worker.js +12 -4
- package/build/services/durable/workflow/condition.d.ts +14 -0
- package/build/services/durable/workflow/condition.js +14 -0
- package/build/services/engine/completion.js +3 -3
- package/build/services/engine/signal.js +3 -3
- package/build/services/escalations/batch.d.ts +7 -3
- package/build/services/escalations/batch.js +64 -6
- package/build/services/escalations/client.d.ts +4 -2
- package/build/services/escalations/client.js +4 -2
- package/build/services/escalations/fold.d.ts +3 -2
- package/build/services/escalations/fold.js +13 -2
- package/build/services/escalations/index.d.ts +1 -1
- package/build/services/escalations/index.js +2 -1
- package/build/services/hotmesh/index.js +17 -4
- package/build/services/quorum/index.js +13 -13
- package/build/services/router/consumption/index.d.ts +20 -0
- package/build/services/router/consumption/index.js +177 -7
- package/build/services/store/providers/postgres/kvtransaction.js +8 -1
- package/build/services/store/providers/postgres/postgres.d.ts +2 -1
- package/build/services/store/providers/postgres/postgres.js +18 -9
- package/build/services/stream/index.d.ts +16 -0
- package/build/services/stream/index.js +23 -0
- package/build/services/stream/providers/postgres/messages.d.ts +7 -0
- package/build/services/stream/providers/postgres/messages.js +27 -1
- package/build/services/stream/providers/postgres/notifications.d.ts +13 -0
- package/build/services/stream/providers/postgres/notifications.js +89 -2
- package/build/services/stream/providers/postgres/postgres.d.ts +7 -0
- package/build/services/stream/providers/postgres/postgres.js +24 -3
- package/build/services/stream/providers/postgres/scout.d.ts +10 -0
- package/build/services/stream/providers/postgres/scout.js +38 -4
- package/build/services/stream/registry.d.ts +6 -0
- package/build/services/stream/registry.js +11 -2
- package/build/services/sub/providers/postgres/postgres.d.ts +6 -0
- package/build/services/sub/providers/postgres/postgres.js +62 -2
- package/build/services/task/index.js +1 -1
- package/build/services/worker/credentials.js +5 -0
- package/build/services/worker/index.js +5 -5
- package/build/types/hmsh_escalations.d.ts +32 -0
- package/build/types/hmsh_escalations.js +5 -1
- package/build/types/index.d.ts +3 -3
- package/build/types/index.js +2 -1
- package/build/types/postgres.d.ts +20 -0
- package/build/types/provider.d.ts +28 -0
- package/index.ts +2 -0
- package/package.json +1 -1
|
@@ -37,8 +37,8 @@ class QuorumService {
|
|
|
37
37
|
await instance.subscribe.subscribe(hotmesh_1.KeyType.QUORUM, instance.subscriptionHandler(), appId);
|
|
38
38
|
//app-specific quorum subscription (used for pubsub one-time request/response)
|
|
39
39
|
await instance.subscribe.subscribe(hotmesh_1.KeyType.QUORUM, instance.subscriptionHandler(), appId, instance.guid);
|
|
40
|
-
instance.engine.processWebHooks();
|
|
41
|
-
instance.engine.processTimeHooks();
|
|
40
|
+
(0, utils_1.detach)(instance.engine.processWebHooks(), logger, 'quorum-process-webhooks-error');
|
|
41
|
+
(0, utils_1.detach)(instance.engine.processTimeHooks(), logger, 'quorum-process-timehooks-error');
|
|
42
42
|
return instance;
|
|
43
43
|
}
|
|
44
44
|
}
|
|
@@ -74,7 +74,7 @@ class QuorumService {
|
|
|
74
74
|
self.engine.setCacheMode(message.cache_mode, message.until_version);
|
|
75
75
|
}
|
|
76
76
|
else if (message.type === 'ping') {
|
|
77
|
-
self.sayPong(self.appId, self.guid, message.originator, message.details);
|
|
77
|
+
(0, utils_1.detach)(self.sayPong(self.appId, self.guid, message.originator, message.details), self.logger, 'quorum-pong-error');
|
|
78
78
|
}
|
|
79
79
|
else if (message.type === 'pong' && self.guid === message.originator) {
|
|
80
80
|
self.quorum = self.quorum + 1;
|
|
@@ -83,10 +83,10 @@ class QuorumService {
|
|
|
83
83
|
}
|
|
84
84
|
}
|
|
85
85
|
else if (message.type === 'throttle') {
|
|
86
|
-
self.engine.throttle(message.throttle);
|
|
86
|
+
(0, utils_1.detach)(self.engine.throttle(message.throttle), self.logger, 'quorum-throttle-error');
|
|
87
87
|
}
|
|
88
88
|
else if (message.type === 'work') {
|
|
89
|
-
self.engine.processWebHooks();
|
|
89
|
+
(0, utils_1.detach)(self.engine.processWebHooks(), self.logger, 'quorum-process-webhooks-error');
|
|
90
90
|
}
|
|
91
91
|
else if (message.type === 'job') {
|
|
92
92
|
let jobOutput = message.job;
|
|
@@ -106,10 +106,10 @@ class QuorumService {
|
|
|
106
106
|
return; // Can't route without job data
|
|
107
107
|
}
|
|
108
108
|
}
|
|
109
|
-
self.engine.routeToSubscribers(message.topic, jobOutput);
|
|
109
|
+
(0, utils_1.detach)(self.engine.routeToSubscribers(message.topic, jobOutput), self.logger, 'quorum-route-subscribers-error');
|
|
110
110
|
}
|
|
111
111
|
else if (message.type === 'cron') {
|
|
112
|
-
self.engine.processTimeHooks();
|
|
112
|
+
(0, utils_1.detach)(self.engine.processTimeHooks(), self.logger, 'quorum-process-timehooks-error');
|
|
113
113
|
}
|
|
114
114
|
else if (message.type === 'duress') {
|
|
115
115
|
// Apply remote duress signal (skip our own broadcasts)
|
|
@@ -118,7 +118,7 @@ class QuorumService {
|
|
|
118
118
|
}
|
|
119
119
|
}
|
|
120
120
|
else if (message.type === 'rollcall') {
|
|
121
|
-
self.doRollCall(message);
|
|
121
|
+
(0, utils_1.detach)(self.doRollCall(message), self.logger, 'quorum-rollcall-error');
|
|
122
122
|
}
|
|
123
123
|
//if there are any callbacks, call them
|
|
124
124
|
if (self.callbacks.length > 0) {
|
|
@@ -161,12 +161,12 @@ class QuorumService {
|
|
|
161
161
|
profile.duress_per_type = duressSnapshot.per_type;
|
|
162
162
|
}
|
|
163
163
|
}
|
|
164
|
-
this.subscribe.publish(hotmesh_1.KeyType.QUORUM, {
|
|
164
|
+
(0, utils_1.detach)(this.subscribe.publish(hotmesh_1.KeyType.QUORUM, {
|
|
165
165
|
type: 'pong',
|
|
166
166
|
guid,
|
|
167
167
|
originator,
|
|
168
168
|
profile,
|
|
169
|
-
}, appId);
|
|
169
|
+
}, appId), this.logger, 'quorum-pong-publish-error');
|
|
170
170
|
}
|
|
171
171
|
/**
|
|
172
172
|
* A quorum-wide command to request a quorum count.
|
|
@@ -243,7 +243,7 @@ class QuorumService {
|
|
|
243
243
|
async rollCall(delay = enums_1.HMSH_QUORUM_DELAY_MS) {
|
|
244
244
|
await this.requestQuorum(delay, true);
|
|
245
245
|
const stream_depths = await this.engine.stream.getStreamDepths(this.profiles);
|
|
246
|
-
this.profiles.forEach(
|
|
246
|
+
this.profiles.forEach((profile, index) => {
|
|
247
247
|
//if nothing in the table, the depth will be 0
|
|
248
248
|
//todo: separate table for every worker stream?
|
|
249
249
|
profile.stream_depth = stream_depths?.[index]?.depth ?? 0;
|
|
@@ -270,7 +270,7 @@ class QuorumService {
|
|
|
270
270
|
const q3 = await this.requestQuorum(delay);
|
|
271
271
|
if (q1 && q1 === q2 && q2 === q3) {
|
|
272
272
|
this.logger.info('quorum-rollcall-succeeded', { q1, q2, q3 });
|
|
273
|
-
this.subscribe.publish(hotmesh_1.KeyType.QUORUM, { type: 'activate', cache_mode: 'nocache', until_version: version }, this.appId);
|
|
273
|
+
(0, utils_1.detach)(this.subscribe.publish(hotmesh_1.KeyType.QUORUM, { type: 'activate', cache_mode: 'nocache', until_version: version }, this.appId), this.logger, 'quorum-activate-publish-error');
|
|
274
274
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
275
275
|
await this.store.releaseScoutRole('activate');
|
|
276
276
|
//confirm we received the activation message
|
|
@@ -287,7 +287,7 @@ class QuorumService {
|
|
|
287
287
|
}
|
|
288
288
|
else {
|
|
289
289
|
this.logger.warn('quorum-rollcall-error', { q1, q2, q3, count });
|
|
290
|
-
this.store.releaseScoutRole('activate');
|
|
290
|
+
(0, utils_1.detach)(this.store.releaseScoutRole('activate'), this.logger, 'quorum-release-scout-error');
|
|
291
291
|
if (count < enums_1.HMSH_ACTIVATION_MAX_RETRY) {
|
|
292
292
|
//increase the delay (give the quorum time to respond) and try again
|
|
293
293
|
return await this.activate(version, delay * 2, count + 1);
|
|
@@ -31,6 +31,9 @@ export declare class ConsumptionManager<S extends StreamService<ProviderClient,
|
|
|
31
31
|
private onDuressChange?;
|
|
32
32
|
private messagesSinceLastEval;
|
|
33
33
|
private canExtendReservations;
|
|
34
|
+
private redeliveryWakes;
|
|
35
|
+
private deferredReservations;
|
|
36
|
+
private releaseArmed;
|
|
34
37
|
private adaptiveReservationTimeout;
|
|
35
38
|
private adaptiveBatchSize;
|
|
36
39
|
private lastDepthCheckAt;
|
|
@@ -53,6 +56,23 @@ export declare class ConsumptionManager<S extends StreamService<ProviderClient,
|
|
|
53
56
|
consumeMessages(stream: string, group: string, consumer: string, callback: (streamData: StreamData) => Promise<StreamDataResponse | void>): Promise<void>;
|
|
54
57
|
private consumeWithNotifications;
|
|
55
58
|
private consumeWithPolling;
|
|
59
|
+
/**
|
|
60
|
+
* Record a message this consumer deferred because the connection was
|
|
61
|
+
* unavailable. The reservation is released as soon as a connection is
|
|
62
|
+
* restored, so the message is redelivered at once; the timed wake below
|
|
63
|
+
* remains the fallback when a release is not possible.
|
|
64
|
+
*/
|
|
65
|
+
private deferForRedelivery;
|
|
66
|
+
private armDeferredRelease;
|
|
67
|
+
private releaseDeferred;
|
|
68
|
+
/**
|
|
69
|
+
* A message left unacked because the connection was unavailable is
|
|
70
|
+
* redelivered once its reservation lapses, but only when a consumer
|
|
71
|
+
* next fetches. Wake the stream's consumers just after the lapse (and
|
|
72
|
+
* twice more, in case the database is still away) instead of waiting
|
|
73
|
+
* for the fallback poller. One schedule per stream at a time.
|
|
74
|
+
*/
|
|
75
|
+
private scheduleRedeliveryWake;
|
|
56
76
|
/**
|
|
57
77
|
* Whether reservation heartbeats are available: the provider must
|
|
58
78
|
* implement extendReservation and advertise the capability.
|
|
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.ConsumptionManager = void 0;
|
|
4
4
|
const utils_1 = require("../../../modules/utils");
|
|
5
5
|
const errors_1 = require("../../../modules/errors");
|
|
6
|
+
const enums_1 = require("../../../modules/enums");
|
|
7
|
+
const health_1 = require("../../connector/health");
|
|
6
8
|
const telemetry_1 = require("../telemetry");
|
|
7
9
|
const config_1 = require("../config");
|
|
8
10
|
const stream_1 = require("../../../types/stream");
|
|
@@ -19,6 +21,11 @@ class ConsumptionManager {
|
|
|
19
21
|
set hasReachedMaxBackoff(v) { this.router.hasReachedMaxBackoff = v; }
|
|
20
22
|
constructor(stream, logger, throttleManager, errorHandler, lifecycleManager, reclaimDelay, reclaimCount, appId, role, router, retry, duressManager) {
|
|
21
23
|
this.messagesSinceLastEval = 0;
|
|
24
|
+
//streams with a pending redelivery wake (one schedule per stream)
|
|
25
|
+
this.redeliveryWakes = new Set();
|
|
26
|
+
//messages deferred during an outage, released when a connection returns
|
|
27
|
+
this.deferredReservations = new Map();
|
|
28
|
+
this.releaseArmed = false;
|
|
22
29
|
// Adaptive consumption pressure — scales reservation timeout AND batch
|
|
23
30
|
// size based on stream depth. Under load: timeout grows (prevents
|
|
24
31
|
// duplicate re-reservation) and batch size shrinks (reduces in-memory
|
|
@@ -419,6 +426,19 @@ class ConsumptionManager {
|
|
|
419
426
|
}
|
|
420
427
|
catch (error) {
|
|
421
428
|
if (this.lifecycleManager.getShouldConsume() &&
|
|
429
|
+
error instanceof errors_1.HotMeshConnectionError) {
|
|
430
|
+
//the connection is reconnecting: resume within one reconnect ceiling
|
|
431
|
+
this.logger.warn(`router-stream-connection-unavailable`, {
|
|
432
|
+
stream,
|
|
433
|
+
group,
|
|
434
|
+
consumer,
|
|
435
|
+
error: error.message,
|
|
436
|
+
});
|
|
437
|
+
this.errorCount++;
|
|
438
|
+
const timeout = Math.min(1000 * 2 ** Math.min(this.errorCount, 10), Math.max(enums_1.HMSH_PG_RECONNECT_MAX_MS, 1000));
|
|
439
|
+
setTimeout(consume.bind(this), timeout);
|
|
440
|
+
}
|
|
441
|
+
else if (this.lifecycleManager.getShouldConsume() &&
|
|
422
442
|
process.env.NODE_ENV !== 'test') {
|
|
423
443
|
this.logger.error(`router-stream-error`, {
|
|
424
444
|
error,
|
|
@@ -434,6 +454,97 @@ class ConsumptionManager {
|
|
|
434
454
|
};
|
|
435
455
|
consume.call(this);
|
|
436
456
|
}
|
|
457
|
+
/**
|
|
458
|
+
* Record a message this consumer deferred because the connection was
|
|
459
|
+
* unavailable. The reservation is released as soon as a connection is
|
|
460
|
+
* restored, so the message is redelivered at once; the timed wake below
|
|
461
|
+
* remains the fallback when a release is not possible.
|
|
462
|
+
*/
|
|
463
|
+
deferForRedelivery(stream, id, consumer) {
|
|
464
|
+
this.scheduleRedeliveryWake(stream);
|
|
465
|
+
if (!consumer || typeof this.stream.releaseReservations !== 'function') {
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
const key = `${stream}|${consumer}`;
|
|
469
|
+
let entry = this.deferredReservations.get(key);
|
|
470
|
+
if (!entry) {
|
|
471
|
+
entry = { stream, consumer, ids: new Set() };
|
|
472
|
+
this.deferredReservations.set(key, entry);
|
|
473
|
+
}
|
|
474
|
+
entry.ids.add(id);
|
|
475
|
+
this.armDeferredRelease();
|
|
476
|
+
}
|
|
477
|
+
armDeferredRelease() {
|
|
478
|
+
if (this.releaseArmed) {
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
this.releaseArmed = true;
|
|
482
|
+
health_1.ConnectionHealth.once('restored', () => {
|
|
483
|
+
this.releaseArmed = false;
|
|
484
|
+
return this.releaseDeferred();
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
async releaseDeferred() {
|
|
488
|
+
const batches = Array.from(this.deferredReservations.values());
|
|
489
|
+
this.deferredReservations.clear();
|
|
490
|
+
for (const batch of batches) {
|
|
491
|
+
const ids = Array.from(batch.ids);
|
|
492
|
+
try {
|
|
493
|
+
const released = await this.stream.releaseReservations(batch.stream, ids, batch.consumer);
|
|
494
|
+
this.logger.info('stream-deferred-released', {
|
|
495
|
+
stream: batch.stream,
|
|
496
|
+
consumer: batch.consumer,
|
|
497
|
+
requested: ids.length,
|
|
498
|
+
released,
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
catch (error) {
|
|
502
|
+
//the stream's own connection is not back yet: keep the batch for
|
|
503
|
+
//the next restore (the timed wake still covers it)
|
|
504
|
+
const key = `${batch.stream}|${batch.consumer}`;
|
|
505
|
+
const pending = this.deferredReservations.get(key);
|
|
506
|
+
if (pending) {
|
|
507
|
+
ids.forEach((id) => pending.ids.add(id));
|
|
508
|
+
}
|
|
509
|
+
else {
|
|
510
|
+
this.deferredReservations.set(key, batch);
|
|
511
|
+
}
|
|
512
|
+
this.armDeferredRelease();
|
|
513
|
+
this.logger.warn('stream-deferred-release-error', {
|
|
514
|
+
stream: batch.stream,
|
|
515
|
+
consumer: batch.consumer,
|
|
516
|
+
error: error?.message,
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* A message left unacked because the connection was unavailable is
|
|
523
|
+
* redelivered once its reservation lapses, but only when a consumer
|
|
524
|
+
* next fetches. Wake the stream's consumers just after the lapse (and
|
|
525
|
+
* twice more, in case the database is still away) instead of waiting
|
|
526
|
+
* for the fallback poller. One schedule per stream at a time.
|
|
527
|
+
*/
|
|
528
|
+
scheduleRedeliveryWake(stream) {
|
|
529
|
+
const streamService = this.stream;
|
|
530
|
+
if (typeof streamService.scheduleStreamNotify !== 'function' ||
|
|
531
|
+
this.redeliveryWakes.has(stream)) {
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
this.redeliveryWakes.add(stream);
|
|
535
|
+
//a message becomes claimable once the longest reservation window lapses
|
|
536
|
+
const windowMs = Math.max(Number(streamService.reservationTimeout) || 0, this.adaptiveReservationTimeout + ConsumptionManager.LEASE_BUFFER_S) * 1000;
|
|
537
|
+
const delays = [
|
|
538
|
+
windowMs + 1000,
|
|
539
|
+
windowMs * 2 + 1000,
|
|
540
|
+
windowMs * 4 + 1000,
|
|
541
|
+
];
|
|
542
|
+
for (const delay of delays) {
|
|
543
|
+
streamService.scheduleStreamNotify(stream, delay);
|
|
544
|
+
}
|
|
545
|
+
const release = setTimeout(() => this.redeliveryWakes.delete(stream), delays[delays.length - 1]);
|
|
546
|
+
release.unref?.();
|
|
547
|
+
}
|
|
437
548
|
/**
|
|
438
549
|
* Whether reservation heartbeats are available: the provider must
|
|
439
550
|
* implement extendReservation and advertise the capability.
|
|
@@ -589,6 +700,26 @@ class ConsumptionManager {
|
|
|
589
700
|
}
|
|
590
701
|
catch (err) {
|
|
591
702
|
const category = (0, errors_1.classifyError)(err);
|
|
703
|
+
if (category === errors_1.ErrorCategory.UNAVAILABLE) {
|
|
704
|
+
// The HotMesh database connection is unavailable. Do NOT ack and
|
|
705
|
+
// do NOT publish an error response: the message stays reserved and
|
|
706
|
+
// is redelivered once the connection returns, without spending
|
|
707
|
+
// the retry budget on an outage.
|
|
708
|
+
this.logger.warn('stream-connection-unavailable', {
|
|
709
|
+
category,
|
|
710
|
+
group,
|
|
711
|
+
stream,
|
|
712
|
+
id,
|
|
713
|
+
topic: input.metadata?.topic,
|
|
714
|
+
activityId: input.metadata?.aid,
|
|
715
|
+
jobId: input.metadata?.jid,
|
|
716
|
+
error: err?.message,
|
|
717
|
+
});
|
|
718
|
+
telemetry.setStreamErrorFromException(err);
|
|
719
|
+
telemetry.endStreamSpan();
|
|
720
|
+
this.deferForRedelivery(stream, id, consumer);
|
|
721
|
+
return; // NO ack — redelivered after the connection returns
|
|
722
|
+
}
|
|
592
723
|
if (err instanceof errors_1.LeaseExpiredError) {
|
|
593
724
|
// FATAL: lease expired — do NOT ack. The message remains in the
|
|
594
725
|
// stream for a reclaimant to pick up cleanly. Any partial writes
|
|
@@ -646,6 +777,7 @@ class ConsumptionManager {
|
|
|
646
777
|
}
|
|
647
778
|
}
|
|
648
779
|
}
|
|
780
|
+
let skipAck = false;
|
|
649
781
|
try {
|
|
650
782
|
// When the ENGINE encounters an infrastructure error (schema not found,
|
|
651
783
|
// subscription missing — code 598), the message is permanently unprocessable.
|
|
@@ -667,16 +799,49 @@ class ConsumptionManager {
|
|
|
667
799
|
}
|
|
668
800
|
}
|
|
669
801
|
catch (publishErr) {
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
802
|
+
if ((0, errors_1.isConnectionError)(publishErr)) {
|
|
803
|
+
// The response was not written because the connection is gone.
|
|
804
|
+
// Acking now would lose it; leave the message for redelivery.
|
|
805
|
+
skipAck = true;
|
|
806
|
+
this.deferForRedelivery(stream, id, consumer);
|
|
807
|
+
this.logger.warn(`stream-publish-response-deferred`, {
|
|
808
|
+
category: errors_1.ErrorCategory.UNAVAILABLE,
|
|
809
|
+
group,
|
|
810
|
+
stream,
|
|
811
|
+
id,
|
|
812
|
+
error: publishErr?.message,
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
else {
|
|
816
|
+
// If publishResponse fails, still ack the message to prevent
|
|
817
|
+
// infinite reprocessing. Log the error for debugging.
|
|
818
|
+
this.logger.error(`stream-publish-response-error`, {
|
|
819
|
+
category: (0, errors_1.classifyError)(publishErr),
|
|
820
|
+
group,
|
|
821
|
+
stream,
|
|
822
|
+
id,
|
|
823
|
+
error: publishErr,
|
|
824
|
+
});
|
|
825
|
+
}
|
|
676
826
|
this.errorCount++;
|
|
677
827
|
}
|
|
678
828
|
finally {
|
|
679
|
-
|
|
829
|
+
if (!skipAck) {
|
|
830
|
+
try {
|
|
831
|
+
await this.ackAndDelete(stream, group, id);
|
|
832
|
+
}
|
|
833
|
+
catch (ackErr) {
|
|
834
|
+
// An unacked message is redelivered; never let the ack reject
|
|
835
|
+
// the consumer loop.
|
|
836
|
+
this.logger.warn(`stream-ack-deferred`, {
|
|
837
|
+
category: (0, errors_1.classifyError)(ackErr),
|
|
838
|
+
group,
|
|
839
|
+
stream,
|
|
840
|
+
id,
|
|
841
|
+
error: ackErr?.message,
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
}
|
|
680
845
|
telemetry.endStreamSpan();
|
|
681
846
|
this.logger.debug(`stream-read-one-end`, { group, stream, id });
|
|
682
847
|
}
|
|
@@ -687,6 +852,11 @@ class ConsumptionManager {
|
|
|
687
852
|
output = await callback(input);
|
|
688
853
|
}
|
|
689
854
|
catch (error) {
|
|
855
|
+
if (error instanceof errors_1.HotMeshConnectionError) {
|
|
856
|
+
//an outage is not the callback's failure; consumeOne leaves the
|
|
857
|
+
//message for redelivery instead of structuring an error response
|
|
858
|
+
throw error;
|
|
859
|
+
}
|
|
690
860
|
this.logger.error(`stream-call-function-error`, {
|
|
691
861
|
category: (0, errors_1.classifyError)(error),
|
|
692
862
|
error,
|
|
@@ -263,7 +263,14 @@ class KVTransaction {
|
|
|
263
263
|
commandTypes: this.commands.map(c => c.returnType),
|
|
264
264
|
commandSqlPreviews: this.commands.map(c => c.sql.substring(0, 80)),
|
|
265
265
|
});
|
|
266
|
-
|
|
266
|
+
//a ROLLBACK on a lost session fails too; the original error is the one
|
|
267
|
+
//the caller needs (the server already rolled the session back)
|
|
268
|
+
try {
|
|
269
|
+
await client.query('ROLLBACK');
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
//nothing to roll back
|
|
273
|
+
}
|
|
267
274
|
throw err;
|
|
268
275
|
}
|
|
269
276
|
}
|
|
@@ -341,7 +341,8 @@ declare class PostgresStoreService extends StoreService<ProviderClient, Provider
|
|
|
341
341
|
/**
|
|
342
342
|
* The shared body of both batch-item store ops: guarded fill of one item
|
|
343
343
|
* into `envelope.batch_items` (with its `batch_filled_at` stamp — the
|
|
344
|
-
* database clock, row truth
|
|
344
|
+
* database clock, row truth — and, when an actor is named, its
|
|
345
|
+
* `batch_filled_by` entry), `batch_pending`/`batch_count` recompute,
|
|
345
346
|
* resolve-on-last-item with the assembled collection as
|
|
346
347
|
* `resolver_payload`, wake enqueue, and outcome classification — one
|
|
347
348
|
* atomic statement. `targetCTE` supplies the row selector; it must expose
|
|
@@ -1002,8 +1002,8 @@ class PostgresStoreService extends __1.StoreService {
|
|
|
1002
1002
|
if (didRemove) {
|
|
1003
1003
|
if (scrub) {
|
|
1004
1004
|
//indexes can be designed to be self-cleaning; `engine.hookAll` exposes this option
|
|
1005
|
-
this.kvsql().del(processedKey);
|
|
1006
|
-
this.kvsql().del(key.split(':').slice(0, 5).join(':'));
|
|
1005
|
+
(0, utils_1.detach)(this.kvsql().del(processedKey), this.logger, 'store-scrub-error');
|
|
1006
|
+
(0, utils_1.detach)(this.kvsql().del(key.split(':').slice(0, 5).join(':')), this.logger, 'store-scrub-error');
|
|
1007
1007
|
}
|
|
1008
1008
|
else {
|
|
1009
1009
|
await this.kvsql().rename(processedKey, key);
|
|
@@ -2159,14 +2159,15 @@ class PostgresStoreService extends __1.StoreService {
|
|
|
2159
2159
|
/**
|
|
2160
2160
|
* The shared body of both batch-item store ops: guarded fill of one item
|
|
2161
2161
|
* into `envelope.batch_items` (with its `batch_filled_at` stamp — the
|
|
2162
|
-
* database clock, row truth
|
|
2162
|
+
* database clock, row truth — and, when an actor is named, its
|
|
2163
|
+
* `batch_filled_by` entry), `batch_pending`/`batch_count` recompute,
|
|
2163
2164
|
* resolve-on-last-item with the assembled collection as
|
|
2164
2165
|
* `resolver_payload`, wake enqueue, and outcome classification — one
|
|
2165
2166
|
* atomic statement. `targetCTE` supplies the row selector; it must expose
|
|
2166
2167
|
* id, signal_key, topic, status, assigned_to, assigned_until, batch_keys,
|
|
2167
2168
|
* batch_pending.
|
|
2168
2169
|
*/
|
|
2169
|
-
_batchItemStatement(targetCTE, itemKeyIdx, payloadIdx, metaIdx, claimIdx, wakeCTE, wakeCount) {
|
|
2170
|
+
_batchItemStatement(targetCTE, itemKeyIdx, payloadIdx, metaIdx, claimIdx, actorIdx, wakeCTE, wakeCount) {
|
|
2170
2171
|
const remaining = `jsonb_array_length((e.metadata->'batch_pending') - $${itemKeyIdx}::text)`;
|
|
2171
2172
|
return `
|
|
2172
2173
|
WITH target AS MATERIALIZED (${targetCTE}),
|
|
@@ -2179,7 +2180,13 @@ class PostgresStoreService extends __1.StoreService {
|
|
|
2179
2180
|
|| jsonb_build_object($${itemKeyIdx}::text, $${payloadIdx}::jsonb),
|
|
2180
2181
|
'batch_filled_at',
|
|
2181
2182
|
COALESCE(e.envelope->'batch_filled_at', '{}'::jsonb)
|
|
2182
|
-
|| jsonb_build_object($${itemKeyIdx}::text, to_jsonb(NOW())))
|
|
2183
|
+
|| jsonb_build_object($${itemKeyIdx}::text, to_jsonb(NOW())))
|
|
2184
|
+
|| CASE WHEN $${actorIdx}::text IS NULL THEN '{}'::jsonb
|
|
2185
|
+
ELSE jsonb_build_object(
|
|
2186
|
+
'batch_filled_by',
|
|
2187
|
+
COALESCE(e.envelope->'batch_filled_by', '{}'::jsonb)
|
|
2188
|
+
|| jsonb_build_object($${itemKeyIdx}::text, $${actorIdx}::text))
|
|
2189
|
+
END,
|
|
2183
2190
|
metadata = COALESCE(e.metadata, '{}'::jsonb)
|
|
2184
2191
|
|| COALESCE($${metaIdx}::jsonb, '{}'::jsonb)
|
|
2185
2192
|
|| jsonb_build_object(
|
|
@@ -2264,7 +2271,7 @@ class PostgresStoreService extends __1.StoreService {
|
|
|
2264
2271
|
* collection ONLY (never into the stored `resolver_payload`).
|
|
2265
2272
|
*/
|
|
2266
2273
|
async resolveEscalationBatchItem(params, wakeCommand, resolutionJson) {
|
|
2267
|
-
const { id, signalKey, namespace, itemKey, payload, metadata, assertClaim } = params;
|
|
2274
|
+
const { id, signalKey, namespace, itemKey, payload, metadata, assertClaim, actor } = params;
|
|
2268
2275
|
if ((id ? 1 : 0) + (signalKey ? 1 : 0) !== 1) {
|
|
2269
2276
|
throw new Error('resolveBatchItem requires exactly one of `id` or `signalKey`');
|
|
2270
2277
|
}
|
|
@@ -2274,6 +2281,7 @@ class PostgresStoreService extends __1.StoreService {
|
|
|
2274
2281
|
JSON.stringify(payload ?? {}),
|
|
2275
2282
|
metadata ? JSON.stringify(metadata) : null,
|
|
2276
2283
|
assertClaim ?? null,
|
|
2284
|
+
actor ?? null,
|
|
2277
2285
|
];
|
|
2278
2286
|
let nsClause = '';
|
|
2279
2287
|
if (namespace) {
|
|
@@ -2288,7 +2296,7 @@ class PostgresStoreService extends __1.StoreService {
|
|
|
2288
2296
|
FROM public.hmsh_escalations
|
|
2289
2297
|
WHERE ${id ? 'id' : 'signal_key'} = $1${nsClause}
|
|
2290
2298
|
LIMIT 1 FOR UPDATE`;
|
|
2291
|
-
const result = await this.pgClient.query(this._batchItemStatement(targetCTE, 2, 3, 4, 5, wakeCTE, wakeCount), sqlParams);
|
|
2299
|
+
const result = await this.pgClient.query(this._batchItemStatement(targetCTE, 2, 3, 4, 5, 6, wakeCTE, wakeCount), sqlParams);
|
|
2292
2300
|
return this._mapBatchItemRow(result.rows[0], assertClaim ?? undefined);
|
|
2293
2301
|
}
|
|
2294
2302
|
/**
|
|
@@ -2298,7 +2306,7 @@ class PostgresStoreService extends __1.StoreService {
|
|
|
2298
2306
|
* variant, matching the by-metadata precedent.
|
|
2299
2307
|
*/
|
|
2300
2308
|
async resolveEscalationBatchItemByMetadata(params, wakeCommand, resolutionJson) {
|
|
2301
|
-
const { key, value, roles, namespace, itemKey, payload, metadata } = params;
|
|
2309
|
+
const { key, value, roles, namespace, itemKey, payload, metadata, actor } = params;
|
|
2302
2310
|
const filter = JSON.stringify({ [key]: value });
|
|
2303
2311
|
const sqlParams = [
|
|
2304
2312
|
filter,
|
|
@@ -2307,6 +2315,7 @@ class PostgresStoreService extends __1.StoreService {
|
|
|
2307
2315
|
metadata ? JSON.stringify(metadata) : null,
|
|
2308
2316
|
null,
|
|
2309
2317
|
roles ?? null,
|
|
2318
|
+
actor ?? null,
|
|
2310
2319
|
];
|
|
2311
2320
|
let nsClause = '';
|
|
2312
2321
|
if (namespace) {
|
|
@@ -2325,7 +2334,7 @@ class PostgresStoreService extends __1.StoreService {
|
|
|
2325
2334
|
AND status IN ('pending', 'cancelled')
|
|
2326
2335
|
ORDER BY priority ASC, created_at ASC
|
|
2327
2336
|
LIMIT 1 FOR UPDATE`;
|
|
2328
|
-
const result = await this.pgClient.query(this._batchItemStatement(targetCTE, 2, 3, 4, 5, wakeCTE, wakeCount), sqlParams);
|
|
2337
|
+
const result = await this.pgClient.query(this._batchItemStatement(targetCTE, 2, 3, 4, 5, 7, wakeCTE, wakeCount), sqlParams);
|
|
2329
2338
|
return this._mapBatchItemRow(result.rows[0]);
|
|
2330
2339
|
}
|
|
2331
2340
|
_accumulateSelector(sel, label) {
|
|
@@ -10,6 +10,21 @@ export declare abstract class StreamService<ClientProvider extends ProviderClien
|
|
|
10
10
|
protected logger: ILogger;
|
|
11
11
|
protected appId: string;
|
|
12
12
|
protected config: StreamConfig;
|
|
13
|
+
/**
|
|
14
|
+
* Services running background work (pollers, scouts) in this process.
|
|
15
|
+
* `HotMesh.stop()` drains them through {@link StreamService.stopAll}, so
|
|
16
|
+
* no loop outlives the connections it queries.
|
|
17
|
+
*/
|
|
18
|
+
private static running;
|
|
19
|
+
/** Registers this service's background work for process shutdown. */
|
|
20
|
+
protected trackBackgroundWork(): void;
|
|
21
|
+
/** Forgets this service once its own `cleanup()` has run. */
|
|
22
|
+
protected untrackBackgroundWork(): void;
|
|
23
|
+
/**
|
|
24
|
+
* Runs `cleanup()` on every service still running background work.
|
|
25
|
+
* Each cleanup logs its own faults; one failure never blocks the rest.
|
|
26
|
+
*/
|
|
27
|
+
static stopAll(): Promise<void>;
|
|
13
28
|
constructor(streamClient: ClientProvider, storeClient: ProviderClient, config?: StreamConfig);
|
|
14
29
|
abstract init(namespace: string, appId: string, logger: ILogger): Promise<void>;
|
|
15
30
|
abstract mintKey(type: KeyType, params: KeyStoreParams): string;
|
|
@@ -73,6 +88,7 @@ export declare abstract class StreamService<ClientProvider extends ProviderClien
|
|
|
73
88
|
deadLetterMessages?(streamName: string, groupName: string, messageIds: string[]): Promise<number>;
|
|
74
89
|
expireJobMessages?(jid: string): Promise<number>;
|
|
75
90
|
extendReservation?(streamName: string, messageId: string, consumerName: string): Promise<number>;
|
|
91
|
+
releaseReservations?(streamName: string, messageIds: string[], consumerName: string): Promise<number>;
|
|
76
92
|
stopNotificationConsumer?(streamName: string, groupName: string): Promise<void>;
|
|
77
93
|
cleanup?(): Promise<void>;
|
|
78
94
|
}
|
|
@@ -2,6 +2,23 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.StreamService = void 0;
|
|
4
4
|
class StreamService {
|
|
5
|
+
/** Registers this service's background work for process shutdown. */
|
|
6
|
+
trackBackgroundWork() {
|
|
7
|
+
StreamService.running.add(this);
|
|
8
|
+
}
|
|
9
|
+
/** Forgets this service once its own `cleanup()` has run. */
|
|
10
|
+
untrackBackgroundWork() {
|
|
11
|
+
StreamService.running.delete(this);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Runs `cleanup()` on every service still running background work.
|
|
15
|
+
* Each cleanup logs its own faults; one failure never blocks the rest.
|
|
16
|
+
*/
|
|
17
|
+
static async stopAll() {
|
|
18
|
+
const services = [...StreamService.running];
|
|
19
|
+
StreamService.running.clear();
|
|
20
|
+
await Promise.all(services.map((service) => Promise.resolve(service.cleanup?.()).catch(() => undefined)));
|
|
21
|
+
}
|
|
5
22
|
constructor(streamClient, storeClient, config = {}) {
|
|
6
23
|
// Adaptive reservation timeout — set by the consumption manager
|
|
7
24
|
// based on stream depth. Providers read this when reserving messages.
|
|
@@ -13,4 +30,10 @@ class StreamService {
|
|
|
13
30
|
this.config = config;
|
|
14
31
|
}
|
|
15
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* Services running background work (pollers, scouts) in this process.
|
|
35
|
+
* `HotMesh.stop()` drains them through {@link StreamService.stopAll}, so
|
|
36
|
+
* no loop outlives the connections it queries.
|
|
37
|
+
*/
|
|
38
|
+
StreamService.running = new Set();
|
|
16
39
|
exports.StreamService = StreamService;
|
|
@@ -44,6 +44,13 @@ export declare function expireJobMessages(client: PostgresClientType & ProviderC
|
|
|
44
44
|
* stale consumer can abandon its execution.
|
|
45
45
|
*/
|
|
46
46
|
export declare function extendReservation(client: PostgresClientType & ProviderClient, tableName: string, streamName: string, messageId: string, consumerName: string, logger: ILogger): Promise<number>;
|
|
47
|
+
/**
|
|
48
|
+
* Release reservations the consumer still holds so the messages are
|
|
49
|
+
* redelivered immediately. Scoped to the owning consumer and to live
|
|
50
|
+
* rows: a message another consumer reclaimed, or one already acked or
|
|
51
|
+
* expired, is left alone.
|
|
52
|
+
*/
|
|
53
|
+
export declare function releaseReservations(client: PostgresClientType & ProviderClient, tableName: string, streamName: string, messageIds: string[], consumerName: string, logger: ILogger): Promise<number>;
|
|
47
54
|
/**
|
|
48
55
|
* Fetch messages from the stream with optional exponential backoff.
|
|
49
56
|
* Uses SKIP LOCKED for high-concurrency consumption.
|
|
@@ -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.extendReservation = exports.expireJobMessages = exports.buildPublishSQL = exports.publishMessages = exports.getMessagePriority = void 0;
|
|
3
|
+
exports.retryMessages = exports.deadLetterMessages = exports.ackAndDelete = exports.deleteMessages = exports.acknowledgeMessages = exports.fetchMessages = exports.releaseReservations = 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");
|
|
@@ -255,6 +255,32 @@ async function extendReservation(client, tableName, streamName, messageId, consu
|
|
|
255
255
|
}
|
|
256
256
|
}
|
|
257
257
|
exports.extendReservation = extendReservation;
|
|
258
|
+
/**
|
|
259
|
+
* Release reservations the consumer still holds so the messages are
|
|
260
|
+
* redelivered immediately. Scoped to the owning consumer and to live
|
|
261
|
+
* rows: a message another consumer reclaimed, or one already acked or
|
|
262
|
+
* expired, is left alone.
|
|
263
|
+
*/
|
|
264
|
+
async function releaseReservations(client, tableName, streamName, messageIds, consumerName, logger) {
|
|
265
|
+
if (messageIds.length === 0) {
|
|
266
|
+
return 0;
|
|
267
|
+
}
|
|
268
|
+
try {
|
|
269
|
+
const res = await client.query(`UPDATE ${tableName}
|
|
270
|
+
SET reserved_at = NULL, reserved_by = NULL
|
|
271
|
+
WHERE stream_name = $1 AND id = ANY($2::bigint[])
|
|
272
|
+
AND reserved_by = $3 AND expired_at IS NULL`, [streamName, messageIds.map((id) => parseInt(id, 10)), consumerName]);
|
|
273
|
+
return res.rowCount ?? 0;
|
|
274
|
+
}
|
|
275
|
+
catch (error) {
|
|
276
|
+
logger.error(`postgres-stream-release-error-${streamName}`, {
|
|
277
|
+
messageIds,
|
|
278
|
+
error,
|
|
279
|
+
});
|
|
280
|
+
throw error;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
exports.releaseReservations = releaseReservations;
|
|
258
284
|
/**
|
|
259
285
|
* Delivery liveness guard. Scoped to messages that are REDELIVERIES
|
|
260
286
|
* (a prior reservation lapsed) or RETRIES (retry_attempt > 0) — zombie
|
|
@@ -17,6 +17,7 @@ export declare class NotificationManager<TService> {
|
|
|
17
17
|
private static clientNotificationConsumers;
|
|
18
18
|
private static clientNotificationHandlers;
|
|
19
19
|
private static clientFallbackPollers;
|
|
20
|
+
private static relistenClients;
|
|
20
21
|
private instanceNotificationConsumers;
|
|
21
22
|
private notificationHandlerBound;
|
|
22
23
|
constructor(client: PostgresClientType & ProviderClient, getTableName: () => string, getFallbackInterval: () => number, logger: ILogger);
|
|
@@ -24,6 +25,12 @@ export declare class NotificationManager<TService> {
|
|
|
24
25
|
* Set up notification handler for this client (once per client).
|
|
25
26
|
*/
|
|
26
27
|
setupClientNotificationHandler(serviceInstance: TService): void;
|
|
28
|
+
/**
|
|
29
|
+
* Re-issue LISTEN for every stream channel with a consumer on this
|
|
30
|
+
* client, then wake each listening consumer. Failures are logged; the
|
|
31
|
+
* fallback poller and the next reconnect cover what remains.
|
|
32
|
+
*/
|
|
33
|
+
private static relisten;
|
|
27
34
|
/**
|
|
28
35
|
* Start fallback poller for missed notifications (once per client).
|
|
29
36
|
*/
|
|
@@ -55,6 +62,12 @@ export declare class NotificationManager<TService> {
|
|
|
55
62
|
*/
|
|
56
63
|
private getConsumerKey;
|
|
57
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* Hand a batch to a consumer's callback. The callback is async in
|
|
67
|
+
* practice; its rejection is logged here and never becomes an unhandled
|
|
68
|
+
* rejection. Unacked messages are redelivered by the stream.
|
|
69
|
+
*/
|
|
70
|
+
export declare function deliver(consumer: NotificationConsumer, messages: StreamMessage[], logger: ILogger): void;
|
|
58
71
|
/**
|
|
59
72
|
* Get configuration values for notification settings.
|
|
60
73
|
*/
|