@dudousxd/nestjs-durable 0.53.0 → 0.55.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.
@@ -0,0 +1,741 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/migrate-from-nestjs-workflows/index.ts
5
+ import { RunGateway as RunGateway2, STATE_STORE_CANONICAL as STATE_STORE_CANONICAL2, WorkflowEngine as WorkflowEngine2, workflowName } from "@dudousxd/nestjs-durable-core";
6
+ import { WorkflowsRunGateway, toWorkflowRun } from "@dudousxd/nestjs-durable-workflows-gateway";
7
+ import { Inject as Inject2, Injectable as Injectable2, Module } from "@nestjs/common";
8
+ import { WorkflowClient, WorkflowEvents } from "@nestjs/workflows";
9
+
10
+ // src/store-run-gateway.ts
11
+ import { LIFECYCLE_REGISTRY_WORKFLOW, STATE_STORE_CANONICAL, SUMMARY_CHILD_LIMIT, WorkflowEngine, aggregatesCheckpoints, childIdsOf, etagMatches, extendEtag, fanPageEtag, indexWaitersByRun, lifecycleDeliveriesOf, lifecycleKindOf, lifecycleSourceOf, lifecycleTraceparentOf, listSignalWaitersOfRuns, mergeRunFacetRows, pageFan, pageFanFromStore, readRunsByIds, resolveRunWaiting, runDetailEtag, runWaitPrefix, runWaitTargetOf, summarizeRunFromStore, summarizeTimeline, traceIdOfTraceparent } from "@dudousxd/nestjs-durable-core";
12
+ import { Inject, Injectable } from "@nestjs/common";
13
+ function _ts_decorate(decorators, target, key, desc) {
14
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
15
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
16
+ r = Reflect.decorate(decorators, target, key, desc);
17
+ } else {
18
+ for (var i = decorators.length - 1; i >= 0; i--) {
19
+ if (d = decorators[i]) {
20
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
21
+ }
22
+ }
23
+ }
24
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
25
+ }
26
+ __name(_ts_decorate, "_ts_decorate");
27
+ function _ts_metadata(metadataKey, metadataValue) {
28
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
29
+ return Reflect.metadata(metadataKey, metadataValue);
30
+ }
31
+ }
32
+ __name(_ts_metadata, "_ts_metadata");
33
+ function _ts_param(paramIndex, decorator) {
34
+ return function(target, key) {
35
+ decorator(target, key, paramIndex);
36
+ };
37
+ }
38
+ __name(_ts_param, "_ts_param");
39
+ function detailExtras(links) {
40
+ const { lifecycleSubscribers, lifecycleDeliveries, waitsFor, awaitedBy, triggeredBy } = links;
41
+ if (!lifecycleSubscribers && !lifecycleDeliveries && !waitsFor && !awaitedBy && !triggeredBy) {
42
+ return void 0;
43
+ }
44
+ return {
45
+ lifecycleSubscribers,
46
+ lifecycleDeliveries,
47
+ waitsFor,
48
+ awaitedBy,
49
+ triggeredBy
50
+ };
51
+ }
52
+ __name(detailExtras, "detailExtras");
53
+ function withoutRegistry(query) {
54
+ if (query.workflow === LIFECYCLE_REGISTRY_WORKFLOW || query.workflows?.includes(LIFECYCLE_REGISTRY_WORKFLOW)) {
55
+ return query;
56
+ }
57
+ return {
58
+ ...query,
59
+ excludeWorkflows: [
60
+ ...query.excludeWorkflows ?? [],
61
+ LIFECYCLE_REGISTRY_WORKFLOW
62
+ ]
63
+ };
64
+ }
65
+ __name(withoutRegistry, "withoutRegistry");
66
+ var StoreRunGateway = class {
67
+ static {
68
+ __name(this, "StoreRunGateway");
69
+ }
70
+ store;
71
+ engine;
72
+ constructor(store, engine) {
73
+ this.store = store;
74
+ this.engine = engine;
75
+ }
76
+ topology() {
77
+ return {
78
+ role: "control-plane"
79
+ };
80
+ }
81
+ async getRunDetail(runId, options) {
82
+ const run = await this.store.getRun(runId);
83
+ if (!run) return null;
84
+ const links = await this.lifecycleLinks(run);
85
+ const over = options?.summarizeFansOver;
86
+ if (over === void 0) {
87
+ const [timeline2, children] = await Promise.all([
88
+ this.store.listCheckpoints(runId),
89
+ this.engine.getRunChildren(runId)
90
+ ]);
91
+ return {
92
+ run,
93
+ timeline: timeline2,
94
+ children,
95
+ ...links
96
+ };
97
+ }
98
+ if (aggregatesCheckpoints(this.store)) {
99
+ const stats = await this.store.checkpointStats(runId);
100
+ const etag = extendEtag(runDetailEtag(run, stats, over), detailExtras(links));
101
+ if (etagMatches(options?.ifNoneMatch, etag)) {
102
+ return {
103
+ run,
104
+ timeline: [],
105
+ children: [],
106
+ notModified: true,
107
+ etag
108
+ };
109
+ }
110
+ return {
111
+ run,
112
+ ...await summarizeRunFromStore(this.store, runId, over, stats),
113
+ etag,
114
+ ...links
115
+ };
116
+ }
117
+ const full = await this.store.listCheckpoints(runId);
118
+ const { timeline, fans } = summarizeTimeline(full, over);
119
+ const ids = childIdsOf(full);
120
+ return {
121
+ run,
122
+ timeline,
123
+ children: ids.slice(0, SUMMARY_CHILD_LIMIT),
124
+ fans,
125
+ childCount: ids.length,
126
+ ...links
127
+ };
128
+ }
129
+ /**
130
+ * What a run detail reads beyond the run row and its checkpoints: what this run's settling
131
+ * started, the subscribers its lifecycle event goes to (of its namespace) and where it stands for
132
+ * each, what started it, its workflow's lifecycle links, and the `ctx.waitForRun` waits on either
133
+ * side of it with the other run's status. A few reads per detail: the run's own waiters while it
134
+ * is suspended, the waiters on it (one prefix read), and one batched read of every linked run.
135
+ */
136
+ async lifecycleLinks(run) {
137
+ const triggered = await this.engine.triggeredRuns(run);
138
+ const source = lifecycleSourceOf(run);
139
+ const kind = lifecycleKindOf(run.status);
140
+ const subscribers = kind ? await this.engine.lifecycleSubscribers(run.workflow, kind, run.namespace || "default") : [];
141
+ const workflowLifecycle = await this.engine.workflowLifecycle(run.workflow);
142
+ const linked = workflowLifecycle.startsOnSettle.length > 0 || workflowLifecycle.startedBy.length > 0;
143
+ const deliveries = kind ? lifecycleDeliveriesOf(run, {
144
+ subscribers,
145
+ live: new Set(subscribers),
146
+ coalesced: this.engine.coalescedSubscribers(run)
147
+ }) : [];
148
+ const [own, onIt] = await Promise.all([
149
+ run.status === "suspended" ? listSignalWaitersOfRuns(this.store, [
150
+ run.id
151
+ ]) : [],
152
+ run.workflow.startsWith("__") ? [] : this.store.listSignalWaiters(runWaitPrefix(run.id))
153
+ ]);
154
+ const waitsFor = own.flatMap((w) => {
155
+ const target = runWaitTargetOf(w);
156
+ return target !== void 0 ? [
157
+ {
158
+ runId: target,
159
+ seq: w.seq
160
+ }
161
+ ] : [];
162
+ });
163
+ const awaitedBy = onIt.filter((w) => runWaitTargetOf(w) === run.id).map((w) => ({
164
+ runId: w.runId,
165
+ seq: w.seq
166
+ }));
167
+ const started = deliveries.flatMap((d) => d.state === "started" && d.runId !== void 0 ? [
168
+ d.runId
169
+ ] : []);
170
+ const { runs } = await readRunsByIds(this.store, [
171
+ ...source ? [
172
+ source.runId
173
+ ] : [],
174
+ ...started,
175
+ ...waitsFor.map((l) => l.runId),
176
+ ...awaitedBy.map((l) => l.runId)
177
+ ]);
178
+ const withRun = /* @__PURE__ */ __name((link) => {
179
+ const other = link.runId !== void 0 ? runs.get(link.runId) : void 0;
180
+ return other ? {
181
+ ...link,
182
+ status: other.status,
183
+ namespace: other.namespace
184
+ } : link;
185
+ }, "withRun");
186
+ const sourceRun = source ? runs.get(source.runId) : void 0;
187
+ const traceId = traceIdOfTraceparent(lifecycleTraceparentOf(sourceRun?.tags));
188
+ return {
189
+ ...triggered.length > 0 ? {
190
+ triggered
191
+ } : {},
192
+ ...source ? {
193
+ triggeredBy: {
194
+ ...source,
195
+ ...sourceRun ? {
196
+ status: sourceRun.status,
197
+ namespace: sourceRun.namespace
198
+ } : {},
199
+ ...traceId ? {
200
+ traceId
201
+ } : {}
202
+ }
203
+ } : {},
204
+ ...subscribers.length > 0 ? {
205
+ lifecycleSubscribers: subscribers
206
+ } : {},
207
+ ...linked ? {
208
+ workflowLifecycle
209
+ } : {},
210
+ ...deliveries.length > 0 ? {
211
+ lifecycleDeliveries: deliveries.map((d) => d.state === "started" ? withRun(d) : d)
212
+ } : {},
213
+ ...waitsFor.length > 0 ? {
214
+ waitsFor: waitsFor.map(withRun)
215
+ } : {},
216
+ ...awaitedBy.length > 0 ? {
217
+ awaitedBy: awaitedBy.map(withRun)
218
+ } : {}
219
+ };
220
+ }
221
+ workflowLifecycle(workflow, opts) {
222
+ return this.engine.workflowLifecycle(workflow, opts);
223
+ }
224
+ lifecycleSubscribers(workflow, kind, namespace) {
225
+ return this.engine.lifecycleSubscribers(workflow, kind, namespace);
226
+ }
227
+ getRun(runId) {
228
+ return this.store.getRun(runId);
229
+ }
230
+ async getFanMembers(runId, group, query) {
231
+ if (!await this.store.getRun(runId)) return null;
232
+ if (aggregatesCheckpoints(this.store)) {
233
+ const stats = await this.store.checkpointStats(runId, {
234
+ group
235
+ });
236
+ const etag = fanPageEtag(group, stats, query);
237
+ if (etagMatches(query.ifNoneMatch, etag)) {
238
+ return {
239
+ items: [],
240
+ total: 0,
241
+ notModified: true,
242
+ etag
243
+ };
244
+ }
245
+ return {
246
+ ...await pageFanFromStore(this.store, runId, group, query, stats),
247
+ etag
248
+ };
249
+ }
250
+ return pageFan(await this.store.listCheckpoints(runId), group, query);
251
+ }
252
+ async listRuns(query) {
253
+ const runs = await this.store.listRuns(withoutRegistry(query));
254
+ const waiterByRun = indexWaitersByRun(await listSignalWaitersOfRuns(this.store, runs.filter((run) => run.status === "suspended").map((run) => run.id)));
255
+ return runs.map((run) => {
256
+ const waiting = resolveRunWaiting(run, waiterByRun);
257
+ return waiting ? {
258
+ ...run,
259
+ waiting
260
+ } : run;
261
+ });
262
+ }
263
+ /**
264
+ * The `(status, origin)` counts behind a console's chips, straight off the store's aggregate. The
265
+ * console needs this precisely BECAUSE its list is paginated: the page bounds what is rendered,
266
+ * these counts stay whole-set exact. A store with no aggregate falls back to counting a full
267
+ * listing — correct, but the unbounded read this exists to avoid, so it is the last resort.
268
+ */
269
+ async runFacets(query) {
270
+ const scoped = withoutRegistry(query);
271
+ if (this.store.runFacets) return this.store.runFacets(scoped);
272
+ const runs = await this.store.listRuns(scoped);
273
+ return mergeRunFacetRows(runs.map((r) => ({
274
+ status: r.status,
275
+ origin: r.origin,
276
+ count: 1
277
+ })));
278
+ }
279
+ /**
280
+ * The distinct values behind a console's pickers, straight off the store's enumeration. A store
281
+ * without one answers `[]` rather than falling back to a listing: unlike the facet counts above —
282
+ * where a full listing is at least the RIGHT answer expensively — a picker built from an unbounded
283
+ * scan would be the same unbounded read on every keystroke, for a control whose free-text entry
284
+ * still works without it.
285
+ */
286
+ async runValueFacets(axis, query, opts) {
287
+ return this.store.runValueFacets?.(axis, withoutRegistry(query), opts) ?? [];
288
+ }
289
+ /**
290
+ * Bulk-resolve what each of `runIds` is currently parked on — for a consumer with its own filtered/
291
+ * paginated run listing (e.g. "which of MY suspended runs are stuck at a breakpoint") without
292
+ * re-deriving `listRuns`' waiter read or querying `durable_step_checkpoints` directly. Mirrors
293
+ * `listRuns`' waiting computation (the requested runs' signal waiters + `resolveRunWaiting`), but ALSO
294
+ * bulk-fetches the currently-suspended runs to check real status: `engine.cancel` (the non-compensate
295
+ * path) doesn't clear a run's signal waiter row, so a cancelled run can leave an ORPHANED waiter
296
+ * behind — trusting waiter presence alone would wrongly report a terminal run as still waiting.
297
+ * Two bulk reads total (never one query per requested id), same as `listRuns`.
298
+ */
299
+ async waitingFor(runIds) {
300
+ if (runIds.length === 0) return {};
301
+ const idSet = new Set(runIds);
302
+ const [suspended, waiters] = await Promise.all([
303
+ this.store.listRuns({
304
+ statuses: [
305
+ "suspended"
306
+ ]
307
+ }),
308
+ listSignalWaitersOfRuns(this.store, runIds)
309
+ ]);
310
+ const waiterByRun = indexWaitersByRun(waiters);
311
+ const result = {};
312
+ for (const run of suspended) {
313
+ if (!idSet.has(run.id)) continue;
314
+ const waiting = resolveRunWaiting(run, waiterByRun);
315
+ if (waiting) result[run.id] = waiting;
316
+ }
317
+ return result;
318
+ }
319
+ /** Every group the engine knows about — unscoped. A tenant proxy's request is scoped by the
320
+ * `RunRequestResponder` (to the requester's `@<tenant>` groups); the operator's own UI sees all. */
321
+ workerHealth() {
322
+ return this.engine.workerHealth();
323
+ }
324
+ cancel(runId, opts) {
325
+ return this.engine.cancel(runId, opts);
326
+ }
327
+ /** Re-enqueue (dispatch model) instead of resuming inline — a worker picks the run up and replays it. */
328
+ retry(runId) {
329
+ return this.engine.requeue(runId);
330
+ }
331
+ continue(runId) {
332
+ return this.engine.continue(runId);
333
+ }
334
+ retryWithInput(runId, input) {
335
+ return this.engine.retryWithInput(runId, input);
336
+ }
337
+ redispatchPending(runId) {
338
+ return this.engine.redispatchPending(runId);
339
+ }
340
+ republishLifecycle(target) {
341
+ return this.engine.republishLifecycle(target);
342
+ }
343
+ subscribe(runId, onEvent) {
344
+ return this.engine.subscribe((event) => {
345
+ if (event.runId === runId) onEvent(event);
346
+ });
347
+ }
348
+ };
349
+ StoreRunGateway = _ts_decorate([
350
+ Injectable(),
351
+ _ts_param(0, Inject(STATE_STORE_CANONICAL)),
352
+ _ts_metadata("design:type", Function),
353
+ _ts_metadata("design:paramtypes", [
354
+ typeof StateStore === "undefined" ? Object : StateStore,
355
+ typeof WorkflowEngine === "undefined" ? Object : WorkflowEngine
356
+ ])
357
+ ], StoreRunGateway);
358
+
359
+ // src/migrate-from-nestjs-workflows/combined-run-gateway.ts
360
+ import { RunGateway } from "@dudousxd/nestjs-durable-core";
361
+ var CombinedRunGateway = class extends RunGateway {
362
+ static {
363
+ __name(this, "CombinedRunGateway");
364
+ }
365
+ primary;
366
+ legacy;
367
+ // Durable-only features (lifecycle events, fan paging): the primary's, when it has them.
368
+ getFanMembers;
369
+ republishLifecycle;
370
+ workflowLifecycle;
371
+ lifecycleSubscribers;
372
+ constructor(primary, legacy) {
373
+ super();
374
+ this.primary = primary;
375
+ this.legacy = legacy;
376
+ if (primary.getFanMembers) this.getFanMembers = primary.getFanMembers.bind(primary);
377
+ if (primary.republishLifecycle) this.republishLifecycle = primary.republishLifecycle.bind(primary);
378
+ if (primary.workflowLifecycle) this.workflowLifecycle = primary.workflowLifecycle.bind(primary);
379
+ if (primary.lifecycleSubscribers) {
380
+ this.lifecycleSubscribers = primary.lifecycleSubscribers.bind(primary);
381
+ }
382
+ }
383
+ topology() {
384
+ return {
385
+ ...this.primary.topology(),
386
+ engine: "nestjs-durable + @nestjs/workflows"
387
+ };
388
+ }
389
+ /** The gateway that has `runId`, durable first; `undefined` when neither does. */
390
+ async owner(runId) {
391
+ for (const gateway of [
392
+ this.primary,
393
+ this.legacy
394
+ ]) {
395
+ const run = gateway.getRun ? await gateway.getRun(runId) : (await gateway.getRunDetail(runId))?.run;
396
+ if (run) return gateway;
397
+ }
398
+ return void 0;
399
+ }
400
+ async getRun(runId) {
401
+ return await this.primary.getRun?.(runId) ?? await this.legacy.getRun?.(runId) ?? (await this.getRunDetail(runId))?.run ?? null;
402
+ }
403
+ async getRunDetail(runId, options) {
404
+ return await this.primary.getRunDetail(runId, options) ?? this.legacy.getRunDetail(runId, options);
405
+ }
406
+ /**
407
+ * Both lists, newest first, then the page. The legacy side holds only the rows its gateway can
408
+ * read: the official gateway reads at most `WORKFLOWS_LIST_CAP` (1000) matching instances per list,
409
+ * so legacy rows past that cap are missing here as they are from the legacy console, and deep pages
410
+ * show durable rows only.
411
+ */
412
+ async listRuns(query) {
413
+ const offset = query.offset ?? 0;
414
+ const limit = query.limit ?? 100;
415
+ const window = {
416
+ ...query,
417
+ offset: 0,
418
+ limit: offset + limit
419
+ };
420
+ const [a, b] = await Promise.all([
421
+ this.primary.listRuns(window),
422
+ this.legacy.listRuns(window)
423
+ ]);
424
+ return [
425
+ ...a,
426
+ ...b
427
+ ].sort((x, y) => y.createdAt.getTime() - x.createdAt.getTime() || y.id.localeCompare(x.id)).slice(offset, offset + limit);
428
+ }
429
+ async runFacets(query) {
430
+ const [a, b] = await Promise.all([
431
+ this.primary.runFacets(query),
432
+ this.legacy.runFacets(query)
433
+ ]);
434
+ const cells = /* @__PURE__ */ new Map();
435
+ for (const row of [
436
+ ...a,
437
+ ...b
438
+ ]) {
439
+ const key = `${row.status}\0${row.origin ?? ""}`;
440
+ const cell = cells.get(key);
441
+ if (cell) cell.count += row.count;
442
+ else cells.set(key, {
443
+ ...row
444
+ });
445
+ }
446
+ return [
447
+ ...cells.values()
448
+ ];
449
+ }
450
+ async runValueFacets(axis, query, opts) {
451
+ const [a, b] = await Promise.all([
452
+ this.primary.runValueFacets(axis, query, opts),
453
+ this.legacy.runValueFacets(axis, query, opts)
454
+ ]);
455
+ const counts = /* @__PURE__ */ new Map();
456
+ for (const row of [
457
+ ...a,
458
+ ...b
459
+ ]) counts.set(row.value, (counts.get(row.value) ?? 0) + row.count);
460
+ return [
461
+ ...counts
462
+ ].map(([value, count]) => ({
463
+ value,
464
+ count
465
+ })).sort((x, y) => y.count - x.count);
466
+ }
467
+ async waitingFor(runIds) {
468
+ const [a, b] = await Promise.all([
469
+ this.primary.waitingFor(runIds),
470
+ this.legacy.waitingFor(runIds)
471
+ ]);
472
+ return {
473
+ ...b,
474
+ ...a
475
+ };
476
+ }
477
+ workerHealth() {
478
+ return this.primary.workerHealth();
479
+ }
480
+ async cancel(runId, opts) {
481
+ return (await this.owner(runId))?.cancel(runId, opts) ?? null;
482
+ }
483
+ async retry(runId) {
484
+ return (await this.owner(runId))?.retry(runId) ?? null;
485
+ }
486
+ async continue(runId) {
487
+ return (await this.owner(runId))?.continue(runId) ?? null;
488
+ }
489
+ async redispatchPending(runId) {
490
+ return (await this.owner(runId))?.redispatchPending(runId) ?? null;
491
+ }
492
+ /** Replays on the engine that ran it (a legacy run's workflow may not exist on durable yet). */
493
+ async retryWithInput(runId, input) {
494
+ return (await this.owner(runId))?.retryWithInput(runId, input) ?? null;
495
+ }
496
+ subscribe(runId, onEvent) {
497
+ const offs = [
498
+ this.primary.subscribe(runId, onEvent),
499
+ this.legacy.subscribe(runId, onEvent)
500
+ ];
501
+ return () => {
502
+ for (const off of offs) off();
503
+ };
504
+ }
505
+ };
506
+
507
+ // src/migrate-from-nestjs-workflows/index.ts
508
+ function _ts_decorate2(decorators, target, key, desc) {
509
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
510
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
511
+ r = Reflect.decorate(decorators, target, key, desc);
512
+ } else {
513
+ for (var i = decorators.length - 1; i >= 0; i--) {
514
+ if (d = decorators[i]) {
515
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
516
+ }
517
+ }
518
+ }
519
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
520
+ }
521
+ __name(_ts_decorate2, "_ts_decorate");
522
+ function _ts_metadata2(metadataKey, metadataValue) {
523
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
524
+ return Reflect.metadata(metadataKey, metadataValue);
525
+ }
526
+ }
527
+ __name(_ts_metadata2, "_ts_metadata");
528
+ function _ts_param2(paramIndex, decorator) {
529
+ return function(target, key) {
530
+ decorator(target, key, paramIndex);
531
+ };
532
+ }
533
+ __name(_ts_param2, "_ts_param");
534
+ var UNFINISHED = [
535
+ "pending",
536
+ "running",
537
+ "suspended",
538
+ "compensating"
539
+ ];
540
+ var TERMINAL = [
541
+ "completed",
542
+ "failed",
543
+ "cancelled",
544
+ "dead"
545
+ ];
546
+ var MigrationClient = class {
547
+ static {
548
+ __name(this, "MigrationClient");
549
+ }
550
+ engine;
551
+ store;
552
+ official;
553
+ constructor(engine, store, official) {
554
+ this.engine = engine;
555
+ this.store = store;
556
+ this.official = official;
557
+ }
558
+ start(workflow, input, runId = globalThis.crypto.randomUUID(), opts) {
559
+ return this.engine.start(workflowName(workflow), input, runId, opts);
560
+ }
561
+ /** The engine that owns `runId`, or `null` when neither has it. */
562
+ async owner(runId) {
563
+ if (await this.store.getRun(runId)) return "nestjs-durable";
564
+ if (await this.official.getStatus(runId)) return "@nestjs/workflows";
565
+ return null;
566
+ }
567
+ /**
568
+ * Signal the instance `runId` waits on: durable gets the token `<signal>:<key>` (deduplicated by
569
+ * `id` per token), the official engine `signal(signal, payload, { key, id })`. Resolves the owner, or `null` for an unknown id
570
+ * (nothing is sent: a signal for nobody would be buffered for a later wait).
571
+ */
572
+ async signal(runId, signal, payload, opts = {}) {
573
+ const owner = await this.owner(runId);
574
+ if (owner === "nestjs-durable") {
575
+ await this.engine.signal(opts.key ? `${signal}:${opts.key}` : signal, payload, opts.id !== void 0 ? {
576
+ id: opts.id
577
+ } : void 0);
578
+ } else if (owner === "@nestjs/workflows") {
579
+ await this.official.signal(signal, payload, {
580
+ ...opts.key !== void 0 ? {
581
+ key: opts.key
582
+ } : {},
583
+ ...opts.id !== void 0 ? {
584
+ id: opts.id
585
+ } : {}
586
+ });
587
+ }
588
+ return owner;
589
+ }
590
+ /**
591
+ * Cancel `runId` where it runs. `compensate: true` runs the saga undo (official `cancel`);
592
+ * otherwise it stops without compensating (official `terminate`).
593
+ */
594
+ async cancel(runId, opts = {}) {
595
+ const owner = await this.owner(runId);
596
+ if (owner === "nestjs-durable") await this.engine.cancel(runId, opts);
597
+ else if (owner === "@nestjs/workflows") {
598
+ if (opts.compensate) await this.official.cancel(runId);
599
+ else await this.official.terminate(runId);
600
+ }
601
+ return owner ? this.getStatus(runId) : null;
602
+ }
603
+ async getStatus(runId) {
604
+ const run = await this.store.getRun(runId);
605
+ if (run) {
606
+ return {
607
+ engine: "nestjs-durable",
608
+ runId,
609
+ workflow: run.workflow,
610
+ status: run.status,
611
+ ...run.output !== void 0 ? {
612
+ output: run.output
613
+ } : {},
614
+ ...run.error ? {
615
+ error: run.error
616
+ } : {}
617
+ };
618
+ }
619
+ const instance = await this.official.getStatus(runId);
620
+ if (!instance) return null;
621
+ const mapped = toWorkflowRun(instance);
622
+ return {
623
+ engine: "@nestjs/workflows",
624
+ runId,
625
+ workflow: instance.workflow,
626
+ status: mapped.status,
627
+ ...mapped.output !== void 0 ? {
628
+ output: mapped.output
629
+ } : {},
630
+ ...mapped.error ? {
631
+ error: mapped.error
632
+ } : {}
633
+ };
634
+ }
635
+ /**
636
+ * Wait for `runId` to finish where it runs and resolve its status (`completed` with `output`, or
637
+ * `failed` / `cancelled` / `dead` with `error`). Never throws for a failed instance.
638
+ */
639
+ async result(runId, opts = {}) {
640
+ const owner = await this.owner(runId);
641
+ if (owner === "nestjs-durable") {
642
+ await this.engine.waitForRun(runId, {
643
+ until: "terminal",
644
+ ...opts.timeoutMs !== void 0 ? {
645
+ timeoutMs: opts.timeoutMs
646
+ } : {}
647
+ });
648
+ } else if (owner === "@nestjs/workflows") {
649
+ await this.official.result(runId, opts.timeoutMs !== void 0 ? {
650
+ timeout: opts.timeoutMs
651
+ } : {}).catch((error) => {
652
+ if (error?.name !== "WorkflowFailedError") throw error;
653
+ });
654
+ } else {
655
+ throw new Error(`no instance ${runId} in nestjs-durable or @nestjs/workflows`);
656
+ }
657
+ const status = await this.getStatus(runId);
658
+ if (!status || !TERMINAL.includes(status.status)) {
659
+ throw new Error(`instance ${runId} did not finish`);
660
+ }
661
+ return status;
662
+ }
663
+ /**
664
+ * How many instances the official engine still has to finish. The cutover is over when it is 0:
665
+ * nothing starts there any more, so it only goes down.
666
+ */
667
+ async remainingOnOfficial() {
668
+ return (await this.official.list({
669
+ status: UNFINISHED,
670
+ limit: 1e4
671
+ })).length;
672
+ }
673
+ };
674
+ MigrationClient = _ts_decorate2([
675
+ Injectable2(),
676
+ _ts_param2(1, Inject2(STATE_STORE_CANONICAL2)),
677
+ _ts_metadata2("design:type", Function),
678
+ _ts_metadata2("design:paramtypes", [
679
+ typeof WorkflowEngine2 === "undefined" ? Object : WorkflowEngine2,
680
+ typeof StateStore === "undefined" ? Object : StateStore,
681
+ typeof WorkflowClient === "undefined" ? Object : WorkflowClient
682
+ ])
683
+ ], MigrationClient);
684
+ function combinedGateway(store, engine, client, events) {
685
+ return new CombinedRunGateway(new StoreRunGateway(store, engine), new WorkflowsRunGateway(client, events));
686
+ }
687
+ __name(combinedGateway, "combinedGateway");
688
+ var DurableMigrationModule = class _DurableMigrationModule {
689
+ static {
690
+ __name(this, "DurableMigrationModule");
691
+ }
692
+ static forRoot() {
693
+ return {
694
+ module: _DurableMigrationModule,
695
+ global: true,
696
+ providers: [
697
+ MigrationClient
698
+ ],
699
+ exports: [
700
+ MigrationClient
701
+ ]
702
+ };
703
+ }
704
+ static console() {
705
+ return {
706
+ module: DurableMigrationConsoleModule,
707
+ providers: [
708
+ {
709
+ provide: RunGateway2,
710
+ inject: [
711
+ STATE_STORE_CANONICAL2,
712
+ WorkflowEngine2,
713
+ WorkflowClient,
714
+ WorkflowEvents
715
+ ],
716
+ useFactory: combinedGateway
717
+ }
718
+ ],
719
+ exports: [
720
+ RunGateway2
721
+ ]
722
+ };
723
+ }
724
+ };
725
+ DurableMigrationModule = _ts_decorate2([
726
+ Module({})
727
+ ], DurableMigrationModule);
728
+ var DurableMigrationConsoleModule = class DurableMigrationConsoleModule2 {
729
+ static {
730
+ __name(this, "DurableMigrationConsoleModule");
731
+ }
732
+ };
733
+ DurableMigrationConsoleModule = _ts_decorate2([
734
+ Module({})
735
+ ], DurableMigrationConsoleModule);
736
+ export {
737
+ CombinedRunGateway,
738
+ DurableMigrationModule,
739
+ MigrationClient
740
+ };
741
+ //# sourceMappingURL=migrate-from-nestjs-workflows.js.map