@hotmeshio/hotmesh 0.22.1 → 0.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,262 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EscalationClientService = void 0;
4
+ const enums_1 = require("../../modules/enums");
5
+ const utils_1 = require("../../modules/utils");
6
+ const hotmesh_1 = require("../hotmesh");
7
+ const types_1 = require("../../types");
8
+ const factory_1 = require("../durable/schemas/factory");
9
+ /**
10
+ * Standalone client for the `public.hmsh_escalations` signal-pause surface.
11
+ *
12
+ * Requires NO dependency on `services/durable/`. Any HotMesh consumer — AI
13
+ * agent, YAML DAG worker, REST API — can interact with the escalation queue
14
+ * directly with just a Postgres connection.
15
+ *
16
+ * Signal delivery (for `resolve()` / `resolveByMetadata()`) uses HotMesh's
17
+ * `engine.signal()` internally. The engine is initialised lazily on first use
18
+ * and cached for the lifetime of the process.
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * import { Escalations } from '@hotmeshio/hotmesh';
23
+ * import { Client as Postgres } from 'pg';
24
+ *
25
+ * const client = new Escalations.Client({
26
+ * connection: {
27
+ * class: Postgres,
28
+ * options: { connectionString: 'postgresql://usr:pwd@localhost:5432/db' },
29
+ * },
30
+ * });
31
+ *
32
+ * // Claim the next available approval for the 'manager' role
33
+ * const result = await client.claimByMetadata({
34
+ * key: 'orderId', value: 'order-123',
35
+ * assignee: 'alice@company.com',
36
+ * roles: ['manager'],
37
+ * });
38
+ *
39
+ * if (result.ok) {
40
+ * await client.resolve({ id: result.entry.id, resolverPayload: { approved: true } });
41
+ * }
42
+ * ```
43
+ */
44
+ class EscalationClientService {
45
+ constructor(config = {}) {
46
+ if (config.getHotMeshClient) {
47
+ // Reuse a caller-supplied engine factory (e.g. Durable.Client) — no extra connections.
48
+ this._engine = config.getHotMeshClient;
49
+ }
50
+ else if (config.connection) {
51
+ this._connection = config.connection;
52
+ this._engine = this._makeEngineFactory(config.connection);
53
+ }
54
+ else {
55
+ throw new Error('EscalationClient requires either `connection` or `getHotMeshClient`');
56
+ }
57
+ }
58
+ _makeEngineFactory(connection) {
59
+ return async (topic, namespace) => {
60
+ const optionsHash = this._hashConnection(connection);
61
+ const targetNS = namespace ?? factory_1.APP_ID;
62
+ const key = `esc:${optionsHash}.${targetNS}`;
63
+ if (EscalationClientService.instances.has(key)) {
64
+ return await EscalationClientService.instances.get(key);
65
+ }
66
+ const pending = hotmesh_1.HotMesh.init({
67
+ appId: targetNS,
68
+ taskQueue: topic ?? undefined,
69
+ logLevel: enums_1.HMSH_LOGLEVEL,
70
+ engine: { connection },
71
+ });
72
+ EscalationClientService.instances.set(key, pending);
73
+ return await pending;
74
+ };
75
+ }
76
+ _hashConnection(connection) {
77
+ if ('options' in connection) {
78
+ return (0, utils_1.hashOptions)(connection.options);
79
+ }
80
+ const parts = [];
81
+ for (const p in connection) {
82
+ if (connection[p]?.options) {
83
+ parts.push((0, utils_1.hashOptions)(connection[p].options));
84
+ }
85
+ }
86
+ return parts.join('');
87
+ }
88
+ // ─── Signal delivery ───────────────────────────────────────────────────────
89
+ async _deliverEscalationSignal(ns, topic, signalPayload) {
90
+ if (topic) {
91
+ try {
92
+ const tc = await this._engine(topic, ns);
93
+ await tc.engine.signal(topic, signalPayload, types_1.StreamStatus.SUCCESS, 200);
94
+ return true;
95
+ }
96
+ catch { /* topic not currently registered — fall through */ }
97
+ }
98
+ let delivered = false;
99
+ try {
100
+ const sc = await this._engine(`${ns}.wfs.signal`, ns);
101
+ await sc.engine.signal(`${ns}.wfs.signal`, signalPayload, types_1.StreamStatus.SUCCESS, 200);
102
+ delivered = true;
103
+ }
104
+ catch { }
105
+ try {
106
+ const wc = await this._engine(`${ns}.wfs.wait`, ns);
107
+ await wc.engine.signal(`${ns}.wfs.wait`, signalPayload, types_1.StreamStatus.SUCCESS, 200);
108
+ delivered = true;
109
+ }
110
+ catch { }
111
+ return delivered;
112
+ }
113
+ // ─── Public API ─────────────────────────────────────────────────────────────
114
+ /**
115
+ * Returns all escalation rows matching the given filters. Each row includes
116
+ * a computed `available` field (true = claimable). Supports `sortBy`,
117
+ * `sortOrder`, and multi-role `roles[]` filter.
118
+ */
119
+ async list(params) {
120
+ const hm = await this._engine(null, params?.namespace);
121
+ return hm.engine.store.listEscalations(params ?? {});
122
+ }
123
+ /**
124
+ * Returns the count of escalation rows matching the given filters.
125
+ * Uses the same filter parameters as `list()`.
126
+ */
127
+ async count(params) {
128
+ const hm = await this._engine(null, params?.namespace);
129
+ return hm.engine.store.countEscalations(params ?? {});
130
+ }
131
+ /** Returns a single escalation row by UUID. Returns `null` if not found. */
132
+ async get(id, namespace) {
133
+ const hm = await this._engine(null, namespace);
134
+ return hm.engine.store.getEscalation(id, namespace);
135
+ }
136
+ /** Looks up an escalation by `signal_key` — the value passed to `condition()`. */
137
+ async getBySignalKey(signalKey, namespace) {
138
+ const hm = await this._engine(null, namespace);
139
+ return hm.engine.store.getEscalationBySignalKey(signalKey, namespace);
140
+ }
141
+ /**
142
+ * Creates a standalone escalation row with `signal_key = null`.
143
+ * Useful for external task tracking that doesn't need to resume a workflow.
144
+ */
145
+ async create(params) {
146
+ const hm = await this._engine(null, params.namespace);
147
+ return hm.engine.store.createEscalation(params);
148
+ }
149
+ /**
150
+ * Patches an existing escalation row. `metadata` is merged, not replaced.
151
+ * Signal routing fields can be enriched after creation.
152
+ */
153
+ async update(params) {
154
+ const hm = await this._engine(null, params.namespace);
155
+ return hm.engine.store.updateEscalation(params);
156
+ }
157
+ /** Appends milestone entries to the escalation's audit trail. */
158
+ async appendMilestones(params) {
159
+ const hm = await this._engine(null, params.namespace);
160
+ return hm.engine.store.appendEscalationMilestones(params);
161
+ }
162
+ /**
163
+ * Atomically claims an escalation by UUID. Implicit model: `status` stays
164
+ * `'pending'`; claim is expressed via `assigned_to` + `assigned_until`.
165
+ */
166
+ async claim(params) {
167
+ const hm = await this._engine(null, params.namespace);
168
+ return hm.engine.store.claimEscalation(params);
169
+ }
170
+ /**
171
+ * Atomically claims the highest-priority pending escalation whose `metadata`
172
+ * contains the given key/value. Returns `isExtension: true` when the same
173
+ * assignee re-claims a row they already hold (extends the expiry).
174
+ */
175
+ async claimByMetadata(params) {
176
+ const hm = await this._engine(null, params.namespace);
177
+ return hm.engine.store.claimEscalationByMetadata(params);
178
+ }
179
+ /** Releases a claimed escalation, returning it to available status. */
180
+ async release(params) {
181
+ const hm = await this._engine(null, params.namespace);
182
+ return hm.engine.store.releaseEscalation(params);
183
+ }
184
+ /**
185
+ * Reassigns the escalation to a different role, clearing any current claim
186
+ * and resetting status to `'pending'`.
187
+ */
188
+ async escalateToRole(params) {
189
+ const hm = await this._engine(null, params.namespace);
190
+ return hm.engine.store.escalateEscalationToRole(params);
191
+ }
192
+ /**
193
+ * Cancels a pending escalation without delivering a signal. Terminal rows
194
+ * return `already-terminal`.
195
+ */
196
+ async cancel(id, namespace) {
197
+ const hm = await this._engine(null, namespace);
198
+ return hm.engine.store.cancelEscalation(id, namespace);
199
+ }
200
+ /**
201
+ * Signal-first resolve: marks the escalation resolved **and** delivers the
202
+ * signal to the waiting workflow in a single held transaction. If signal
203
+ * delivery fails, the transaction rolls back — `committed: false`.
204
+ */
205
+ async resolve(params, namespace) {
206
+ const ns = (params.namespace ?? namespace) ?? factory_1.APP_ID;
207
+ const hm = await this._engine(null, ns);
208
+ const dbResult = await hm.engine.store.resolveEscalation({ id: params.id, resolverPayload: params.resolverPayload });
209
+ if (!dbResult.ok)
210
+ return dbResult;
211
+ if (dbResult.signalKey) {
212
+ await this._deliverEscalationSignal(ns, dbResult.topic, {
213
+ id: dbResult.signalKey,
214
+ data: params.resolverPayload ?? {},
215
+ });
216
+ }
217
+ return { ok: true };
218
+ }
219
+ /**
220
+ * Resolves the highest-priority matching escalation by metadata filter,
221
+ * then delivers its signal.
222
+ */
223
+ async resolveByMetadata(params, namespace) {
224
+ const ns = (params.namespace ?? namespace) ?? factory_1.APP_ID;
225
+ const hm = await this._engine(null, ns);
226
+ const dbResult = await hm.engine.store.resolveEscalationByMetadata({ key: params.key, value: params.value, resolverPayload: params.resolverPayload, roles: params.roles });
227
+ if (!dbResult.ok)
228
+ return dbResult;
229
+ if (dbResult.signalKey) {
230
+ await this._deliverEscalationSignal(ns, dbResult.topic, {
231
+ id: dbResult.signalKey,
232
+ data: params.resolverPayload ?? {},
233
+ });
234
+ }
235
+ return { ok: true };
236
+ }
237
+ /**
238
+ * Full-fidelity migration: inserts an escalation row preserving the original
239
+ * UUID and lifecycle state. Returns `null` on duplicate (idempotent).
240
+ */
241
+ async migrate(params, namespace) {
242
+ const ns = (params.namespace ?? namespace) ?? factory_1.APP_ID;
243
+ const hm = await this._engine(null, ns);
244
+ return hm.engine.store.createEscalationForMigration(params);
245
+ }
246
+ /**
247
+ * No-op in the implicit claim model — availability is computed at query time
248
+ * from `assigned_until`. Kept for API compatibility.
249
+ */
250
+ async releaseExpired(namespace) {
251
+ const hm = await this._engine(null, namespace);
252
+ return hm.engine.store.releaseExpiredEscalations(namespace);
253
+ }
254
+ static async shutdown() {
255
+ for (const [_, instance] of EscalationClientService.instances) {
256
+ (await instance).stop();
257
+ }
258
+ EscalationClientService.instances.clear();
259
+ }
260
+ }
261
+ EscalationClientService.instances = new Map();
262
+ exports.EscalationClientService = EscalationClientService;
@@ -0,0 +1,66 @@
1
+ import { guid, uuid } from '../../modules/utils';
2
+ import { EscalationClientService } from './client';
3
+ /**
4
+ * Escalation queue — the canonical signal-pause surface for HotMesh workflows.
5
+ *
6
+ * `public.hmsh_escalations` is a global Postgres table written by both the
7
+ * YAML DAG hook activity and `Durable.workflow.condition()`. Any consumer
8
+ * can interact with the queue using just a Postgres connection — no Durable
9
+ * dependency required.
10
+ *
11
+ * ## Quick Start
12
+ *
13
+ * ```typescript
14
+ * import { Escalations } from '@hotmeshio/hotmesh';
15
+ * import { Client as Postgres } from 'pg';
16
+ *
17
+ * const client = new Escalations.Client({
18
+ * connection: {
19
+ * class: Postgres,
20
+ * options: { connectionString: 'postgresql://usr:pwd@localhost:5432/db' },
21
+ * },
22
+ * });
23
+ *
24
+ * // List all available approvals for the 'manager' role
25
+ * const pending = await client.list({ role: 'manager', available: true });
26
+ *
27
+ * // Claim one atomically
28
+ * const result = await client.claimByMetadata({
29
+ * key: 'orderId', value: 'order-123',
30
+ * assignee: 'alice@company.com',
31
+ * roles: ['manager', 'senior-manager'],
32
+ * });
33
+ *
34
+ * // Resolve and resume the waiting workflow in one round-trip
35
+ * if (result.ok) {
36
+ * await client.resolve({ id: result.entry.id, resolverPayload: { approved: true } });
37
+ * }
38
+ * ```
39
+ */
40
+ declare class EscalationsClass {
41
+ /** @private */
42
+ constructor();
43
+ /**
44
+ * Creates an escalation queue client. Pass a `connection` for standalone
45
+ * use, or inject a `getHotMeshClient` function to share an existing
46
+ * engine pool (e.g. from a `Durable.Client`).
47
+ */
48
+ static Client: typeof EscalationClientService;
49
+ /**
50
+ * Generate a compact HotMesh identifier (not RFC 4122).
51
+ * Use `Escalations.uuid()` for DB primary keys.
52
+ */
53
+ static guid: typeof guid;
54
+ /**
55
+ * Generate a standard RFC 4122 v4 UUID — required for the `id` field
56
+ * when calling `client.migrate()` or any direct UUID column insert.
57
+ */
58
+ static uuid: typeof uuid;
59
+ /**
60
+ * Gracefully stop all escalation engine instances.
61
+ * Call from your process signal handlers (`SIGTERM`, `SIGINT`).
62
+ */
63
+ static shutdown(): Promise<void>;
64
+ }
65
+ export { EscalationsClass as Escalations };
66
+ export { EscalationClientService };
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EscalationClientService = exports.Escalations = void 0;
4
+ const utils_1 = require("../../modules/utils");
5
+ const client_1 = require("./client");
6
+ Object.defineProperty(exports, "EscalationClientService", { enumerable: true, get: function () { return client_1.EscalationClientService; } });
7
+ /**
8
+ * Escalation queue — the canonical signal-pause surface for HotMesh workflows.
9
+ *
10
+ * `public.hmsh_escalations` is a global Postgres table written by both the
11
+ * YAML DAG hook activity and `Durable.workflow.condition()`. Any consumer
12
+ * can interact with the queue using just a Postgres connection — no Durable
13
+ * dependency required.
14
+ *
15
+ * ## Quick Start
16
+ *
17
+ * ```typescript
18
+ * import { Escalations } from '@hotmeshio/hotmesh';
19
+ * import { Client as Postgres } from 'pg';
20
+ *
21
+ * const client = new Escalations.Client({
22
+ * connection: {
23
+ * class: Postgres,
24
+ * options: { connectionString: 'postgresql://usr:pwd@localhost:5432/db' },
25
+ * },
26
+ * });
27
+ *
28
+ * // List all available approvals for the 'manager' role
29
+ * const pending = await client.list({ role: 'manager', available: true });
30
+ *
31
+ * // Claim one atomically
32
+ * const result = await client.claimByMetadata({
33
+ * key: 'orderId', value: 'order-123',
34
+ * assignee: 'alice@company.com',
35
+ * roles: ['manager', 'senior-manager'],
36
+ * });
37
+ *
38
+ * // Resolve and resume the waiting workflow in one round-trip
39
+ * if (result.ok) {
40
+ * await client.resolve({ id: result.entry.id, resolverPayload: { approved: true } });
41
+ * }
42
+ * ```
43
+ */
44
+ class EscalationsClass {
45
+ /** @private */
46
+ constructor() { }
47
+ /**
48
+ * Gracefully stop all escalation engine instances.
49
+ * Call from your process signal handlers (`SIGTERM`, `SIGINT`).
50
+ */
51
+ static async shutdown() {
52
+ await client_1.EscalationClientService.shutdown();
53
+ }
54
+ }
55
+ exports.Escalations = EscalationsClass;
56
+ /**
57
+ * Creates an escalation queue client. Pass a `connection` for standalone
58
+ * use, or inject a `getHotMeshClient` function to share an existing
59
+ * engine pool (e.g. from a `Durable.Client`).
60
+ */
61
+ EscalationsClass.Client = client_1.EscalationClientService;
62
+ /**
63
+ * Generate a compact HotMesh identifier (not RFC 4122).
64
+ * Use `Escalations.uuid()` for DB primary keys.
65
+ */
66
+ EscalationsClass.guid = utils_1.guid;
67
+ /**
68
+ * Generate a standard RFC 4122 v4 UUID — required for the `id` field
69
+ * when calling `client.migrate()` or any direct UUID column insert.
70
+ */
71
+ EscalationsClass.uuid = utils_1.uuid;
@@ -247,16 +247,17 @@ declare class PostgresStoreService extends StoreService<ProviderClient, Provider
247
247
  getEscalation(id: string, namespace?: string): Promise<import('../../../../types/hmsh_escalations').EscalationEntry | null>;
248
248
  getEscalationBySignalKey(signalKey: string, namespace?: string): Promise<import('../../../../types/hmsh_escalations').EscalationEntry | null>;
249
249
  listEscalations(params?: import('../../../../types/hmsh_escalations').ListEscalationsParams): Promise<import('../../../../types/hmsh_escalations').EscalationEntry[]>;
250
+ countEscalations(params?: import('../../../../types/hmsh_escalations').ListEscalationsParams): Promise<number>;
250
251
  claimEscalation(params: import('../../../../types/hmsh_escalations').ClaimEscalationParams): Promise<import('../../../../types/hmsh_escalations').ClaimEscalationResult>;
251
252
  claimEscalationByMetadata(params: import('../../../../types/hmsh_escalations').ClaimByMetadataParams): Promise<import('../../../../types/hmsh_escalations').ClaimByMetadataResult>;
252
253
  releaseEscalation(params: import('../../../../types/hmsh_escalations').ReleaseEscalationParams): Promise<import('../../../../types/hmsh_escalations').ReleaseEscalationResult>;
253
254
  resolveEscalation(params: import('../../../../types/hmsh_escalations').ResolveEscalationParams): Promise<import('../../../../types/hmsh_escalations').ResolveEscalationResult & {
254
- signalKey?: string;
255
- topic?: string;
255
+ signalKey?: string | null;
256
+ topic?: string | null;
256
257
  }>;
257
258
  resolveEscalationByMetadata(params: import('../../../../types/hmsh_escalations').ResolveByMetadataParams): Promise<import('../../../../types/hmsh_escalations').ResolveEscalationResult & {
258
- signalKey?: string;
259
- topic?: string;
259
+ signalKey?: string | null;
260
+ topic?: string | null;
260
261
  }>;
261
262
  /**
262
263
  * Queues the escalation UPDATE into an existing transaction without executing it.
@@ -278,6 +279,6 @@ declare class PostgresStoreService extends StoreService<ProviderClient, Provider
278
279
  escalateEscalationToRole(params: import('../../../../types/hmsh_escalations').EscalateToRoleParams): Promise<import('../../../../types/hmsh_escalations').EscalationEntry | null>;
279
280
  updateEscalation(params: import('../../../../types/hmsh_escalations').UpdateEscalationParams): Promise<import('../../../../types/hmsh_escalations').EscalationEntry | null>;
280
281
  appendEscalationMilestones(params: import('../../../../types/hmsh_escalations').AppendMilestonesParams): Promise<import('../../../../types/hmsh_escalations').EscalationEntry | null>;
281
- releaseExpiredEscalations(namespace?: string): Promise<number>;
282
+ releaseExpiredEscalations(_namespace?: string): Promise<number>;
282
283
  }
283
284
  export { PostgresStoreService };