@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
package/README.md CHANGED
@@ -224,6 +224,49 @@ Defaults: 3 attempts, coefficient 10, 120s cap. Delay formula: `min(coefficient
224
224
 
225
225
  If all retries are exhausted, the activity fails and the error propagates to the workflow function — handle it with a standard `try/catch`.
226
226
 
227
+ ## Connection resilience
228
+
229
+ Every connection HotMesh opens from a `pg.Client` class survives database restarts, failovers, and dropped sockets. A process running HotMesh never exits because the database went away: the connection reconnects in place and work resumes when the database returns.
230
+
231
+ - **Reconnect in place.** A lost session is replaced with jittered exponential backoff (250 ms base, 10 s cap), without limit, until the connection is ended. Store, stream, and sub keep the same client object, so nothing above the connector sees the swap.
232
+ - **Fail fast while away.** A query issued while reconnecting rejects at once with `HotMeshConnectionError` (`code: 'HMSH_PG_UNAVAILABLE'`, the native error on `cause`).
233
+ - **LISTEN re-armed.** Pub/sub and stream channels are re-subscribed on the new session, and stream consumers fetch at once, so messages sent while the session was down are still delivered.
234
+ - **No lost work, no spent retries.** A message whose processing or response write fails because the connection is unavailable is neither acked nor failed. Its reservation is released when the connection returns and it is redelivered, without spending its retry budget.
235
+ - **Transactions never straddle sessions.** Statements of a transaction that was open when its session died are refused on the new session until the owner rolls back.
236
+ - **Silent hosts detected.** An idle session is probed every 15 s; a probe that does not answer within 5 s drops the socket and reconnects.
237
+ - **Waits survive.** `handle.result()` keeps waiting through an outage and re-checks as soon as the connection is restored.
238
+
239
+ Observe availability and classify errors:
240
+
241
+ ```typescript
242
+ import { ConnectionHealth, Errors } from '@hotmeshio/hotmesh';
243
+
244
+ ConnectionHealth.on('lost', (e) => log.warn('database lost', e)); // { connectionId, at, error }
245
+ ConnectionHealth.on('restored', (e) => log.info('database back', e)); // { connectionId, at, downtimeMs, attempts }
246
+ ConnectionHealth.snapshot(); // { state: 'up' | 'down', total, down, downSince? }
247
+
248
+ try {
249
+ await client.workflow.start({ /* ... */ });
250
+ } catch (err) {
251
+ if (Errors.isConnectionError(err)) {
252
+ // the database is unavailable: retry later or park the request
253
+ }
254
+ }
255
+ ```
256
+
257
+ | Setting | Default | Effect |
258
+ |---|---|---|
259
+ | `HMSH_PG_RESILIENT` | `true` | `false` restores the plain `pg.Client` |
260
+ | `HMSH_PG_RECONNECT_BASE_MS` | `250` | first reconnect delay ceiling |
261
+ | `HMSH_PG_RECONNECT_MAX_MS` | `10000` | largest reconnect delay |
262
+ | `HMSH_PG_HEARTBEAT_MS` | `15000` | idle probe interval (`0` disables) |
263
+ | `HMSH_PG_HEARTBEAT_TIMEOUT_MS` | `5000` | probe answer deadline |
264
+ | `HMSH_PG_CONNECT_TIMEOUT_MS` | `10000` | `connectionTimeoutMillis` when you set none (`0` keeps pg's default) |
265
+ | `HMSH_PG_KEEPALIVE_DELAY_MS` | `10000` | `keepAliveInitialDelayMillis` when you set none |
266
+ | `HMSH_PG_TX_LOST_WINDOW_MS` | `30000` | longest refusal of a lost transaction's statements |
267
+
268
+ HotMesh fills `connectionTimeoutMillis`, `keepAlive`, `keepAliveInitialDelayMillis`, and `application_name` (`hotmesh`) only when your connection options leave them unset. When you pass a `pg.Pool` instead of a client class, HotMesh adds a logging `'error'` listener only if the pool has none; reconnect and re-LISTEN apply to the client-class form.
269
+
227
270
  ## Workflow state is queryable data
228
271
 
229
272
  Workflow state lives in your database as ordinary rows — `jobs` and `jobs_attributes`. Query it directly, back it up with pg_dump, replicate it, join it against your application tables.
package/build/index.d.ts CHANGED
@@ -18,8 +18,9 @@ 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
  export { Connector, //factory
23
- ConnectorNATS, ConnectorPostgres, HotMesh, HotMeshConfig, Virtual, Durable, Escalations, DBA, Client, Connection, proxyActivities, Search, Entity, Worker, workflow, WorkflowHandle, Enums, Errors, Utils, KeyStore, };
24
+ ConnectorNATS, ConnectorPostgres, ConnectionHealth, HotMesh, HotMeshConfig, Virtual, Durable, Escalations, DBA, Client, Connection, proxyActivities, Search, Entity, Worker, workflow, WorkflowHandle, Enums, Errors, Utils, KeyStore, };
24
25
  export * as Types from './types';
25
26
  export type { EventsConfig, SystemEvent } from './types/system_events';
package/build/index.js CHANGED
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.Types = exports.KeyStore = exports.Utils = exports.Errors = exports.Enums = exports.WorkflowHandle = exports.workflow = exports.Worker = exports.Entity = exports.Search = exports.proxyActivities = exports.Connection = exports.Client = exports.DBA = exports.Escalations = exports.Durable = exports.Virtual = exports.HotMesh = exports.ConnectorPostgres = exports.ConnectorNATS = exports.Connector = void 0;
26
+ exports.Types = exports.KeyStore = exports.Utils = exports.Errors = exports.Enums = exports.WorkflowHandle = exports.workflow = exports.Worker = exports.Entity = exports.Search = exports.proxyActivities = exports.Connection = exports.Client = exports.DBA = exports.Escalations = exports.Durable = exports.Virtual = exports.HotMesh = exports.ConnectionHealth = exports.ConnectorPostgres = exports.ConnectorNATS = exports.Connector = void 0;
27
27
  const hotmesh_1 = require("./services/hotmesh");
28
28
  Object.defineProperty(exports, "HotMesh", { enumerable: true, get: function () { return hotmesh_1.HotMesh; } });
29
29
  const virtual_1 = require("./services/virtual");
@@ -62,6 +62,8 @@ const postgres_1 = require("./services/connector/providers/postgres");
62
62
  Object.defineProperty(exports, "ConnectorPostgres", { enumerable: true, get: function () { return postgres_1.PostgresConnection; } });
63
63
  const nats_1 = require("./services/connector/providers/nats");
64
64
  Object.defineProperty(exports, "ConnectorNATS", { enumerable: true, get: function () { return nats_1.NatsConnection; } });
65
+ const health_1 = require("./services/connector/health");
66
+ Object.defineProperty(exports, "ConnectionHealth", { enumerable: true, get: function () { return health_1.ConnectionHealth; } });
65
67
  const escalations_1 = require("./services/escalations");
66
68
  Object.defineProperty(exports, "Escalations", { enumerable: true, get: function () { return escalations_1.Escalations; } });
67
69
  exports.Types = __importStar(require("./types"));
@@ -305,3 +305,38 @@ export declare const HMSH_NOTIFY_PAYLOAD_LIMIT: number;
305
305
  * Used when LISTEN/NOTIFY is unavailable or fails. Default 30 seconds.
306
306
  */
307
307
  export declare const HMSH_ROUTER_POLL_FALLBACK_INTERVAL: number;
308
+ /**
309
+ * When `true` (default), every connection HotMesh opens from a
310
+ * `pg.Client` class is a resilient client: it survives server restarts,
311
+ * failovers and dropped sockets by reconnecting in place and re-arming
312
+ * LISTEN. Set `HMSH_PG_RESILIENT=false` to use the plain native client.
313
+ */
314
+ export declare const HMSH_PG_RESILIENT: boolean;
315
+ /** Base delay for the first reconnect attempt (full-jitter exponential backoff). */
316
+ export declare const HMSH_PG_RECONNECT_BASE_MS: number;
317
+ /** Ceiling for any single reconnect delay. Reconnect never gives up until the client is ended. */
318
+ export declare const HMSH_PG_RECONNECT_MAX_MS: number;
319
+ /**
320
+ * Interval at which an idle resilient connection is probed with
321
+ * `SELECT 1`. A probe that fails or exceeds the timeout below drops the
322
+ * socket, which detects a blackholed host. `0` disables the heartbeat.
323
+ */
324
+ export declare const HMSH_PG_HEARTBEAT_MS: number;
325
+ /** Time a heartbeat probe may take before the session is considered lost. */
326
+ export declare const HMSH_PG_HEARTBEAT_TIMEOUT_MS: number;
327
+ /**
328
+ * Default `connectionTimeoutMillis` applied to HotMesh-created clients
329
+ * when the caller does not set one, so a connect against a restarting
330
+ * or unreachable host fails instead of hanging. `0` leaves pg's default
331
+ * (no timeout).
332
+ */
333
+ export declare const HMSH_PG_CONNECT_TIMEOUT_MS: number;
334
+ /** Default TCP keepalive idle delay applied when the caller does not set one. */
335
+ export declare const HMSH_PG_KEEPALIVE_DELAY_MS: number;
336
+ /**
337
+ * How long statements are refused after a reconnect when a transaction
338
+ * was open on the lost session, unless the owner closes it first. Bounds
339
+ * the refusal so an owner that never issues ROLLBACK cannot wedge the
340
+ * client.
341
+ */
342
+ export declare const HMSH_PG_TX_LOST_WINDOW_MS: number;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.HMSH_RESERVATION_TIMEOUT_S = exports.HMSH_ENGINE_CONCURRENCY = exports.HMSH_BATCH_SIZE_MIN = exports.HMSH_BATCH_SIZE = exports.HMSH_XPENDING_COUNT = exports.HMSH_XCLAIM_COUNT = exports.HMSH_XCLAIM_DELAY_MS = exports.HMSH_BLOCK_TIME_MS = exports.HMSH_DURABLE_INITIAL_INTERVAL = exports.HMSH_DURABLE_EXP_BACKOFF = exports.HMSH_DURABLE_MAX_INTERVAL = exports.HMSH_DURABLE_MAX_ATTEMPTS = exports.HMSH_GRADUATED_INTERVAL_MS = exports.HMSH_MAX_TIMEOUT_MS = exports.HMSH_MAX_CYCLES = exports.HMSH_POISON_MESSAGE_THRESHOLD = exports.HMSH_MAX_RETRIES = exports.MAX_DELAY = exports.MAX_STREAM_RETRIES = exports.INITIAL_STREAM_BACKOFF = exports.MAX_STREAM_BACKOFF = exports.HMSH_EXPIRE_JOB_SECONDS = exports.HMSH_OTT_WAIT_TIME = exports.HMSH_DEPLOYMENT_PAUSE = exports.HMSH_DEPLOYMENT_DELAY = exports.HMSH_ACTIVATION_MAX_RETRY = exports.HMSH_QUORUM_DELAY_MS = exports.HMSH_QUORUM_ROLLCALL_CYCLES = exports.HMSH_STATUS_UNKNOWN = exports.HMSH_CODE_DURABLE_RETRYABLE = exports.HMSH_CODE_DURABLE_FATAL = exports.HMSH_CODE_DURABLE_MAXED = exports.HMSH_CODE_DURABLE_TIMEOUT = exports.HMSH_CODE_DURABLE_WAIT = exports.HMSH_CODE_DURABLE_CONTINUE = exports.HMSH_CODE_DURABLE_PROXY = exports.HMSH_CODE_DURABLE_CHILD = exports.HMSH_CODE_DURABLE_ALL = exports.HMSH_CODE_DURABLE_SLEEP = exports.HMSH_CODE_UNACKED = exports.HMSH_CODE_TIMEOUT = exports.HMSH_CODE_UNKNOWN = exports.HMSH_CODE_INTERRUPT = exports.HMSH_CODE_NOTFOUND = exports.HMSH_CODE_PENDING = exports.HMSH_CODE_SUCCESS = exports.HMSH_PENDING_SIGNAL_EXPIRE = exports.HMSH_SIGNAL_EXPIRE = exports.HMSH_TELEMETRY = exports.HMSH_LOGLEVEL = void 0;
4
- exports.HMSH_ROUTER_POLL_FALLBACK_INTERVAL = exports.HMSH_NOTIFY_PAYLOAD_LIMIT = exports.HMSH_DURESS_HYSTERESIS_COUNT = exports.HMSH_DURESS_BROADCAST_INTERVAL_MS = exports.HMSH_DURESS_MODERATE_CEILING_MS = exports.HMSH_DURESS_MILD_CEILING_MS = exports.HMSH_DURESS_HEALTHY_CEILING_MS = exports.HMSH_DURESS_EVAL_INTERVAL = exports.HMSH_DURESS_ALPHA = exports.DEFAULT_TASK_QUEUE = exports.HMSH_GUID_SIZE = exports.HMSH_ROUTER_SCOUT_INTERVAL_MS = exports.HMSH_ROUTER_SCOUT_INTERVAL_SECONDS = exports.HMSH_SCOUT_INTERVAL_SECONDS = exports.HMSH_FIDELITY_SECONDS = exports.HMSH_EXPIRE_DURATION = exports.HMSH_RESERVATION_TIMEOUT_MAX_S = void 0;
4
+ exports.HMSH_PG_TX_LOST_WINDOW_MS = exports.HMSH_PG_KEEPALIVE_DELAY_MS = exports.HMSH_PG_CONNECT_TIMEOUT_MS = exports.HMSH_PG_HEARTBEAT_TIMEOUT_MS = exports.HMSH_PG_HEARTBEAT_MS = exports.HMSH_PG_RECONNECT_MAX_MS = exports.HMSH_PG_RECONNECT_BASE_MS = exports.HMSH_PG_RESILIENT = exports.HMSH_ROUTER_POLL_FALLBACK_INTERVAL = exports.HMSH_NOTIFY_PAYLOAD_LIMIT = exports.HMSH_DURESS_HYSTERESIS_COUNT = exports.HMSH_DURESS_BROADCAST_INTERVAL_MS = exports.HMSH_DURESS_MODERATE_CEILING_MS = exports.HMSH_DURESS_MILD_CEILING_MS = exports.HMSH_DURESS_HEALTHY_CEILING_MS = exports.HMSH_DURESS_EVAL_INTERVAL = exports.HMSH_DURESS_ALPHA = exports.DEFAULT_TASK_QUEUE = exports.HMSH_GUID_SIZE = exports.HMSH_ROUTER_SCOUT_INTERVAL_MS = exports.HMSH_ROUTER_SCOUT_INTERVAL_SECONDS = exports.HMSH_SCOUT_INTERVAL_SECONDS = exports.HMSH_FIDELITY_SECONDS = exports.HMSH_EXPIRE_DURATION = exports.HMSH_RESERVATION_TIMEOUT_MAX_S = void 0;
5
5
  /**
6
6
  * Determines the log level for the application. The default is 'info'.
7
7
  */
@@ -338,3 +338,43 @@ exports.HMSH_NOTIFY_PAYLOAD_LIMIT = parseInt(process.env.HMSH_NOTIFY_PAYLOAD_LIM
338
338
  * Used when LISTEN/NOTIFY is unavailable or fails. Default 30 seconds.
339
339
  */
340
340
  exports.HMSH_ROUTER_POLL_FALLBACK_INTERVAL = parseInt(process.env.HOTMESH_POSTGRES_FALLBACK_INTERVAL, 10) || 30000;
341
+ // ************* POSTGRES CONNECTION RESILIENCE *************
342
+ const intFromEnv = (name, fallback) => {
343
+ const value = parseInt(process.env[name], 10);
344
+ return Number.isFinite(value) && value >= 0 ? value : fallback;
345
+ };
346
+ /**
347
+ * When `true` (default), every connection HotMesh opens from a
348
+ * `pg.Client` class is a resilient client: it survives server restarts,
349
+ * failovers and dropped sockets by reconnecting in place and re-arming
350
+ * LISTEN. Set `HMSH_PG_RESILIENT=false` to use the plain native client.
351
+ */
352
+ exports.HMSH_PG_RESILIENT = process.env.HMSH_PG_RESILIENT !== 'false';
353
+ /** Base delay for the first reconnect attempt (full-jitter exponential backoff). */
354
+ exports.HMSH_PG_RECONNECT_BASE_MS = intFromEnv('HMSH_PG_RECONNECT_BASE_MS', 250);
355
+ /** Ceiling for any single reconnect delay. Reconnect never gives up until the client is ended. */
356
+ exports.HMSH_PG_RECONNECT_MAX_MS = intFromEnv('HMSH_PG_RECONNECT_MAX_MS', 10000);
357
+ /**
358
+ * Interval at which an idle resilient connection is probed with
359
+ * `SELECT 1`. A probe that fails or exceeds the timeout below drops the
360
+ * socket, which detects a blackholed host. `0` disables the heartbeat.
361
+ */
362
+ exports.HMSH_PG_HEARTBEAT_MS = intFromEnv('HMSH_PG_HEARTBEAT_MS', 15000);
363
+ /** Time a heartbeat probe may take before the session is considered lost. */
364
+ exports.HMSH_PG_HEARTBEAT_TIMEOUT_MS = intFromEnv('HMSH_PG_HEARTBEAT_TIMEOUT_MS', 5000);
365
+ /**
366
+ * Default `connectionTimeoutMillis` applied to HotMesh-created clients
367
+ * when the caller does not set one, so a connect against a restarting
368
+ * or unreachable host fails instead of hanging. `0` leaves pg's default
369
+ * (no timeout).
370
+ */
371
+ exports.HMSH_PG_CONNECT_TIMEOUT_MS = intFromEnv('HMSH_PG_CONNECT_TIMEOUT_MS', 10000);
372
+ /** Default TCP keepalive idle delay applied when the caller does not set one. */
373
+ exports.HMSH_PG_KEEPALIVE_DELAY_MS = intFromEnv('HMSH_PG_KEEPALIVE_DELAY_MS', 10000);
374
+ /**
375
+ * How long statements are refused after a reconnect when a transaction
376
+ * was open on the lost session, unless the owner closes it first. Bounds
377
+ * the refusal so an owner that never issues ROLLBACK cannot wedge the
378
+ * client.
379
+ */
380
+ exports.HMSH_PG_TX_LOST_WINDOW_MS = intFromEnv('HMSH_PG_TX_LOST_WINDOW_MS', 30000);
@@ -12,12 +12,17 @@ import { DurableChildErrorType, DurableContinueAsNewErrorType, DurableProxyError
12
12
  * Message is acked; job is marked failed.
13
13
  * COLLATION — duplicate delivery detected via GUID ledger.
14
14
  * Silent ack; no work needed.
15
+ * UNAVAILABLE — the HotMesh database connection is unavailable.
16
+ * The message is NOT acked and no response is published;
17
+ * it is redelivered once the connection returns, without
18
+ * spending the retry budget.
15
19
  */
16
20
  export declare enum ErrorCategory {
17
21
  FATAL = "fatal",
18
22
  RETRYABLE = "retryable",
19
23
  TERMINAL = "terminal",
20
- COLLATION = "collation"
24
+ COLLATION = "collation",
25
+ UNAVAILABLE = "unavailable"
21
26
  }
22
27
  export declare function classifyError(error: unknown): ErrorCategory;
23
28
  declare class GetStateError extends Error {
@@ -165,6 +170,24 @@ declare class LeaseExpiredError extends Error {
165
170
  reservationTimeoutS: number;
166
171
  constructor(deadlineMs: number, reservationTimeoutS: number);
167
172
  }
173
+ /**
174
+ * Raised by a HotMesh PostgreSQL connection when the failure is the
175
+ * connection's, not the statement's: the session was lost, is
176
+ * reconnecting, or a transaction did not survive a reconnect. The
177
+ * native error, when there is one, is kept on `cause`.
178
+ */
179
+ declare class HotMeshConnectionError extends Error {
180
+ readonly code = "HMSH_PG_UNAVAILABLE";
181
+ readonly connectionId?: string;
182
+ readonly cause?: unknown;
183
+ constructor(message: string, connectionId?: string, cause?: unknown);
184
+ }
185
+ /**
186
+ * True when an error means the database connection is unavailable (lost,
187
+ * refused, timed out, shutting down), not that the statement failed.
188
+ * Walks `cause` so a wrapped native error is recognized.
189
+ */
190
+ declare function isConnectionError(error: unknown, depth?: number): boolean;
168
191
  declare class CollationError extends Error {
169
192
  status: number;
170
193
  leg: ActivityDuplex;
@@ -172,4 +195,5 @@ declare class CollationError extends Error {
172
195
  fault: CollationFaultType;
173
196
  constructor(status: number, leg: ActivityDuplex, stage: CollationStage, fault?: CollationFaultType);
174
197
  }
175
- export { CollationError, DurableChildError, DurableContinueAsNewError, DurableFatalError, DurableMaxedError, DurableProxyError, DurableRetryError, DurableSleepError, DurableTimeoutError, DurableWaitForAllError, DurableWaitForError, DuplicateJobError, ExecActivityError, GenerationalError, GetStateError, InactiveJobError, LeaseExpiredError, MapDataError, RegisterTimeoutError, SetStateError, };
198
+ export { isConnectionError };
199
+ export { CollationError, DurableChildError, DurableContinueAsNewError, DurableFatalError, DurableMaxedError, DurableProxyError, DurableRetryError, DurableSleepError, DurableTimeoutError, DurableWaitForAllError, DurableWaitForError, DuplicateJobError, ExecActivityError, GenerationalError, GetStateError, HotMeshConnectionError, InactiveJobError, LeaseExpiredError, MapDataError, RegisterTimeoutError, SetStateError, };
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SetStateError = exports.RegisterTimeoutError = exports.MapDataError = exports.LeaseExpiredError = exports.InactiveJobError = exports.GetStateError = exports.GenerationalError = exports.ExecActivityError = exports.DuplicateJobError = exports.DurableWaitForError = exports.DurableWaitForAllError = exports.DurableTimeoutError = exports.DurableSleepError = exports.DurableRetryError = exports.DurableProxyError = exports.DurableMaxedError = exports.DurableFatalError = exports.DurableContinueAsNewError = exports.DurableChildError = exports.CollationError = exports.classifyError = exports.ErrorCategory = void 0;
3
+ exports.SetStateError = exports.RegisterTimeoutError = exports.MapDataError = exports.LeaseExpiredError = exports.InactiveJobError = exports.HotMeshConnectionError = exports.GetStateError = exports.GenerationalError = exports.ExecActivityError = exports.DuplicateJobError = exports.DurableWaitForError = exports.DurableWaitForAllError = exports.DurableTimeoutError = exports.DurableSleepError = exports.DurableRetryError = exports.DurableProxyError = exports.DurableMaxedError = exports.DurableFatalError = exports.DurableContinueAsNewError = exports.DurableChildError = exports.CollationError = exports.isConnectionError = exports.classifyError = exports.ErrorCategory = void 0;
4
4
  const enums_1 = require("./enums");
5
5
  /**
6
6
  * Error classification for dispatcher logging.
@@ -13,6 +13,10 @@ const enums_1 = require("./enums");
13
13
  * Message is acked; job is marked failed.
14
14
  * COLLATION — duplicate delivery detected via GUID ledger.
15
15
  * Silent ack; no work needed.
16
+ * UNAVAILABLE — the HotMesh database connection is unavailable.
17
+ * The message is NOT acked and no response is published;
18
+ * it is redelivered once the connection returns, without
19
+ * spending the retry budget.
16
20
  */
17
21
  var ErrorCategory;
18
22
  (function (ErrorCategory) {
@@ -20,8 +24,12 @@ var ErrorCategory;
20
24
  ErrorCategory["RETRYABLE"] = "retryable";
21
25
  ErrorCategory["TERMINAL"] = "terminal";
22
26
  ErrorCategory["COLLATION"] = "collation";
27
+ ErrorCategory["UNAVAILABLE"] = "unavailable";
23
28
  })(ErrorCategory = exports.ErrorCategory || (exports.ErrorCategory = {}));
24
29
  function classifyError(error) {
30
+ if (error instanceof HotMeshConnectionError) {
31
+ return ErrorCategory.UNAVAILABLE;
32
+ }
25
33
  if (error instanceof LeaseExpiredError) {
26
34
  return ErrorCategory.FATAL;
27
35
  }
@@ -264,6 +272,79 @@ class LeaseExpiredError extends Error {
264
272
  }
265
273
  }
266
274
  exports.LeaseExpiredError = LeaseExpiredError;
275
+ /**
276
+ * Raised by a HotMesh PostgreSQL connection when the failure is the
277
+ * connection's, not the statement's: the session was lost, is
278
+ * reconnecting, or a transaction did not survive a reconnect. The
279
+ * native error, when there is one, is kept on `cause`.
280
+ */
281
+ class HotMeshConnectionError extends Error {
282
+ constructor(message, connectionId, cause) {
283
+ super(message);
284
+ this.code = 'HMSH_PG_UNAVAILABLE';
285
+ this.name = 'HotMeshConnectionError';
286
+ this.connectionId = connectionId;
287
+ this.cause = cause;
288
+ }
289
+ }
290
+ exports.HotMeshConnectionError = HotMeshConnectionError;
291
+ /** pg and Node messages that mean the connection, not the statement, failed. */
292
+ const CONNECTION_ERROR_MESSAGES = [
293
+ 'connection terminated',
294
+ 'not queryable',
295
+ 'timeout expired',
296
+ 'connection timeout',
297
+ 'server closed the connection',
298
+ 'terminating connection',
299
+ 'the database system is starting up',
300
+ 'the database system is shutting down',
301
+ 'the database system is in recovery mode',
302
+ ];
303
+ /** Node socket and DNS codes that mean the host could not be reached. */
304
+ const CONNECTION_ERROR_CODES = new Set([
305
+ 'ECONNRESET',
306
+ 'ECONNREFUSED',
307
+ 'ETIMEDOUT',
308
+ 'EPIPE',
309
+ 'EHOSTUNREACH',
310
+ 'ENETUNREACH',
311
+ 'ENOTFOUND',
312
+ 'EAI_AGAIN',
313
+ 'HMSH_PG_UNAVAILABLE',
314
+ ]);
315
+ /** SQLSTATEs outside class 08 that mean the server ended or refused the session. */
316
+ const CONNECTION_ERROR_SQLSTATES = new Set(['57P01', '57P02', '57P03']);
317
+ /**
318
+ * True when an error means the database connection is unavailable (lost,
319
+ * refused, timed out, shutting down), not that the statement failed.
320
+ * Walks `cause` so a wrapped native error is recognized.
321
+ */
322
+ function isConnectionError(error, depth = 0) {
323
+ if (!error || typeof error !== 'object' || depth > 4) {
324
+ return false;
325
+ }
326
+ if (error instanceof HotMeshConnectionError) {
327
+ return true;
328
+ }
329
+ const { code, message, cause } = error;
330
+ if (typeof code === 'string') {
331
+ if (CONNECTION_ERROR_CODES.has(code) ||
332
+ CONNECTION_ERROR_SQLSTATES.has(code)) {
333
+ return true;
334
+ }
335
+ if (/^08[0-9A-Z]{3}$/.test(code)) {
336
+ return true;
337
+ }
338
+ }
339
+ if (typeof message === 'string') {
340
+ const lower = message.toLowerCase();
341
+ if (CONNECTION_ERROR_MESSAGES.some((fragment) => lower.includes(fragment))) {
342
+ return true;
343
+ }
344
+ }
345
+ return cause ? isConnectionError(cause, depth + 1) : false;
346
+ }
347
+ exports.isConnectionError = isConnectionError;
267
348
  class CollationError extends Error {
268
349
  constructor(status, leg, stage, fault) {
269
350
  super('collation-error');
@@ -15,6 +15,14 @@ export declare function deterministicRandom(seed: number): number;
15
15
  export declare function guid(size?: number): string;
16
16
  /** Returns a standard RFC 4122 v4 UUID (e.g. for use as a DB primary key). */
17
17
  export declare function uuid(): string;
18
+ /**
19
+ * Let a best-effort async call run without awaiting it. A rejection is
20
+ * logged at `warn` under `label` and never becomes an unhandled
21
+ * rejection (which ends a Node process). Non-promise values are ignored.
22
+ */
23
+ export declare function detach(result: unknown, logger: {
24
+ warn: (message: string, context?: StringAnyType) => void;
25
+ } | undefined, label: string, context?: StringAnyType): void;
18
26
  export declare function sleepFor(ms: number): Promise<void>;
19
27
  export declare function sleepImmediate(): Promise<void>;
20
28
  export declare function XSleepFor(ms: number): {
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.arrayToHash = exports.isStreamMessage = exports.parseStreamMessage = exports.normalizeRetryPolicy = exports.s = exports.isValidCron = exports.restoreHierarchy = exports.getValueByPath = exports.getIndexedHash = exports.getSymVal = exports.getSymKey = exports.formatISODate = exports.getTimeSeries = exports.getSubscriptionTopic = exports.findSubscriptionForTrigger = exports.findTopKey = exports.matchesStatus = exports.matchesStatusCode = exports.polyfill = exports.identifyProvider = exports.XSleepFor = exports.sleepImmediate = exports.sleepFor = exports.uuid = exports.guid = exports.deterministicRandom = exports.deepCopy = exports.getSystemHealth = exports.hashOptions = void 0;
6
+ exports.arrayToHash = exports.isStreamMessage = exports.parseStreamMessage = exports.normalizeRetryPolicy = exports.s = exports.isValidCron = exports.restoreHierarchy = exports.getValueByPath = exports.getIndexedHash = exports.getSymVal = exports.getSymKey = exports.formatISODate = exports.getTimeSeries = exports.getSubscriptionTopic = exports.findSubscriptionForTrigger = exports.findTopKey = exports.matchesStatus = exports.matchesStatusCode = exports.polyfill = exports.identifyProvider = exports.XSleepFor = exports.sleepImmediate = exports.sleepFor = exports.detach = exports.uuid = exports.guid = exports.deterministicRandom = exports.deepCopy = exports.getSystemHealth = exports.hashOptions = void 0;
7
7
  const os_1 = __importDefault(require("os"));
8
8
  const crypto_1 = require("crypto");
9
9
  const cron_parser_1 = require("cron-parser");
@@ -52,6 +52,24 @@ function uuid() {
52
52
  return (0, crypto_1.randomUUID)();
53
53
  }
54
54
  exports.uuid = uuid;
55
+ /**
56
+ * Let a best-effort async call run without awaiting it. A rejection is
57
+ * logged at `warn` under `label` and never becomes an unhandled
58
+ * rejection (which ends a Node process). Non-promise values are ignored.
59
+ */
60
+ function detach(result, logger, label, context) {
61
+ if (result && typeof result.then === 'function') {
62
+ result.then(undefined, (error) => {
63
+ try {
64
+ logger?.warn(label, { ...context, error });
65
+ }
66
+ catch {
67
+ //a logger fault must not become the unhandled rejection
68
+ }
69
+ });
70
+ }
71
+ }
72
+ exports.detach = detach;
55
73
  async function sleepFor(ms) {
56
74
  return new Promise((resolve) => setTimeout(resolve, ms));
57
75
  }
@@ -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",
@@ -132,7 +132,9 @@ class Trigger extends activity_1.Activity {
132
132
  await txn2.exec();
133
133
  }
134
134
  //best-effort parent notification
135
- this.execAdjacentParent();
135
+ (0, utils_1.detach)(this.execAdjacentParent(), this.logger, 'trigger-exec-adjacent-parent-error', {
136
+ jid: this.context.metadata.jid,
137
+ });
136
138
  //═══ Step 3: Completion (if job immediately complete) ═══
137
139
  //NOTE: runJobCompletionTasks is non-transactional here because
138
140
  //the trigger runs inline within pub(). Subscribers register AFTER
@@ -0,0 +1,42 @@
1
+ import { ConnectionHealthEvent, ConnectionHealthSnapshot, ConnectionLostEvent, ConnectionRestoredEvent } from '../../types/provider';
2
+ type HealthListener<E extends ConnectionHealthEvent> = E extends 'lost' ? (event: ConnectionLostEvent) => unknown : (event: ConnectionRestoredEvent) => unknown;
3
+ /**
4
+ * Process-wide availability of the resilient PostgreSQL connections.
5
+ *
6
+ * Every connection HotMesh opens through a `pg.Client` class registers
7
+ * here. `state` is `down` while any registered connection is
8
+ * reconnecting; `downSince` is the earliest loss among them. Listener
9
+ * faults are logged and never reach the reconnect loop.
10
+ *
11
+ * ```typescript
12
+ * import { ConnectionHealth } from '@hotmeshio/hotmesh';
13
+ *
14
+ * ConnectionHealth.on('lost', (e) => log.warn('db lost', e));
15
+ * ConnectionHealth.on('restored', (e) => log.info('db back', e));
16
+ * ConnectionHealth.snapshot(); // { state: 'up', total: 3, down: 0 }
17
+ * ```
18
+ */
19
+ declare class ConnectionHealthService {
20
+ private readonly emitter;
21
+ private readonly connections;
22
+ private readonly lost;
23
+ private logger;
24
+ constructor();
25
+ on<E extends ConnectionHealthEvent>(event: E, listener: HealthListener<E>): this;
26
+ once<E extends ConnectionHealthEvent>(event: E, listener: HealthListener<E>): this;
27
+ off<E extends ConnectionHealthEvent>(event: E, listener: HealthListener<E>): this;
28
+ snapshot(): ConnectionHealthSnapshot;
29
+ /** @private */
30
+ register(connectionId: string): void;
31
+ /** @private */
32
+ unregister(connectionId: string): void;
33
+ /** @private */
34
+ markLost(event: ConnectionLostEvent): void;
35
+ /** @private */
36
+ markRestored(event: ConnectionRestoredEvent): void;
37
+ /** @private test isolation: forget every registered connection and listener. */
38
+ reset(): void;
39
+ private dispatch;
40
+ }
41
+ declare const ConnectionHealth: ConnectionHealthService;
42
+ export { ConnectionHealth, ConnectionHealthService };
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConnectionHealthService = exports.ConnectionHealth = void 0;
4
+ const events_1 = require("events");
5
+ const logger_1 = require("../logger");
6
+ /**
7
+ * Process-wide availability of the resilient PostgreSQL connections.
8
+ *
9
+ * Every connection HotMesh opens through a `pg.Client` class registers
10
+ * here. `state` is `down` while any registered connection is
11
+ * reconnecting; `downSince` is the earliest loss among them. Listener
12
+ * faults are logged and never reach the reconnect loop.
13
+ *
14
+ * ```typescript
15
+ * import { ConnectionHealth } from '@hotmeshio/hotmesh';
16
+ *
17
+ * ConnectionHealth.on('lost', (e) => log.warn('db lost', e));
18
+ * ConnectionHealth.on('restored', (e) => log.info('db back', e));
19
+ * ConnectionHealth.snapshot(); // { state: 'up', total: 3, down: 0 }
20
+ * ```
21
+ */
22
+ class ConnectionHealthService {
23
+ constructor() {
24
+ this.emitter = new events_1.EventEmitter();
25
+ this.connections = new Set();
26
+ this.lost = new Map();
27
+ this.logger = new logger_1.LoggerService('hotmesh', 'connection-health');
28
+ this.emitter.setMaxListeners(0);
29
+ }
30
+ on(event, listener) {
31
+ this.emitter.on(event, listener);
32
+ return this;
33
+ }
34
+ once(event, listener) {
35
+ this.emitter.once(event, listener);
36
+ return this;
37
+ }
38
+ off(event, listener) {
39
+ this.emitter.off(event, listener);
40
+ return this;
41
+ }
42
+ snapshot() {
43
+ const down = this.lost.size;
44
+ const snapshot = {
45
+ state: down > 0 ? 'down' : 'up',
46
+ total: this.connections.size,
47
+ down,
48
+ };
49
+ if (down > 0) {
50
+ snapshot.downSince = Math.min(...this.lost.values());
51
+ }
52
+ return snapshot;
53
+ }
54
+ /** @private */
55
+ register(connectionId) {
56
+ this.connections.add(connectionId);
57
+ }
58
+ /** @private */
59
+ unregister(connectionId) {
60
+ this.connections.delete(connectionId);
61
+ this.lost.delete(connectionId);
62
+ }
63
+ /** @private */
64
+ markLost(event) {
65
+ this.lost.set(event.connectionId, event.at);
66
+ this.dispatch('lost', event);
67
+ }
68
+ /** @private */
69
+ markRestored(event) {
70
+ this.lost.delete(event.connectionId);
71
+ this.dispatch('restored', event);
72
+ }
73
+ /** @private test isolation: forget every registered connection and listener. */
74
+ reset() {
75
+ this.connections.clear();
76
+ this.lost.clear();
77
+ this.emitter.removeAllListeners();
78
+ }
79
+ dispatch(event, payload) {
80
+ //raw listeners keep once() semantics: the wrapper removes itself when invoked
81
+ for (const listener of this.emitter.rawListeners(event)) {
82
+ try {
83
+ const result = listener(payload);
84
+ if (result &&
85
+ typeof result.catch === 'function') {
86
+ result.catch((error) => this.logger.error('connection-health-listener-error', {
87
+ event,
88
+ error,
89
+ }));
90
+ }
91
+ }
92
+ catch (error) {
93
+ this.logger.error('connection-health-listener-error', { event, error });
94
+ }
95
+ }
96
+ }
97
+ }
98
+ exports.ConnectionHealthService = ConnectionHealthService;
99
+ const ConnectionHealth = new ConnectionHealthService();
100
+ exports.ConnectionHealth = ConnectionHealth;
@@ -34,8 +34,9 @@ class AbstractConnection {
34
34
  }
35
35
  const instance = new this();
36
36
  const opts = options ? { ...options } : { ...instance.defaultOptions };
37
- instance.connection = await instance.createConnection(client, opts, config);
37
+ //the id is known to createConnection so connection logs and health events carry it
38
38
  instance.id = id;
39
+ instance.connection = await instance.createConnection(client, opts, config);
39
40
  AbstractConnection.instances.set(id, instance);
40
41
  return instance;
41
42
  }