@voltro/workflow 0.1.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,817 @@
1
+ import { C as e, S as t, b as n, x as r } from "./primitives-CWy1iu5w.js";
2
+ import { Activity as i, DurableClock as a, DurableDeferred as o, Workflow as s, WorkflowEngine as c } from "@effect/workflow";
3
+ import { Cause as l, Effect as u, Exit as d, FiberRef as f, Layer as p, Schema as m } from "effect";
4
+ import { and as h, boolean as g, eq as _, id as v, integer as y, json as b, or as x, queryFor as S, reference as C, table as w, text as T, timestamp as E } from "@voltro/database";
5
+ import { WorkflowInstance as ee } from "@effect/workflow/WorkflowEngine";
6
+ import { publishServerError as te } from "@voltro/protocol";
7
+ //#region src/inMemoryLayer.ts
8
+ var D = c.layerMemory, O = w("_voltro_workflow_runs", {
9
+ id: v({ prefix: "wfrun" }),
10
+ tag: T(),
11
+ executionId: T().unique(),
12
+ status: T().oneOf([
13
+ "running",
14
+ "succeeded",
15
+ "failed",
16
+ "cancelled",
17
+ "suspended"
18
+ ]).default("running"),
19
+ payload: b(),
20
+ workflowVersion: T().nullable(),
21
+ workflowPatches: b().nullable(),
22
+ output: b().nullable(),
23
+ subject: b().nullable(),
24
+ source: T().nullable(),
25
+ errorTag: T().nullable(),
26
+ errorMessage: T().nullable(),
27
+ cancelled: g().default(!1),
28
+ startedAt: E().default("now"),
29
+ completedAt: E().nullable(),
30
+ durationMs: y().nullable(),
31
+ traceId: T().nullable(),
32
+ parentExecutionId: T().nullable(),
33
+ parentClosePolicy: T().oneOf([
34
+ "cancel",
35
+ "terminate",
36
+ "abandon"
37
+ ]).nullable()
38
+ }).index(["tag"]).index(["status"]).index(["source"]).index(["startedAt"]).index(["parentExecutionId"]).index(["parentClosePolicy"]).reactive(), k = w("_voltro_workflow_run_steps", {
39
+ id: v({ prefix: "wfstep" }),
40
+ runId: C(() => O, {
41
+ index: !1,
42
+ onDelete: "cascade"
43
+ }),
44
+ stepName: T(),
45
+ attempt: y().default(1),
46
+ status: T().oneOf([
47
+ "running",
48
+ "succeeded",
49
+ "failed"
50
+ ]).default("running"),
51
+ input: b().nullable(),
52
+ retryPolicy: b().nullable(),
53
+ output: b().nullable(),
54
+ errorTag: T().nullable(),
55
+ errorMessage: T().nullable(),
56
+ errorCause: b().nullable(),
57
+ startedAt: E().default("now"),
58
+ completedAt: E().nullable(),
59
+ durationMs: y().nullable()
60
+ }).index(["runId", "stepName"]).index(["startedAt"]).reactive(), A = w("_voltro_workflow_run_events", {
61
+ id: v({ prefix: "wfev" }),
62
+ runId: C(() => O, {
63
+ index: !1,
64
+ onDelete: "cascade"
65
+ }),
66
+ eventType: T(),
67
+ payload: b().nullable(),
68
+ occurredAt: E().default("now"),
69
+ stepName: T().nullable(),
70
+ attempt: y().nullable()
71
+ }).index(["runId", "occurredAt"]).index(["eventType"]).reactive(), j = w("_voltro_workflow_start_contexts", {
72
+ id: v({ prefix: "wfctx" }),
73
+ workflowName: T(),
74
+ executionId: T().unique(),
75
+ subject: b().nullable(),
76
+ traceId: T().nullable(),
77
+ source: T().nullable(),
78
+ parentExecutionId: T().nullable(),
79
+ parentClosePolicy: T().oneOf([
80
+ "cancel",
81
+ "terminate",
82
+ "abandon"
83
+ ]).nullable(),
84
+ createdAt: E().default("now")
85
+ }).index(["workflowName"]).index(["executionId"]).index(["parentExecutionId"]), M = async (e, t) => {
86
+ if (e) try {
87
+ await e.recordEvent(t);
88
+ } catch {}
89
+ }, N = (t, n) => {
90
+ let a = u.gen(function* () {
91
+ let i = n.pollIntervalMs ?? 200, a = n.maxPollIntervalMs ?? 5e3, o = n.timeoutMs ?? 1440 * 6e4, s = yield* r, c = yield* u.serviceOption(e), l = c._tag === "Some" ? c.value : void 0;
92
+ if (s === void 0) return yield* u.die(/* @__PURE__ */ Error("awaitSignal: no active workflow run id in scope"));
93
+ let d = s;
94
+ yield* u.promise(() => M(l, {
95
+ runId: d,
96
+ eventType: "signal-awaited",
97
+ payload: { signalName: n.name }
98
+ }));
99
+ let f = Date.now(), p = i;
100
+ for (;;) {
101
+ let e = Date.now() - f;
102
+ if (e > o) return yield* u.die(/* @__PURE__ */ Error(`awaitSignal('${n.name}') timed out after ${e}ms`));
103
+ let r = {
104
+ table: "_voltro_workflow_run_events",
105
+ order: [{
106
+ column: "occurredAt",
107
+ direction: "asc"
108
+ }],
109
+ predicate: h(_("runId", d), _("eventType", "signal-sent")),
110
+ projection: void 0,
111
+ skip: void 0,
112
+ take: 1e3
113
+ }, i = (yield* u.tryPromise({
114
+ try: () => t.store.query(r),
115
+ catch: (e) => e
116
+ })).find((e) => e.payload?.signalName === n.name);
117
+ if (i !== void 0) {
118
+ let e = yield* m.decodeUnknown(n.schema)(i.payload?.value);
119
+ return yield* u.promise(() => M(l, {
120
+ runId: d,
121
+ eventType: "signal-received",
122
+ payload: {
123
+ signalName: n.name,
124
+ value: i.payload?.value
125
+ }
126
+ })), e;
127
+ }
128
+ yield* u.sleep(`${p} millis`), p = Math.min(p * 2, a);
129
+ }
130
+ });
131
+ return i.make({
132
+ name: `await-signal:${n.name}`,
133
+ success: n.schema,
134
+ execute: a
135
+ });
136
+ }, P = (e) => new Promise((t) => setTimeout(t, e)), ne = () => {
137
+ let e = globalThis.crypto;
138
+ return typeof e?.randomUUID == "function" ? e.randomUUID() : `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
139
+ }, F = () => `wfu_${ne()}`, I = async (e, t) => {
140
+ let n = t.id ?? t.executionId;
141
+ if (!n) throw Error("workflow message target requires target.id or target.executionId");
142
+ let r = await e.query({
143
+ table: "_voltro_workflow_runs",
144
+ order: [],
145
+ predicate: _("id", n),
146
+ projection: void 0,
147
+ skip: void 0,
148
+ take: 1
149
+ });
150
+ if (r[0]) return r[0];
151
+ let i = (await e.query({
152
+ table: "_voltro_workflow_runs",
153
+ order: [],
154
+ predicate: _("executionId", n),
155
+ projection: void 0,
156
+ skip: void 0,
157
+ take: 1
158
+ }))[0];
159
+ if (!i) throw Error(`workflow message target not found: ${n}`);
160
+ return i;
161
+ }, re = async (e) => {
162
+ let t = await I(e.store, e.target);
163
+ return { eventId: (await e.recorder.recordEvent({
164
+ runId: t.id,
165
+ eventType: "signal-sent",
166
+ payload: {
167
+ signalName: e.signalName,
168
+ value: e.payload
169
+ }
170
+ })).id };
171
+ }, ie = async (e) => {
172
+ let t = await I(e.store, e.target), n = F(), r = await e.recorder.recordEvent({
173
+ runId: t.id,
174
+ eventType: "update-requested",
175
+ payload: {
176
+ updateId: n,
177
+ updateName: e.updateName,
178
+ value: e.payload
179
+ }
180
+ }), i = Date.now(), a = e.options?.timeoutMs ?? 3e4, o = e.options?.pollIntervalMs ?? 100;
181
+ for (;;) {
182
+ let s = {
183
+ table: "_voltro_workflow_run_events",
184
+ order: [{
185
+ column: "occurredAt",
186
+ direction: "asc"
187
+ }],
188
+ predicate: _("runId", t.id),
189
+ projection: void 0,
190
+ skip: void 0,
191
+ take: 1e3
192
+ }, c = await e.store.query(s), l = c.find((e) => e.eventType === "update-completed" && e.payload?.updateId === n);
193
+ if (l) return {
194
+ eventId: r.id,
195
+ updateId: n,
196
+ completedEventId: l.id,
197
+ result: l.payload?.result
198
+ };
199
+ let u = c.find((e) => e.eventType === "update-failed" && e.payload?.updateId === n);
200
+ if (u) {
201
+ let t = Error(u.payload?.errorMessage ?? `workflow update '${e.updateName}' failed`);
202
+ throw Object.assign(t, {
203
+ updateId: n,
204
+ eventId: r.id,
205
+ errorTag: u.payload?.errorTag ?? null
206
+ }), t;
207
+ }
208
+ if (Date.now() - i >= a) throw Error(`Timed out waiting for workflow update '${e.updateName}' (${n})`);
209
+ await P(o);
210
+ }
211
+ }, L = 1440 * 6e4, R = "voltro/suspending-signal", z = (e, t) => `${R}/${e}/${t}`, B = (e) => o.make(e, { success: m.Unknown }), V = async (e, t) => {
212
+ if (e) try {
213
+ await e.recordEvent(t);
214
+ } catch {}
215
+ }, H = (t, n) => u.gen(function* () {
216
+ let t = n.timeoutMs ?? L, i = B(z((yield* c.WorkflowInstance).workflow.name, n.name)), s = yield* r, l = yield* u.serviceOption(e), d = l._tag === "Some" ? l.value : void 0;
217
+ s !== void 0 && (yield* u.promise(() => V(d, {
218
+ runId: s,
219
+ eventType: "signal-awaited",
220
+ payload: { signalName: n.name }
221
+ })));
222
+ let f = o.await(i), p = Number.isFinite(t) ? yield* u.race(f, a.sleep({
223
+ name: `await-signal-timeout/${n.name}`,
224
+ duration: `${t} millis`
225
+ }).pipe(u.andThen(u.die(/* @__PURE__ */ Error(`awaitSignalSuspending('${n.name}') timed out after ${t}ms`))))) : yield* f, h = yield* m.decodeUnknown(n.schema)(p);
226
+ return s !== void 0 && (yield* u.promise(() => V(d, {
227
+ runId: s,
228
+ eventType: "signal-received",
229
+ payload: {
230
+ signalName: n.name,
231
+ value: h
232
+ }
233
+ }))), h;
234
+ }), U = (e) => u.gen(function* () {
235
+ let t = e.target.executionId, n = e.target.workflowName;
236
+ if (t === void 0 || n === void 0) {
237
+ let r = e.store;
238
+ if (r === void 0) return yield* u.die(/* @__PURE__ */ Error("completeSuspendingSignal: provide a store, or target.executionId AND target.workflowName"));
239
+ let i = yield* u.tryPromise({
240
+ try: () => I(r, e.target),
241
+ catch: (e) => e
242
+ });
243
+ t ??= i.executionId, n ??= i.tag;
244
+ }
245
+ if (t === void 0 || n === void 0) return { completed: !1 };
246
+ let r = z(n, e.signalName), i = B(r), a = new o.TokenParsed({
247
+ workflowName: n,
248
+ executionId: t,
249
+ deferredName: r
250
+ }).asToken;
251
+ return yield* o.done(i, {
252
+ token: a,
253
+ exit: d.succeed(e.payload)
254
+ }), { completed: !0 };
255
+ }), W = async (e, t) => {
256
+ if (e) try {
257
+ await e.recordEvent(t);
258
+ } catch {}
259
+ }, G = (e) => {
260
+ let t = l.failureOption(e), n = Array.from(l.defects(e)), r = t._tag === "Some" ? t.value : n[0] ?? l.squash(e);
261
+ return {
262
+ errorTag: r && typeof r == "object" && "_tag" in r ? String(r._tag) : null,
263
+ errorMessage: r?.message ?? String(r)
264
+ };
265
+ }, ae = (t, n) => {
266
+ let a = u.gen(function* () {
267
+ let i = n.pollIntervalMs ?? 200, a = n.maxPollIntervalMs ?? 5e3, o = n.timeoutMs ?? 3e4, s = yield* r, c = yield* u.serviceOption(e), l = c._tag === "Some" ? c.value : void 0;
268
+ if (s === void 0) return yield* u.die(/* @__PURE__ */ Error("awaitUpdate: no active workflow run id in scope"));
269
+ let d = s, f = Date.now(), p = i;
270
+ for (;;) {
271
+ let e = Date.now() - f;
272
+ if (e > o) return yield* u.die(/* @__PURE__ */ Error(`awaitUpdate('${n.name}') timed out after ${e}ms`));
273
+ let r = {
274
+ table: "_voltro_workflow_run_events",
275
+ order: [{
276
+ column: "occurredAt",
277
+ direction: "asc"
278
+ }],
279
+ predicate: _("runId", d),
280
+ projection: void 0,
281
+ skip: void 0,
282
+ take: 1e3
283
+ }, i = yield* u.tryPromise({
284
+ try: () => t.store.query(r),
285
+ catch: (e) => e
286
+ }), s = new Set(i.filter((e) => e.eventType === "update-completed" || e.eventType === "update-failed").map((e) => e.payload?.updateId).filter((e) => typeof e == "string" && e.length > 0)), c = i.find((e) => e.eventType === "update-requested" && e.payload?.updateName === n.name && typeof e.payload.updateId == "string" && !s.has(e.payload.updateId));
287
+ if (c !== void 0) {
288
+ let e = c.payload.updateId;
289
+ yield* u.promise(() => W(l, {
290
+ runId: d,
291
+ eventType: "update-received",
292
+ payload: {
293
+ updateId: e,
294
+ updateName: n.name
295
+ }
296
+ }));
297
+ let t = yield* m.decodeUnknown(n.schema)(c.payload?.value).pipe(u.tapErrorCause((t) => u.promise(() => W(l, {
298
+ runId: d,
299
+ eventType: "update-failed",
300
+ payload: {
301
+ updateId: e,
302
+ updateName: n.name,
303
+ ...G(t)
304
+ }
305
+ })))), r = yield* (n.handle ? n.handle(t) : u.succeed(t)).pipe(u.flatMap((e) => n.success ? m.decodeUnknown(n.success)(e) : u.succeed(e))).pipe(u.tapErrorCause((t) => u.promise(() => W(l, {
306
+ runId: d,
307
+ eventType: "update-failed",
308
+ payload: {
309
+ updateId: e,
310
+ updateName: n.name,
311
+ ...G(t)
312
+ }
313
+ }))));
314
+ return yield* u.promise(() => W(l, {
315
+ runId: d,
316
+ eventType: "update-completed",
317
+ payload: {
318
+ updateId: e,
319
+ updateName: n.name,
320
+ result: r
321
+ }
322
+ })), r;
323
+ }
324
+ yield* u.sleep(`${p} millis`), p = Math.min(p * 2, a);
325
+ }
326
+ });
327
+ return i.make({
328
+ name: `await-update:${n.name}`,
329
+ success: n.success ?? n.schema,
330
+ execute: a
331
+ });
332
+ }, K = 8 * 1024, oe = () => {
333
+ let e = globalThis.crypto;
334
+ return typeof e?.randomUUID == "function" ? e.randomUUID() : `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
335
+ }, q = (e) => `${e}_${oe()}`, J = (e, t = K) => {
336
+ if (e == null) return e;
337
+ try {
338
+ let n = JSON.stringify(e);
339
+ return n.length <= t ? e : {
340
+ __truncated: !0,
341
+ bytes: n.length,
342
+ sample: n.slice(0, t)
343
+ };
344
+ } catch {
345
+ return { __unserialisable: String(e) };
346
+ }
347
+ }, Y = (e) => {
348
+ let t = {};
349
+ for (let [n, r] of Object.entries(e)) t[n] = r instanceof Date ? r.toISOString() : r;
350
+ return t;
351
+ }, X = (e) => {
352
+ let t = e.truncateBytes ?? K, n = e.makeId ?? q, r = (t, n) => e.log?.warn(t, n), i = e.emit;
353
+ return {
354
+ startStep: async ({ runId: a, stepName: o, attempt: s, stepInput: c, retryPolicy: l }) => {
355
+ try {
356
+ let r = await e.store.insert("_voltro_workflow_run_steps", {
357
+ id: n("ws"),
358
+ runId: a,
359
+ stepName: o,
360
+ attempt: s,
361
+ status: "running",
362
+ input: c === void 0 ? null : J(c, t),
363
+ retryPolicy: l ?? null,
364
+ output: null,
365
+ errorTag: null,
366
+ errorMessage: null,
367
+ startedAt: /* @__PURE__ */ new Date(),
368
+ completedAt: null,
369
+ durationMs: null
370
+ });
371
+ return i?.("workflowSteps", {
372
+ op: "insert",
373
+ row: Y(r)
374
+ }), r.id;
375
+ } catch (e) {
376
+ r("failed to record step start (continuing)", {
377
+ runId: a,
378
+ stepName: o,
379
+ attempt: s,
380
+ reason: e?.message ?? String(e)
381
+ });
382
+ return;
383
+ }
384
+ },
385
+ endStepSuccess: async ({ stepRecordId: n, output: a, durationMs: o }) => {
386
+ try {
387
+ let r = await e.store.update("_voltro_workflow_run_steps", n, {
388
+ status: "succeeded",
389
+ output: J(a, t),
390
+ completedAt: /* @__PURE__ */ new Date(),
391
+ durationMs: o
392
+ });
393
+ r && i?.("workflowSteps", {
394
+ op: "update",
395
+ row: Y(r)
396
+ });
397
+ } catch (e) {
398
+ r("failed to record step success", {
399
+ stepRecordId: n,
400
+ reason: e?.message ?? String(e)
401
+ });
402
+ }
403
+ },
404
+ endStepFailure: async ({ stepRecordId: n, errorTag: a, errorMessage: o, errorCause: s, durationMs: c }) => {
405
+ try {
406
+ let r = await e.store.update("_voltro_workflow_run_steps", n, {
407
+ status: "failed",
408
+ errorTag: a,
409
+ errorMessage: o,
410
+ errorCause: s === void 0 ? null : J(s, t),
411
+ completedAt: /* @__PURE__ */ new Date(),
412
+ durationMs: c
413
+ });
414
+ r && i?.("workflowSteps", {
415
+ op: "update",
416
+ row: Y(r)
417
+ });
418
+ } catch (e) {
419
+ r("failed to record step failure", {
420
+ stepRecordId: n,
421
+ reason: e?.message ?? String(e)
422
+ });
423
+ }
424
+ },
425
+ recordEvent: async ({ runId: t, eventType: a, payload: o, stepName: s, attempt: c }) => {
426
+ let l = n("wfev");
427
+ try {
428
+ let n = await e.store.insert("_voltro_workflow_run_events", {
429
+ id: l,
430
+ runId: t,
431
+ eventType: a,
432
+ payload: o ?? null,
433
+ occurredAt: /* @__PURE__ */ new Date(),
434
+ stepName: s ?? null,
435
+ attempt: c ?? null
436
+ });
437
+ i?.("workflowEvents", {
438
+ op: "insert",
439
+ row: Y(n)
440
+ });
441
+ } catch (e) {
442
+ r("failed to record workflow event (continuing)", {
443
+ runId: t,
444
+ eventType: a,
445
+ reason: e?.message ?? String(e)
446
+ });
447
+ }
448
+ if (e.wakeups !== void 0) {
449
+ let n = o?.scheduledWakeAt, r = typeof n == "string" ? new Date(n) : void 0, i = o?.tenantId, s = typeof i == "string" ? i : void 0;
450
+ a === "timer-set" && r !== void 0 && !Number.isNaN(r.getTime()) ? await e.wakeups.register(t, r, s).catch(() => {}) : (a === "timer-fired" || a === "run-succeeded" || a === "run-failed" || a === "run-cancelled") && await e.wakeups.cancel(t, s).catch(() => {});
451
+ }
452
+ return { id: l };
453
+ }
454
+ };
455
+ }, se = (i, a) => {
456
+ let o = i.truncateBytes ?? K, c = i.makeId ?? q, p = i.recorder ?? X(i), m = (e, t) => i.log?.warn(e, t), h = i.emit, g = (e, t, n) => u.promise(async () => {
457
+ if (i.onParentClose) try {
458
+ await i.onParentClose({
459
+ workflowName: i.name,
460
+ executionId: e,
461
+ ...n === void 0 ? {} : { runId: n },
462
+ status: t
463
+ });
464
+ } catch (n) {
465
+ m("failed to apply workflow parent-close policy", {
466
+ tag: i.name,
467
+ executionId: e,
468
+ status: t,
469
+ reason: n?.message ?? String(n)
470
+ });
471
+ }
472
+ });
473
+ return (v, y) => u.gen(function* () {
474
+ let b = Date.now(), x = yield* f.get(n), S = i.parentExecutionId ?? x ?? null, C = i.parentClosePolicy ?? null, w, T = (e, t) => t.pipe(u.catchAllCause((t) => l.isInterrupted(t) ? u.failCause(t) : u.sync(() => {
475
+ let n = l.squash(t);
476
+ m(e, {
477
+ tag: i.name,
478
+ executionId: y,
479
+ reason: n?.message ?? String(n)
480
+ });
481
+ }))), E = (i.store.query ? yield* u.promise(() => i.store.query({
482
+ table: "_voltro_workflow_runs",
483
+ order: [],
484
+ predicate: _("executionId", y),
485
+ projection: void 0,
486
+ skip: void 0,
487
+ take: 1
488
+ })) : [])[0], D = E?.workflowVersion ?? null;
489
+ if (E?.id !== void 0 && D !== null && i.workflowCompatibleVersions !== void 0 && i.workflowCompatibleVersions !== null && !i.workflowCompatibleVersions.includes(D)) {
490
+ let e = `Workflow '${i.name}' run '${y}' was started on version ${D}, but current code is compatible with ${i.workflowCompatibleVersions.join(", ")}`, t = yield* u.promise(() => i.store.update("_voltro_workflow_runs", E.id, {
491
+ status: "failed",
492
+ errorTag: "WorkflowVersionIncompatible",
493
+ errorMessage: e,
494
+ completedAt: /* @__PURE__ */ new Date()
495
+ }));
496
+ return t && h?.("workflowRuns", {
497
+ op: "update",
498
+ row: Y(t)
499
+ }), yield* u.promise(() => p.recordEvent({
500
+ runId: E.id,
501
+ eventType: "run-failed",
502
+ payload: {
503
+ errorTag: "WorkflowVersionIncompatible",
504
+ errorMessage: e,
505
+ workflowVersion: i.workflowVersion ?? null,
506
+ compatibleWith: i.workflowCompatibleVersions,
507
+ previousVersion: D
508
+ }
509
+ })), yield* u.fail(Error(e));
510
+ }
511
+ yield* T("failed to record workflow start (continuing)", u.gen(function* () {
512
+ let e = yield* u.promise(() => i.store.insert("_voltro_workflow_runs", {
513
+ id: c("wr"),
514
+ tag: i.name,
515
+ executionId: y,
516
+ status: "running",
517
+ payload: v,
518
+ workflowVersion: i.workflowVersion ?? null,
519
+ workflowPatches: i.workflowPatches ?? null,
520
+ output: null,
521
+ subject: i.subject ?? null,
522
+ source: i.source ?? null,
523
+ errorTag: null,
524
+ errorMessage: null,
525
+ cancelled: !1,
526
+ startedAt: /* @__PURE__ */ new Date(),
527
+ completedAt: null,
528
+ durationMs: null,
529
+ traceId: i.traceId ?? null,
530
+ parentExecutionId: S,
531
+ parentClosePolicy: C
532
+ }));
533
+ if (w = e.id, h?.("workflowRuns", {
534
+ op: "insert",
535
+ row: Y(e)
536
+ }), w) {
537
+ let e = w;
538
+ yield* u.promise(() => p.recordEvent({
539
+ runId: e,
540
+ eventType: "run-started",
541
+ payload: {
542
+ tag: i.name,
543
+ executionId: y,
544
+ source: i.source ?? null,
545
+ workflowVersion: i.workflowVersion ?? null,
546
+ workflowPatches: i.workflowPatches ?? null,
547
+ parentExecutionId: S,
548
+ parentClosePolicy: C
549
+ }
550
+ }));
551
+ }
552
+ }));
553
+ let O = i.subject?.tenantId, k = a(v, y).pipe(u.locally(r, w), u.locally(n, y), u.locally(t, typeof O == "string" ? O : void 0), u.provideService(e, p)), A = i.pluginWorkflowStepLayer ? k.pipe(u.provide(i.pluginWorkflowStepLayer)) : k, j = yield* s.intoResult(A);
554
+ if (s.isResult(j) && j._tag === "Suspended") {
555
+ w && (yield* T("failed to record workflow suspend", u.gen(function* () {
556
+ let e = yield* u.promise(() => i.store.update("_voltro_workflow_runs", w, { status: "suspended" }));
557
+ e && h?.("workflowRuns", {
558
+ op: "update",
559
+ row: Y(e)
560
+ }), yield* u.promise(() => p.recordEvent({
561
+ runId: w,
562
+ eventType: "run-suspended",
563
+ payload: { reason: "workflow-suspend" }
564
+ }));
565
+ })));
566
+ let e = yield* ee;
567
+ return yield* s.suspend(e);
568
+ }
569
+ let M = j;
570
+ if (d.isFailure(M.exit)) {
571
+ let e = M.exit.cause, t = l.failureOption(e), n = t._tag === "Some" ? t.value : l.squash(e), r = n && typeof n == "object" && "_tag" in n ? String(n._tag) : null, a = n?.message ?? String(n);
572
+ return yield* u.sync(() => te({
573
+ error: n,
574
+ source: "workflow",
575
+ name: i.name,
576
+ ...i.traceId ? { traceId: i.traceId } : {},
577
+ fields: {
578
+ executionId: y,
579
+ ...r ? { errorTag: r } : {},
580
+ ...w ? { runId: w } : {}
581
+ }
582
+ })), w && (yield* T("failed to record workflow failure", u.gen(function* () {
583
+ let e = yield* u.promise(() => i.store.update("_voltro_workflow_runs", w, {
584
+ status: "failed",
585
+ errorTag: r,
586
+ errorMessage: a,
587
+ completedAt: /* @__PURE__ */ new Date(),
588
+ durationMs: Date.now() - b
589
+ }));
590
+ e && h?.("workflowRuns", {
591
+ op: "update",
592
+ row: Y(e)
593
+ }), yield* u.promise(() => p.recordEvent({
594
+ runId: w,
595
+ eventType: "run-failed",
596
+ payload: {
597
+ errorTag: r,
598
+ errorMessage: a,
599
+ durationMs: Date.now() - b
600
+ }
601
+ })), yield* g(y, "failed", w);
602
+ }))), yield* u.failCause(e);
603
+ }
604
+ let N = M.exit.value;
605
+ return w && (yield* T("failed to record workflow success", u.gen(function* () {
606
+ let e = yield* u.promise(() => i.store.update("_voltro_workflow_runs", w, {
607
+ status: "succeeded",
608
+ output: J(N, o),
609
+ completedAt: /* @__PURE__ */ new Date(),
610
+ durationMs: Date.now() - b
611
+ }));
612
+ e && h?.("workflowRuns", {
613
+ op: "update",
614
+ row: Y(e)
615
+ }), yield* u.promise(() => p.recordEvent({
616
+ runId: w,
617
+ eventType: "run-succeeded",
618
+ payload: { durationMs: Date.now() - b }
619
+ })), yield* g(y, "succeeded", w);
620
+ }))), N;
621
+ });
622
+ }, ce = (e) => e === "cancel" || e === "terminate", le = (e) => e === "running" || e === "suspended", ue = async (e) => {
623
+ let t = await e.store.query({
624
+ table: "_voltro_workflow_runs",
625
+ order: [{
626
+ column: "startedAt",
627
+ direction: "asc"
628
+ }],
629
+ predicate: _("parentExecutionId", e.parentExecutionId),
630
+ projection: void 0,
631
+ skip: void 0,
632
+ take: e.limit ?? 1e3
633
+ }), n = [];
634
+ for (let r of t) {
635
+ let t = {
636
+ runId: r.id,
637
+ workflowName: r.tag,
638
+ executionId: r.executionId,
639
+ policy: r.parentClosePolicy
640
+ };
641
+ if (r.parentClosePolicy === "abandon") {
642
+ n.push({
643
+ ...t,
644
+ action: "abandoned"
645
+ });
646
+ continue;
647
+ }
648
+ if (!ce(r.parentClosePolicy)) {
649
+ n.push({
650
+ ...t,
651
+ action: "skipped",
652
+ reason: "no-parent-close-policy"
653
+ });
654
+ continue;
655
+ }
656
+ if (!le(r.status)) {
657
+ n.push({
658
+ ...t,
659
+ action: "skipped",
660
+ reason: `status:${r.status}`
661
+ });
662
+ continue;
663
+ }
664
+ try {
665
+ await e.interruptChild(r.tag, r.executionId, r.parentClosePolicy);
666
+ let i = await e.store.update("_voltro_workflow_runs", r.id, {
667
+ status: "cancelled",
668
+ cancelled: !0,
669
+ completedAt: /* @__PURE__ */ new Date()
670
+ });
671
+ i && e.emit?.("workflowRuns", {
672
+ op: "update",
673
+ row: Y(i)
674
+ }), await e.recorder?.recordEvent({
675
+ runId: r.id,
676
+ eventType: "run-cancelled",
677
+ payload: {
678
+ reason: "parent-close",
679
+ parentExecutionId: e.parentExecutionId,
680
+ parentStatus: e.parentStatus,
681
+ parentClosePolicy: r.parentClosePolicy,
682
+ action: r.parentClosePolicy
683
+ }
684
+ }), n.push({
685
+ ...t,
686
+ action: "cancelled"
687
+ });
688
+ } catch (i) {
689
+ let a = i?.message ?? String(i);
690
+ e.log?.warn("workflow.parentClose.childInterrupt failed", {
691
+ parentExecutionId: e.parentExecutionId,
692
+ childExecutionId: r.executionId,
693
+ childWorkflowName: r.tag,
694
+ parentClosePolicy: r.parentClosePolicy,
695
+ reason: a
696
+ }), n.push({
697
+ ...t,
698
+ action: "failed",
699
+ reason: a
700
+ });
701
+ }
702
+ }
703
+ return n;
704
+ }, Z = (e) => {
705
+ if (e == null) return null;
706
+ if (e instanceof Date) return e;
707
+ if (typeof e == "string" || typeof e == "number") {
708
+ let t = new Date(e);
709
+ return Number.isNaN(t.getTime()) ? null : t;
710
+ }
711
+ return null;
712
+ }, Q = (e) => typeof e == "number" ? e : e == null ? null : Number(e), $ = (e) => e == null ? null : String(e), de = (e) => {
713
+ let t = /* @__PURE__ */ new Map();
714
+ for (let n of e) {
715
+ let e = String(n.stepName), r = t.get(e);
716
+ r === void 0 ? t.set(e, [n]) : r.push(n);
717
+ }
718
+ let n = [];
719
+ for (let [e, r] of t) {
720
+ r.sort((e, t) => (Q(e.attempt) ?? 0) - (Q(t.attempt) ?? 0));
721
+ let t = r[r.length - 1], i = $(t.errorTag), a = $(t.errorMessage), o = i !== null || a !== null ? {
722
+ tag: i,
723
+ message: a ?? ""
724
+ } : null;
725
+ n.push({
726
+ name: e,
727
+ attempt: Q(t.attempt) ?? r.length,
728
+ attempts: r.length,
729
+ status: t.status ?? "running",
730
+ input: t.input ?? null,
731
+ output: t.output ?? null,
732
+ error: o,
733
+ durationMs: Q(t.durationMs)
734
+ });
735
+ }
736
+ return n.sort((t, n) => {
737
+ let r = e.find((e) => String(e.stepName) === t.name), i = e.find((e) => String(e.stepName) === n.name);
738
+ return (Z(r?.startedAt)?.getTime() ?? 0) - (Z(i?.startedAt)?.getTime() ?? 0);
739
+ }), n;
740
+ }, fe = (e) => {
741
+ if (e == null) return null;
742
+ if (typeof e == "string") try {
743
+ return JSON.parse(e);
744
+ } catch {
745
+ return null;
746
+ }
747
+ return typeof e == "object" ? e : null;
748
+ }, pe = async (e, t) => {
749
+ let n = S(O), r = (await t.query(n.where(x(_("id", e), _("executionId", e))).limit(1).descriptor))[0];
750
+ if (r === void 0) return null;
751
+ let i = String(r.id), a = S(k), o = await t.query(a.where(_("runId", i)).descriptor);
752
+ return {
753
+ id: i,
754
+ executionId: $(r.executionId) ?? "",
755
+ name: $(r.tag) ?? "",
756
+ status: r.status ?? "running",
757
+ input: r.payload ?? null,
758
+ output: r.output ?? null,
759
+ subject: fe(r.subject),
760
+ source: $(r.source),
761
+ steps: de(o),
762
+ startedAt: Z(r.startedAt) ?? /* @__PURE__ */ new Date(0),
763
+ finishedAt: Z(r.completedAt),
764
+ traceId: $(r.traceId),
765
+ parentExecutionId: $(r.parentExecutionId),
766
+ parentClosePolicy: $(r.parentClosePolicy)
767
+ };
768
+ }, me = () => {
769
+ let t = [], n = [], r = 0, i = 0;
770
+ return {
771
+ layer: p.succeed(e, {
772
+ startStep: async ({ runId: e, stepName: n, attempt: i, stepInput: a, retryPolicy: o }) => {
773
+ let s = `wfstep_mem_${++r}`;
774
+ return t.push({
775
+ id: s,
776
+ runId: e,
777
+ stepName: n,
778
+ attempt: i,
779
+ status: "running",
780
+ input: a ?? null,
781
+ retryPolicy: o ?? null,
782
+ output: null,
783
+ errorTag: null,
784
+ errorMessage: null,
785
+ errorCause: null,
786
+ startedAt: /* @__PURE__ */ new Date(),
787
+ completedAt: null,
788
+ durationMs: null
789
+ }), s;
790
+ },
791
+ endStepSuccess: async ({ stepRecordId: e, output: n, durationMs: r }) => {
792
+ let i = t.find((t) => t.id === e);
793
+ i !== void 0 && (i.status = "succeeded", i.output = n, i.completedAt = /* @__PURE__ */ new Date(), i.durationMs = r);
794
+ },
795
+ endStepFailure: async ({ stepRecordId: e, errorTag: n, errorMessage: r, errorCause: i, durationMs: a }) => {
796
+ let o = t.find((t) => t.id === e);
797
+ o !== void 0 && (o.status = "failed", o.errorTag = n, o.errorMessage = r, o.errorCause = i ?? null, o.completedAt = /* @__PURE__ */ new Date(), o.durationMs = a);
798
+ },
799
+ recordEvent: async ({ runId: e, eventType: t, payload: r, stepName: a, attempt: o }) => {
800
+ let s = `wfev_mem_${++i}`;
801
+ return n.push({
802
+ id: s,
803
+ runId: e,
804
+ eventType: t,
805
+ payload: r ?? null,
806
+ stepName: a ?? null,
807
+ attempt: o ?? null,
808
+ occurredAt: /* @__PURE__ */ new Date()
809
+ }), { id: s };
810
+ }
811
+ }),
812
+ readSteps: () => t,
813
+ readEvents: () => n
814
+ };
815
+ };
816
+ //#endregion
817
+ export { j as _, Y as a, O as b, ae as c, z as d, F as f, N as g, ie as h, X as i, H as l, re as m, pe as n, J as o, I as p, ue as r, se as s, me as t, U as u, A as v, D as x, k as y };