@hotmeshio/hotmesh 0.29.1 → 0.30.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.
Files changed (48) hide show
  1. package/README.md +43 -0
  2. package/build/index.d.ts +2 -1
  3. package/build/index.js +3 -1
  4. package/build/modules/enums.d.ts +35 -0
  5. package/build/modules/enums.js +41 -1
  6. package/build/modules/errors.d.ts +26 -2
  7. package/build/modules/errors.js +82 -1
  8. package/build/modules/utils.d.ts +8 -0
  9. package/build/modules/utils.js +19 -1
  10. package/build/package.json +1 -1
  11. package/build/services/activities/trigger.js +3 -1
  12. package/build/services/connector/health.d.ts +42 -0
  13. package/build/services/connector/health.js +100 -0
  14. package/build/services/connector/index.js +2 -1
  15. package/build/services/connector/providers/postgres-resilient-client.d.ts +95 -0
  16. package/build/services/connector/providers/postgres-resilient-client.js +446 -0
  17. package/build/services/connector/providers/postgres.d.ts +6 -0
  18. package/build/services/connector/providers/postgres.js +72 -14
  19. package/build/services/durable/client.js +11 -3
  20. package/build/services/durable/handle.js +101 -41
  21. package/build/services/durable/worker.js +12 -4
  22. package/build/services/engine/completion.js +3 -3
  23. package/build/services/engine/signal.js +3 -3
  24. package/build/services/hotmesh/index.js +13 -4
  25. package/build/services/quorum/index.js +13 -13
  26. package/build/services/router/consumption/index.d.ts +20 -0
  27. package/build/services/router/consumption/index.js +177 -7
  28. package/build/services/store/providers/postgres/kvtransaction.js +8 -1
  29. package/build/services/store/providers/postgres/postgres.js +2 -2
  30. package/build/services/stream/index.d.ts +1 -0
  31. package/build/services/stream/providers/postgres/messages.d.ts +7 -0
  32. package/build/services/stream/providers/postgres/messages.js +27 -1
  33. package/build/services/stream/providers/postgres/notifications.d.ts +13 -0
  34. package/build/services/stream/providers/postgres/notifications.js +89 -2
  35. package/build/services/stream/providers/postgres/postgres.d.ts +7 -0
  36. package/build/services/stream/providers/postgres/postgres.js +22 -3
  37. package/build/services/stream/registry.d.ts +6 -0
  38. package/build/services/stream/registry.js +11 -2
  39. package/build/services/sub/providers/postgres/postgres.d.ts +6 -0
  40. package/build/services/sub/providers/postgres/postgres.js +62 -2
  41. package/build/services/task/index.js +1 -1
  42. package/build/services/worker/credentials.js +5 -0
  43. package/build/services/worker/index.js +5 -5
  44. package/build/types/index.d.ts +2 -2
  45. package/build/types/postgres.d.ts +20 -0
  46. package/build/types/provider.d.ts +28 -0
  47. package/index.ts +2 -0
  48. package/package.json +1 -1
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.PostgresSubService = void 0;
7
7
  const crypto_1 = __importDefault(require("crypto"));
8
8
  const enums_1 = require("../../../../modules/enums");
9
+ const errors_1 = require("../../../../modules/errors");
9
10
  const key_1 = require("../../../../modules/key");
10
11
  const index_1 = require("../../index");
11
12
  class PostgresSubService extends index_1.SubService {
@@ -43,7 +44,12 @@ class PostgresSubService extends index_1.SubService {
43
44
  // Call all callbacks
44
45
  callbackArray.forEach(([callbackKey, callback], index) => {
45
46
  try {
46
- callback(msg.channel, payload);
47
+ //async subscribers settle here; a rejection is logged, never unhandled
48
+ const settled = callback(msg.channel, payload);
49
+ if (settled &&
50
+ typeof settled.catch === 'function') {
51
+ settled.catch((err) => this.logger?.error(`Error in subscription callback for ${msg.channel}:`, err));
52
+ }
47
53
  }
48
54
  catch (err) {
49
55
  this.logger?.error(`Error in subscription callback for ${msg.channel}:`, err);
@@ -55,9 +61,37 @@ class PostgresSubService extends index_1.SubService {
55
61
  }
56
62
  }
57
63
  });
64
+ // A resilient client replaces its session after a loss; LISTEN is
65
+ // session state, so every channel is re-armed on the new session
66
+ const eventClient = this.eventClient;
67
+ if (typeof eventClient.on === 'function' &&
68
+ !PostgresSubService.relistenClients.has(eventClient)) {
69
+ PostgresSubService.relistenClients.add(eventClient);
70
+ eventClient.on('reconnected', () => {
71
+ void PostgresSubService.relisten(eventClient, this.logger);
72
+ });
73
+ }
58
74
  // Mark this client as having a notification handler
59
75
  PostgresSubService.clientHandlers.set(this.eventClient, true);
60
76
  }
77
+ /**
78
+ * Re-issue LISTEN for every channel subscribed on a client. A failure
79
+ * leaves the channel for the next reconnect; nothing is thrown.
80
+ */
81
+ static async relisten(client, logger) {
82
+ const channels = Array.from(PostgresSubService.clientSubscriptions.get(client)?.keys() ?? []);
83
+ let armed = 0;
84
+ for (const channel of channels) {
85
+ try {
86
+ await client.query(`LISTEN "${channel}"`);
87
+ armed++;
88
+ }
89
+ catch (error) {
90
+ logger?.warn('postgres-sub-relisten-error', { channel, error });
91
+ }
92
+ }
93
+ logger?.info('postgres-sub-relisten', { channels: channels.length, armed });
94
+ }
61
95
  transact() {
62
96
  throw new Error('Transactions are not supported in lightweight pub/sub');
63
97
  }
@@ -99,7 +133,22 @@ class PostgresSubService extends index_1.SubService {
99
133
  callbacks = new Map();
100
134
  clientSubscriptions.set(safeKey, callbacks);
101
135
  // Start listening to the safe topic (only once per channel across all instances)
102
- await this.eventClient.query(`LISTEN "${safeKey}"`);
136
+ try {
137
+ await this.eventClient.query(`LISTEN "${safeKey}"`);
138
+ }
139
+ catch (err) {
140
+ if (!(0, errors_1.isConnectionError)(err)) {
141
+ clientSubscriptions.delete(safeKey);
142
+ throw err;
143
+ }
144
+ //the session is being replaced: the channel stays registered and
145
+ //the reconnect re-arms it, so the subscriber is not lost
146
+ this.logger?.warn('postgres-subscribe-deferred', {
147
+ originalKey,
148
+ safeKey,
149
+ error: err?.message,
150
+ });
151
+ }
103
152
  }
104
153
  // Generate unique callback key to avoid overwrites
105
154
  const callbackKey = `${this.instanceId}-${Date.now()}-${Math.random()}`;
@@ -247,6 +296,15 @@ class PostgresSubService extends index_1.SubService {
247
296
  return true;
248
297
  }
249
298
  catch (err) {
299
+ // Pub/sub is best effort: an outage drops the message, never the caller
300
+ if ((0, errors_1.isConnectionError)(err)) {
301
+ this.logger?.warn('postgres-publish-failed-connection-unavailable', {
302
+ originalKey,
303
+ safeKey,
304
+ error: err?.message,
305
+ });
306
+ return false;
307
+ }
250
308
  // Handle gracefully if client was closed during operation
251
309
  if (err?.message?.includes('closed') || err?.message?.includes('queryable')) {
252
310
  this.logger?.debug('postgres-publish-failed-closed-client', {
@@ -271,3 +329,5 @@ exports.PostgresSubService = PostgresSubService;
271
329
  // Static maps to manage subscriptions across all instances sharing the same client
272
330
  PostgresSubService.clientSubscriptions = new Map();
273
331
  PostgresSubService.clientHandlers = new Map();
332
+ // Clients whose 'reconnected' event re-arms LISTEN (armed once per client)
333
+ PostgresSubService.relistenClients = new WeakSet();
@@ -24,7 +24,7 @@ class TaskService {
24
24
  else {
25
25
  await this.store.deleteProcessedTaskQueue(workItemKey, sourceKey, destinationKey, scrub === 'true');
26
26
  }
27
- setImmediate(() => this.processWebHooks(hookEventCallback));
27
+ setImmediate(() => (0, utils_1.detach)(this.processWebHooks(hookEventCallback), this.logger, 'task-process-webhooks-error'));
28
28
  }
29
29
  }
30
30
  async enqueueWorkItems(keys) {
@@ -21,6 +21,11 @@ async function createAdminClient(connection) {
21
21
  const ClientClass = config.class;
22
22
  const options = config.options;
23
23
  const client = new ClientClass(options);
24
+ //a lost socket fails the pending admin query; the 'error' event itself
25
+ //must never go unhandled (that ends the process)
26
+ if (typeof client.on === 'function') {
27
+ client.on('error', () => undefined);
28
+ }
24
29
  await client.connect();
25
30
  return client;
26
31
  }
@@ -129,16 +129,16 @@ class WorkerService {
129
129
  if (message.type === 'throttle') {
130
130
  if (message.topic !== null) {
131
131
  //undefined allows passthrough
132
- self.throttle(message.throttle);
132
+ (0, utils_1.detach)(self.throttle(message.throttle), self.logger, 'worker-throttle-error');
133
133
  }
134
134
  }
135
135
  else if (message.type === 'ping') {
136
- self.sayPong(self.appId, self.guid, message.originator, message.details);
136
+ (0, utils_1.detach)(self.sayPong(self.appId, self.guid, message.originator, message.details), self.logger, 'worker-pong-error');
137
137
  }
138
138
  else if (message.type === 'rollcall') {
139
139
  if (message.topic !== null) {
140
140
  //undefined allows passthrough
141
- self.doRollCall(message);
141
+ (0, utils_1.detach)(self.doRollCall(message), self.logger, 'worker-rollcall-error');
142
142
  }
143
143
  }
144
144
  };
@@ -203,12 +203,12 @@ class WorkerService {
203
203
  signature: signature ? this.callback.toString() : undefined,
204
204
  };
205
205
  }
206
- this.subscribe.publish(key_1.KeyType.QUORUM, {
206
+ (0, utils_1.detach)(this.subscribe.publish(key_1.KeyType.QUORUM, {
207
207
  type: 'pong',
208
208
  guid,
209
209
  originator,
210
210
  profile,
211
- }, appId);
211
+ }, appId), this.logger, 'worker-pong-publish-error');
212
212
  }
213
213
  /**
214
214
  * @private
@@ -14,9 +14,9 @@ export { ILogger, LogLevel } from './logger';
14
14
  export { ExtensionType, JobCompletionOptions, JobData, JobsData, JobInterruptOptions, JobMetadata, JobOutput, JobState, JobStatus, PartialJobState, } from './job';
15
15
  export { MappingStatements } from './map';
16
16
  export { Pipe, PipeContext, PipeItem, PipeItems, PipeObject, ReduceObject, } from './pipe';
17
- export { ProviderClass, ProviderClient, ProviderConfig, ProviderTransaction, Providers, TransactionResultList, ProviderNativeClient, ProviderOptions, } from './provider';
17
+ export { ProviderClass, ProviderClient, ProviderConfig, ProviderTransaction, Providers, TransactionResultList, ProviderNativeClient, ProviderOptions, ConnectionHealthEvent, ConnectionHealthSnapshot, ConnectionLostEvent, ConnectionRestoredEvent, } from './provider';
18
18
  export { VirtualConnectParams, VirtualContext, VirtualExecParams, VirtualCronParams, VirtualExecOptions, VirtualCronOptions, VirtualInterruptOptions, VirtualInterruptParams, VirtualFlushParams, } from './virtual';
19
- export { PostgresClassType, PostgresClientOptions, PostgresClientType, PostgresConsumerGroup, PostgresPendingMessage, PostgresPoolClientType, PostgresQueryConfigType, PostgresQueryResultType, PostgresStreamMessage, PostgresStreamOptions, PostgresTransaction, } from './postgres';
19
+ export { PostgresClassType, PostgresClientOptions, PostgresClientType, PostgresConsumerGroup, PostgresPendingMessage, PostgresPoolClientType, PostgresQueryConfigType, PostgresQueryResultType, PostgresReconnectedEvent, PostgresStreamMessage, PostgresStreamOptions, PostgresTransaction, } from './postgres';
20
20
  export { ActivateMessage, CronMessage, JobMessage, JobMessageCallback, PingMessage, PongMessage, QuorumMessage, QuorumMessageCallback, QuorumProfile, RollCallMessage, RollCallOptions, SubscriptionCallback, SubscriptionOptions, SystemHealth, ThrottleMessage, ThrottleOptions, WorkMessage, } from './quorum';
21
21
  export { NatsAckPolicy, NatsAckPolicyExplicitType, NatsClassType, NatsClientType, NatsClientOptions, NatsConsumerConfigType, NatsJetStreamManager, NatsConnection, NatsJetStreamType, NatsConnectionOptions, NatsConsumerConfig, NatsConsumerInfo, NatsConsumerManager, NatsDeliveryInfo, NatsJetStreamOptions, NatsError, NatsErrorType, NatsJetStreamClient, NatsJsMsg, NatsMessageType, NatsMsgExpect, NatsPubAck, NatsPubAckType, NatsPublishOptions, NatsRetentionPolicy, NatsRetentionPolicyWorkqueueType, NatsSequenceInfo, NatsStorageMemoryType, NatsStorageType, NatsStreamConfig, NatsStreamInfo, NatsStreamManager, NatsStreamConfigType, NatsStreamInfoType, NatsStreamOptions, NatsStreamState, NatsTransaction, } from './nats';
22
22
  export { JSONSchema, StringAnyType, StringScalarType, StringStringType, SymbolMap, SymbolMaps, SymbolRanges, Symbols, SymbolSets, } from './serializer';
@@ -8,6 +8,14 @@ export interface PostgresClientOptions {
8
8
  max?: number;
9
9
  idleTimeoutMillis?: number;
10
10
  ssl?: boolean | Record<string, unknown>;
11
+ /** Milliseconds to wait for a connection before failing (pg default: forever). */
12
+ connectionTimeoutMillis?: number;
13
+ /** Enable TCP keepalive on the socket. */
14
+ keepAlive?: boolean;
15
+ /** Idle time before the first TCP keepalive probe. */
16
+ keepAliveInitialDelayMillis?: number;
17
+ /** Reported in `pg_stat_activity.application_name`. */
18
+ application_name?: string;
11
19
  }
12
20
  export type PostgresJobEnumType = 'status' | 'jdata' | 'adata' | 'udata' | 'jmark' | 'hmark' | 'other';
13
21
  export type PostgresClassType = {
@@ -30,6 +38,18 @@ export interface PostgresClientType {
30
38
  off?: (event: 'notification', listener: (notification: PostgresNotification) => void) => void;
31
39
  removeAllListeners?: (event?: string) => void;
32
40
  }
41
+ /**
42
+ * Payload of the `'reconnected'` event a resilient client emits after it
43
+ * replaces a lost session. Session state (LISTEN channels, open
44
+ * transactions) does not survive; owners re-arm it on this event.
45
+ */
46
+ export interface PostgresReconnectedEvent {
47
+ connectionId: string;
48
+ generation: number;
49
+ at: number;
50
+ downtimeMs: number;
51
+ attempts: number;
52
+ }
33
53
  export interface PostgresPoolClientType {
34
54
  connect: () => Promise<PostgresClientType>;
35
55
  release: () => void;
@@ -139,3 +139,31 @@ export interface KVSQLProviderTransaction extends ProviderTransaction {
139
139
  scan(cursor: number, count?: number): ProviderTransaction;
140
140
  rename(oldKey: string, newKey: string): ProviderTransaction;
141
141
  }
142
+ export type ConnectionHealthEvent = 'lost' | 'restored';
143
+ /** A HotMesh database connection lost its session and began reconnecting. */
144
+ export interface ConnectionLostEvent {
145
+ connectionId: string;
146
+ /** Epoch milliseconds when the loss was observed. */
147
+ at: number;
148
+ error: {
149
+ message: string;
150
+ code?: string;
151
+ };
152
+ }
153
+ /** A HotMesh database connection replaced its lost session. */
154
+ export interface ConnectionRestoredEvent {
155
+ connectionId: string;
156
+ /** Epoch milliseconds when the new session was established. */
157
+ at: number;
158
+ downtimeMs: number;
159
+ attempts: number;
160
+ }
161
+ /** Process-wide availability of HotMesh's resilient database connections. */
162
+ export interface ConnectionHealthSnapshot {
163
+ /** `down` while any registered connection is reconnecting. */
164
+ state: 'up' | 'down';
165
+ total: number;
166
+ down: number;
167
+ /** Epoch milliseconds of the earliest loss still unrecovered. */
168
+ downSince?: number;
169
+ }
package/index.ts CHANGED
@@ -18,6 +18,7 @@ import * as KeyStore from './modules/key';
18
18
  import { ConnectorService as Connector } from './services/connector/factory';
19
19
  import { PostgresConnection as ConnectorPostgres } from './services/connector/providers/postgres';
20
20
  import { NatsConnection as ConnectorNATS } from './services/connector/providers/nats';
21
+ import { ConnectionHealth } from './services/connector/health';
21
22
  import { Escalations } from './services/escalations';
22
23
 
23
24
  export {
@@ -25,6 +26,7 @@ export {
25
26
  Connector, //factory
26
27
  ConnectorNATS,
27
28
  ConnectorPostgres,
29
+ ConnectionHealth,
28
30
 
29
31
  //Top-level Modules
30
32
  HotMesh,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hotmeshio/hotmesh",
3
- "version": "0.29.1",
3
+ "version": "0.30.0",
4
4
  "description": "Durable Workflow",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",