@nagi-js/core 0.1.1-rc.20 → 0.1.1-rc.22
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.
- package/dist/{chunk-VQTYTI6X.js → chunk-PUAV56FC.js} +922 -519
- package/dist/chunk-PUAV56FC.js.map +1 -0
- package/dist/index.d.ts +90 -115
- package/dist/index.js +693 -1390
- package/dist/index.js.map +1 -1
- package/dist/testing.d.ts +2 -1
- package/dist/testing.js +675 -214
- package/dist/testing.js.map +1 -1
- package/dist/{types-DFSYjJE3.d.ts → types-Ct5xHI4W.d.ts} +119 -125
- package/package.json +1 -1
- package/dist/chunk-VQTYTI6X.js.map +0 -1
|
@@ -72,42 +72,6 @@ function isStepTerminal(s) {
|
|
|
72
72
|
return s.tag === "completed" || s.tag === "failed" || s.tag === "skipped" || s.tag === "canceled";
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
-
// src/retry.ts
|
|
76
|
-
var DEFAULT_RETRY = {
|
|
77
|
-
maxAttempts: 3,
|
|
78
|
-
backoff: "exponential",
|
|
79
|
-
initialDelayMs: 1e3,
|
|
80
|
-
maxDelayMs: 6e4
|
|
81
|
-
};
|
|
82
|
-
function resolveRetry(handlerPolicy, runtimeDefault) {
|
|
83
|
-
return handlerPolicy ?? runtimeDefault ?? DEFAULT_RETRY;
|
|
84
|
-
}
|
|
85
|
-
function stepBackoff(policy) {
|
|
86
|
-
const initial = policy.initialDelayMs ?? DEFAULT_RETRY.initialDelayMs;
|
|
87
|
-
const max = policy.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs;
|
|
88
|
-
return (attempt) => {
|
|
89
|
-
switch (policy.backoff) {
|
|
90
|
-
case "exponential":
|
|
91
|
-
return Math.min(initial * 2 ** Math.max(0, attempt - 1), max);
|
|
92
|
-
case "linear":
|
|
93
|
-
return Math.min(initial * Math.max(1, attempt), max);
|
|
94
|
-
case "fixed":
|
|
95
|
-
return Math.min(initial, max);
|
|
96
|
-
}
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
var MAX_DEQUEUE_BACKOFF_MS = 3e4;
|
|
100
|
-
var MIN_DEQUEUE_BACKOFF_MS = 50;
|
|
101
|
-
function dequeueBackoff(pollIntervalMs) {
|
|
102
|
-
const base = Math.max(pollIntervalMs, MIN_DEQUEUE_BACKOFF_MS);
|
|
103
|
-
return (consecutiveFailures) => Math.min(base * 2 ** (consecutiveFailures - 1), MAX_DEQUEUE_BACKOFF_MS);
|
|
104
|
-
}
|
|
105
|
-
var SNAPSHOT_GONE_DELIVERY_BUDGET = 60;
|
|
106
|
-
var MAX_SNAPSHOT_GONE_BACKOFF_MS = 3e5;
|
|
107
|
-
var snapshotGoneBackoff = (readCount) => Math.min(readCount * readCount * 1e3, MAX_SNAPSHOT_GONE_BACKOFF_MS);
|
|
108
|
-
var defaultSnapshotGonePolicy = (readCount) => readCount > SNAPSHOT_GONE_DELIVERY_BUDGET ? { action: "fail" } : { action: "retry", delayMs: snapshotGoneBackoff(readCount) };
|
|
109
|
-
var reapBackoff = () => 0;
|
|
110
|
-
|
|
111
75
|
// src/internal.ts
|
|
112
76
|
function isOptional(ref) {
|
|
113
77
|
return "__optional" in ref;
|
|
@@ -151,15 +115,23 @@ function peekDef(step) {
|
|
|
151
115
|
return step[DEF];
|
|
152
116
|
}
|
|
153
117
|
function handlerDef(def) {
|
|
154
|
-
|
|
118
|
+
switch (def.kind) {
|
|
119
|
+
case "task":
|
|
120
|
+
case "activity":
|
|
121
|
+
case "streaming":
|
|
122
|
+
return def;
|
|
123
|
+
case "signal":
|
|
124
|
+
case "subflow":
|
|
125
|
+
return void 0;
|
|
126
|
+
}
|
|
155
127
|
}
|
|
156
128
|
function needsStepIds(def) {
|
|
157
129
|
return Object.values(def.needs).map((ref) => ref.step.id);
|
|
158
130
|
}
|
|
159
|
-
function resolveNeeds(def,
|
|
131
|
+
function resolveNeeds(def, state) {
|
|
160
132
|
const result = {};
|
|
161
133
|
for (const [localKey, ref] of Object.entries(def.needs)) {
|
|
162
|
-
const resolved =
|
|
134
|
+
const resolved = resolvedOf(stepStateOf(state, ref.step.id));
|
|
163
135
|
result[localKey] = ref.optional ? resolved : unwrap(resolved);
|
|
164
136
|
}
|
|
165
137
|
return result;
|
|
@@ -167,15 +139,6 @@ function resolveNeeds(def, loadResolved) {
|
|
|
167
139
|
function asStepMapWithDefs(steps) {
|
|
168
140
|
return steps;
|
|
169
141
|
}
|
|
170
|
-
function selectArm(def, args) {
|
|
171
|
-
for (const arm of def.arms) {
|
|
172
|
-
if (arm.guard.kind === "otherwise") return arm.id;
|
|
173
|
-
if (arm.guard.when(args)) return arm.id;
|
|
174
|
-
}
|
|
175
|
-
throw new Error(
|
|
176
|
-
`match: no arm matched and no { otherwise: true } fallback was provided`
|
|
177
|
-
);
|
|
178
|
-
}
|
|
179
142
|
|
|
180
143
|
// src/errors.ts
|
|
181
144
|
var NagiValidationError = class extends Error {
|
|
@@ -241,6 +204,27 @@ var NagiSignalTimeoutError = class extends Error {
|
|
|
241
204
|
this.fireAt = fireAt;
|
|
242
205
|
}
|
|
243
206
|
};
|
|
207
|
+
var NagiStepTimeoutError = class extends Error {
|
|
208
|
+
runId;
|
|
209
|
+
stepId;
|
|
210
|
+
attempt;
|
|
211
|
+
timeoutMs;
|
|
212
|
+
constructor({
|
|
213
|
+
runId,
|
|
214
|
+
stepId,
|
|
215
|
+
attempt,
|
|
216
|
+
timeoutMs
|
|
217
|
+
}) {
|
|
218
|
+
super(
|
|
219
|
+
`Step "${stepId}" (run ${runId}, attempt ${attempt}) exceeded its ${timeoutMs}ms deadline \u2014 ctx.signal aborted.`
|
|
220
|
+
);
|
|
221
|
+
this.name = "NagiStepTimeoutError";
|
|
222
|
+
this.runId = runId;
|
|
223
|
+
this.stepId = stepId;
|
|
224
|
+
this.attempt = attempt;
|
|
225
|
+
this.timeoutMs = timeoutMs;
|
|
226
|
+
}
|
|
227
|
+
};
|
|
244
228
|
var NagiFlowSnapshotGoneError = class extends Error {
|
|
245
229
|
runId;
|
|
246
230
|
flowId;
|
|
@@ -310,6 +294,9 @@ function serializeError(err) {
|
|
|
310
294
|
}
|
|
311
295
|
|
|
312
296
|
// src/facts/flow.ts
|
|
297
|
+
function isRunEnd(fact) {
|
|
298
|
+
return fact.kind === "flow.completed" || fact.kind === "flow.failed" || fact.kind === "flow.canceled";
|
|
299
|
+
}
|
|
313
300
|
var flowFacts = {
|
|
314
301
|
flowStarted(a) {
|
|
315
302
|
return {
|
|
@@ -368,15 +355,10 @@ function runCancelCause(fact) {
|
|
|
368
355
|
reason: fact.reason,
|
|
369
356
|
...compact({ note: fact.note })
|
|
370
357
|
};
|
|
371
|
-
case "operator":
|
|
372
|
-
return {
|
|
373
|
-
kind: "operator",
|
|
374
|
-
actor: fact.actor,
|
|
375
|
-
reason: fact.reason,
|
|
376
|
-
...compact({ note: fact.note })
|
|
377
|
-
};
|
|
378
358
|
}
|
|
379
359
|
}
|
|
360
|
+
var RELEASE_RUN = { tag: "release-run" };
|
|
361
|
+
var CLOSE_RUN = { tag: "close-run" };
|
|
380
362
|
var flowKinds = {
|
|
381
363
|
"flow.started": {
|
|
382
364
|
fold: (draft, fact) => {
|
|
@@ -396,7 +378,10 @@ var flowKinds = {
|
|
|
396
378
|
flowHash: fact.flowHash ?? null,
|
|
397
379
|
codeVersion: fact.codeVersion ?? null,
|
|
398
380
|
parent: fact.parent ?? null
|
|
399
|
-
})
|
|
381
|
+
}),
|
|
382
|
+
release: null,
|
|
383
|
+
stream: null,
|
|
384
|
+
event: (fact) => ({ type: "flow.started", flowId: fact.flowId })
|
|
400
385
|
},
|
|
401
386
|
"flow.completed": {
|
|
402
387
|
fold: (draft, fact) => {
|
|
@@ -407,7 +392,12 @@ var flowKinds = {
|
|
|
407
392
|
status: "completed",
|
|
408
393
|
output: fact.output,
|
|
409
394
|
completedAt: fact.at
|
|
410
|
-
})
|
|
395
|
+
}),
|
|
396
|
+
release: () => RELEASE_RUN,
|
|
397
|
+
// Closes every still-open channel of the run, so a subscriber to a skipped
|
|
398
|
+
// or never-emitting step never hangs.
|
|
399
|
+
stream: () => CLOSE_RUN,
|
|
400
|
+
event: (fact) => ({ type: "flow.completed", output: fact.output })
|
|
411
401
|
},
|
|
412
402
|
"flow.failed": {
|
|
413
403
|
fold: (draft, fact) => {
|
|
@@ -418,7 +408,10 @@ var flowKinds = {
|
|
|
418
408
|
status: "failed",
|
|
419
409
|
error: fact.error,
|
|
420
410
|
completedAt: fact.at
|
|
421
|
-
})
|
|
411
|
+
}),
|
|
412
|
+
release: () => RELEASE_RUN,
|
|
413
|
+
stream: () => CLOSE_RUN,
|
|
414
|
+
event: (fact) => ({ type: "flow.failed", error: fact.error })
|
|
422
415
|
},
|
|
423
416
|
"flow.canceled": {
|
|
424
417
|
fold: (draft, fact) => {
|
|
@@ -429,7 +422,14 @@ var flowKinds = {
|
|
|
429
422
|
status: "canceled",
|
|
430
423
|
canceledByRunId: fact.cause === "concurrency" ? fact.canceledByRunId : null,
|
|
431
424
|
completedAt: fact.at
|
|
432
|
-
})
|
|
425
|
+
}),
|
|
426
|
+
release: () => RELEASE_RUN,
|
|
427
|
+
stream: () => CLOSE_RUN,
|
|
428
|
+
event: (fact) => fact.cause === "concurrency" ? {
|
|
429
|
+
type: "flow.canceled",
|
|
430
|
+
cause: "concurrency",
|
|
431
|
+
canceledByRunId: fact.canceledByRunId
|
|
432
|
+
} : { type: "flow.canceled", cause: fact.cause }
|
|
433
433
|
}
|
|
434
434
|
};
|
|
435
435
|
|
|
@@ -448,10 +448,21 @@ var leaseFacts = {
|
|
|
448
448
|
}
|
|
449
449
|
};
|
|
450
450
|
var leaseKinds = {
|
|
451
|
-
//
|
|
452
|
-
//
|
|
453
|
-
|
|
454
|
-
|
|
451
|
+
// The reaper re-enqueues at attempt+1; the projection updates when the next
|
|
452
|
+
// attempt writes its step.started/step.failed. Only the reaped attempt's
|
|
453
|
+
// lease goes: a newer attempt may already hold its own.
|
|
454
|
+
"lease.reaped": {
|
|
455
|
+
fold: () => {
|
|
456
|
+
},
|
|
457
|
+
rows: null,
|
|
458
|
+
release: (fact) => ({
|
|
459
|
+
tag: "release-lease",
|
|
460
|
+
stepId: fact.stepId,
|
|
461
|
+
attempt: fact.attempt
|
|
462
|
+
}),
|
|
463
|
+
stream: null,
|
|
464
|
+
event: null
|
|
465
|
+
}
|
|
455
466
|
};
|
|
456
467
|
|
|
457
468
|
// src/facts/signal.ts
|
|
@@ -485,7 +496,10 @@ var signalKinds = {
|
|
|
485
496
|
fold: (draft, fact) => {
|
|
486
497
|
delete draft.bufferedSignals[fact.stepId];
|
|
487
498
|
},
|
|
488
|
-
rows: null
|
|
499
|
+
rows: null,
|
|
500
|
+
release: null,
|
|
501
|
+
stream: null,
|
|
502
|
+
event: null
|
|
489
503
|
},
|
|
490
504
|
"signal.buffered": {
|
|
491
505
|
// First buffered signal per step wins, mirroring the happy path where the
|
|
@@ -498,7 +512,10 @@ var signalKinds = {
|
|
|
498
512
|
};
|
|
499
513
|
}
|
|
500
514
|
},
|
|
501
|
-
rows: null
|
|
515
|
+
rows: null,
|
|
516
|
+
release: null,
|
|
517
|
+
stream: null,
|
|
518
|
+
event: null
|
|
502
519
|
}
|
|
503
520
|
};
|
|
504
521
|
|
|
@@ -545,8 +562,7 @@ var stepFacts = {
|
|
|
545
562
|
runId: a.runId,
|
|
546
563
|
stepId: a.stepId,
|
|
547
564
|
reason: a.reason,
|
|
548
|
-
at: a.at
|
|
549
|
-
...compact({ actor: a.actor, note: a.note })
|
|
565
|
+
at: a.at
|
|
550
566
|
};
|
|
551
567
|
},
|
|
552
568
|
stepReset(a) {
|
|
@@ -557,8 +573,7 @@ var stepFacts = {
|
|
|
557
573
|
at: a.at,
|
|
558
574
|
...compact({
|
|
559
575
|
cascadedFrom: a.cascadedFrom,
|
|
560
|
-
|
|
561
|
-
note: a.note
|
|
576
|
+
scope: a.scope === "cascade" ? void 0 : a.scope
|
|
562
577
|
})
|
|
563
578
|
};
|
|
564
579
|
},
|
|
@@ -568,13 +583,8 @@ var stepFacts = {
|
|
|
568
583
|
runId: a.runId,
|
|
569
584
|
stepId: a.stepId,
|
|
570
585
|
attempt: a.attempt,
|
|
571
|
-
|
|
572
|
-
at: a.at,
|
|
573
|
-
...compact({ note: a.note })
|
|
586
|
+
at: a.at
|
|
574
587
|
};
|
|
575
|
-
},
|
|
576
|
-
matchArmSelected(runId, stepId, arm, at) {
|
|
577
|
-
return { kind: "match.arm-selected", runId, stepId, arm, at };
|
|
578
588
|
}
|
|
579
589
|
};
|
|
580
590
|
function startTarget(stepKind, attempt) {
|
|
@@ -586,16 +596,21 @@ function startTarget(stepKind, attempt) {
|
|
|
586
596
|
case "task":
|
|
587
597
|
case "activity":
|
|
588
598
|
case "streaming":
|
|
589
|
-
case "match":
|
|
590
599
|
return { tag: "running", attempt };
|
|
591
600
|
}
|
|
592
601
|
}
|
|
602
|
+
function releaseStep(stepId, timer) {
|
|
603
|
+
return { tag: "release-step", stepId, timer };
|
|
604
|
+
}
|
|
605
|
+
function inFlight(prev, attempt) {
|
|
606
|
+
return (prev.tag === "running" || prev.tag === "awaitingSignal" || prev.tag === "awaitingChild" || prev.tag === "aborting") && prev.attempt === attempt;
|
|
607
|
+
}
|
|
593
608
|
var stepKinds = {
|
|
594
609
|
"step.started": {
|
|
595
610
|
fold: (draft, fact) => foldStep(
|
|
596
611
|
draft,
|
|
597
612
|
fact.stepId,
|
|
598
|
-
(prev) => prev
|
|
613
|
+
(prev) => !isStepTerminal(prev) && fact.attempt > attemptOf(prev) ? startTarget(fact.stepKind, fact.attempt) : prev
|
|
599
614
|
),
|
|
600
615
|
rows: (fact) => ({
|
|
601
616
|
row: "step",
|
|
@@ -603,6 +618,13 @@ var stepKinds = {
|
|
|
603
618
|
stepId: fact.stepId,
|
|
604
619
|
attempt: fact.attempt,
|
|
605
620
|
startedAt: fact.at
|
|
621
|
+
}),
|
|
622
|
+
release: null,
|
|
623
|
+
stream: null,
|
|
624
|
+
event: (fact) => ({
|
|
625
|
+
type: "step.started",
|
|
626
|
+
stepId: fact.stepId,
|
|
627
|
+
attempt: fact.attempt
|
|
606
628
|
})
|
|
607
629
|
},
|
|
608
630
|
"step.completed": {
|
|
@@ -616,6 +638,15 @@ var stepKinds = {
|
|
|
616
638
|
status: "completed",
|
|
617
639
|
stepId: fact.stepId,
|
|
618
640
|
attempt: fact.attempt,
|
|
641
|
+
output: fact.output,
|
|
642
|
+
completedAt: fact.at
|
|
643
|
+
}),
|
|
644
|
+
release: (fact) => releaseStep(fact.stepId, true),
|
|
645
|
+
stream: (fact) => ({ tag: "close-ok", stepId: fact.stepId }),
|
|
646
|
+
event: (fact) => ({
|
|
647
|
+
type: "step.completed",
|
|
648
|
+
stepId: fact.stepId,
|
|
649
|
+
attempt: fact.attempt,
|
|
619
650
|
output: fact.output
|
|
620
651
|
})
|
|
621
652
|
},
|
|
@@ -630,6 +661,20 @@ var stepKinds = {
|
|
|
630
661
|
status: "failed",
|
|
631
662
|
stepId: fact.stepId,
|
|
632
663
|
attempt: fact.attempt,
|
|
664
|
+
error: fact.error,
|
|
665
|
+
completedAt: fact.at
|
|
666
|
+
}),
|
|
667
|
+
release: (fact) => releaseStep(fact.stepId, false),
|
|
668
|
+
// Only written on terminal failure (retries use step.retried).
|
|
669
|
+
stream: (fact) => ({
|
|
670
|
+
tag: "close-error",
|
|
671
|
+
stepId: fact.stepId,
|
|
672
|
+
error: fact.error
|
|
673
|
+
}),
|
|
674
|
+
event: (fact) => ({
|
|
675
|
+
type: "step.failed",
|
|
676
|
+
stepId: fact.stepId,
|
|
677
|
+
attempt: fact.attempt,
|
|
633
678
|
error: fact.error
|
|
634
679
|
})
|
|
635
680
|
},
|
|
@@ -644,65 +689,88 @@ var stepKinds = {
|
|
|
644
689
|
status: "canceled",
|
|
645
690
|
stepId: fact.stepId,
|
|
646
691
|
attempt: fact.attempt,
|
|
647
|
-
error: fact.error ?? null
|
|
648
|
-
|
|
692
|
+
error: fact.error ?? null,
|
|
693
|
+
completedAt: fact.at
|
|
694
|
+
}),
|
|
695
|
+
release: (fact) => releaseStep(fact.stepId, false),
|
|
696
|
+
stream: null,
|
|
697
|
+
event: null
|
|
649
698
|
},
|
|
650
699
|
"step.retried": {
|
|
651
700
|
fold: (draft, fact) => foldStep(
|
|
652
701
|
draft,
|
|
653
702
|
fact.stepId,
|
|
654
|
-
(prev) => prev.
|
|
703
|
+
(prev) => inFlight(prev, fact.attempt) ? {
|
|
655
704
|
tag: "backoff",
|
|
656
705
|
failedAttempt: fact.attempt,
|
|
657
706
|
retryAt: fact.nextAttemptAt,
|
|
658
707
|
error: fact.error
|
|
659
708
|
} : prev
|
|
660
709
|
),
|
|
661
|
-
rows:
|
|
710
|
+
rows: (fact) => ({
|
|
711
|
+
row: "step",
|
|
712
|
+
status: "backoff",
|
|
713
|
+
stepId: fact.stepId,
|
|
714
|
+
attempt: fact.attempt,
|
|
715
|
+
error: fact.error
|
|
716
|
+
}),
|
|
717
|
+
release: null,
|
|
718
|
+
stream: (fact) => ({
|
|
719
|
+
tag: "retry",
|
|
720
|
+
stepId: fact.stepId,
|
|
721
|
+
nextAttempt: fact.attempt + 1
|
|
722
|
+
}),
|
|
723
|
+
// Carries the attempt that FAILED; the next one is attempt + 1.
|
|
724
|
+
event: (fact) => ({
|
|
725
|
+
type: "step.retried",
|
|
726
|
+
stepId: fact.stepId,
|
|
727
|
+
attempt: fact.attempt
|
|
728
|
+
})
|
|
662
729
|
},
|
|
663
730
|
"step.skipped": {
|
|
664
|
-
// An operator may skip an in-flight step, not just a pending one.
|
|
665
731
|
fold: (draft, fact) => foldStep(
|
|
666
732
|
draft,
|
|
667
733
|
fact.stepId,
|
|
668
734
|
(prev) => isStepTerminal(prev) ? prev : { tag: "skipped", reason: fact.reason }
|
|
669
735
|
),
|
|
670
|
-
rows: (fact) => ({
|
|
736
|
+
rows: (fact) => ({
|
|
737
|
+
row: "step",
|
|
738
|
+
status: "skipped",
|
|
739
|
+
stepId: fact.stepId,
|
|
740
|
+
completedAt: fact.at
|
|
741
|
+
}),
|
|
742
|
+
release: null,
|
|
743
|
+
stream: null,
|
|
744
|
+
event: (fact) => ({
|
|
745
|
+
type: "step.skipped",
|
|
746
|
+
stepId: fact.stepId,
|
|
747
|
+
reason: fact.reason
|
|
748
|
+
})
|
|
671
749
|
},
|
|
672
750
|
"step.reset": {
|
|
673
751
|
fold: (draft, fact) => {
|
|
674
752
|
draft.steps[fact.stepId] = PENDING;
|
|
675
|
-
|
|
753
|
+
draft.resetCounts[fact.stepId] = (draft.resetCounts[fact.stepId] ?? 0) + 1;
|
|
676
754
|
delete draft.bufferedSignals[fact.stepId];
|
|
677
755
|
if (draft.phase.tag === "completed" || draft.phase.tag === "failed") {
|
|
678
756
|
draft.phase = { tag: "running" };
|
|
679
757
|
}
|
|
680
758
|
},
|
|
681
|
-
rows: (fact) => ({ row: "step", status: "reset", stepId: fact.stepId })
|
|
759
|
+
rows: (fact) => ({ row: "step", status: "reset", stepId: fact.stepId }),
|
|
760
|
+
release: (fact) => releaseStep(fact.stepId, true),
|
|
761
|
+
stream: null,
|
|
762
|
+
event: null
|
|
682
763
|
},
|
|
683
764
|
"step.abort-requested": {
|
|
684
765
|
fold: (draft, fact) => foldStep(
|
|
685
766
|
draft,
|
|
686
767
|
fact.stepId,
|
|
687
|
-
(prev) => prev
|
|
768
|
+
(prev) => inFlight(prev, fact.attempt) && prev.tag !== "aborting" ? { tag: "aborting", attempt: fact.attempt } : prev
|
|
688
769
|
),
|
|
689
|
-
rows: null
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
draft.selectedArms[fact.stepId] = fact.arm;
|
|
694
|
-
},
|
|
695
|
-
rows: null
|
|
696
|
-
},
|
|
697
|
-
"once.recorded": {
|
|
698
|
-
fold: () => {
|
|
699
|
-
},
|
|
700
|
-
rows: (fact) => ({
|
|
701
|
-
row: "once",
|
|
702
|
-
stepId: fact.stepId,
|
|
703
|
-
scope: fact.scope,
|
|
704
|
-
value: fact.value
|
|
705
|
-
})
|
|
770
|
+
rows: null,
|
|
771
|
+
release: null,
|
|
772
|
+
stream: null,
|
|
773
|
+
event: null
|
|
706
774
|
}
|
|
707
775
|
};
|
|
708
776
|
|
|
@@ -731,8 +799,8 @@ function foldRun(runId, facts) {
|
|
|
731
799
|
flowHash: void 0,
|
|
732
800
|
codeVersion: void 0,
|
|
733
801
|
steps: {},
|
|
734
|
-
|
|
735
|
-
|
|
802
|
+
bufferedSignals: {},
|
|
803
|
+
resetCounts: {}
|
|
736
804
|
};
|
|
737
805
|
for (const fact of facts) armOf(fact.kind)?.fold(draft, fact);
|
|
738
806
|
const { parent, flowHash, codeVersion, ...projected } = draft;
|
|
@@ -743,9 +811,51 @@ function foldRun(runId, facts) {
|
|
|
743
811
|
...compact({ parent, flowHash, codeVersion })
|
|
744
812
|
};
|
|
745
813
|
}
|
|
746
|
-
function
|
|
747
|
-
|
|
814
|
+
function factConsequences(fact) {
|
|
815
|
+
const arm = armOf(fact.kind);
|
|
816
|
+
return {
|
|
817
|
+
rows: arm?.rows?.(fact) ?? null,
|
|
818
|
+
release: arm?.release?.(fact) ?? null,
|
|
819
|
+
stream: arm?.stream?.(fact) ?? null,
|
|
820
|
+
event: arm?.event?.(fact) ?? null
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
// src/retry.ts
|
|
825
|
+
var DEFAULT_RETRY = {
|
|
826
|
+
maxAttempts: 3,
|
|
827
|
+
backoff: "exponential",
|
|
828
|
+
initialDelayMs: 1e3,
|
|
829
|
+
maxDelayMs: 6e4
|
|
830
|
+
};
|
|
831
|
+
function resolveRetry(handlerPolicy, runtimeDefault) {
|
|
832
|
+
return handlerPolicy ?? runtimeDefault ?? DEFAULT_RETRY;
|
|
833
|
+
}
|
|
834
|
+
function stepBackoff(policy) {
|
|
835
|
+
const initial = policy.initialDelayMs ?? DEFAULT_RETRY.initialDelayMs;
|
|
836
|
+
const max = policy.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs;
|
|
837
|
+
return (attempt) => {
|
|
838
|
+
switch (policy.backoff) {
|
|
839
|
+
case "exponential":
|
|
840
|
+
return Math.min(initial * 2 ** Math.max(0, attempt - 1), max);
|
|
841
|
+
case "linear":
|
|
842
|
+
return Math.min(initial * Math.max(1, attempt), max);
|
|
843
|
+
case "fixed":
|
|
844
|
+
return Math.min(initial, max);
|
|
845
|
+
}
|
|
846
|
+
};
|
|
847
|
+
}
|
|
848
|
+
var MAX_DEQUEUE_BACKOFF_MS = 3e4;
|
|
849
|
+
var MIN_DEQUEUE_BACKOFF_MS = 50;
|
|
850
|
+
function dequeueBackoff(pollIntervalMs) {
|
|
851
|
+
const base = Math.max(pollIntervalMs, MIN_DEQUEUE_BACKOFF_MS);
|
|
852
|
+
return (consecutiveFailures) => Math.min(base * 2 ** (consecutiveFailures - 1), MAX_DEQUEUE_BACKOFF_MS);
|
|
748
853
|
}
|
|
854
|
+
var SNAPSHOT_GONE_DELIVERY_BUDGET = 60;
|
|
855
|
+
var MAX_SNAPSHOT_GONE_BACKOFF_MS = 3e5;
|
|
856
|
+
var snapshotGoneBackoff = (readCount) => Math.min(readCount * readCount * 1e3, MAX_SNAPSHOT_GONE_BACKOFF_MS);
|
|
857
|
+
var defaultSnapshotGonePolicy = (readCount) => readCount > SNAPSHOT_GONE_DELIVERY_BUDGET ? { action: "fail" } : { action: "retry", delayMs: snapshotGoneBackoff(readCount) };
|
|
858
|
+
var reapBackoff = () => 0;
|
|
749
859
|
|
|
750
860
|
// src/lease-reaper.ts
|
|
751
861
|
function decideExpiredLeaseAction(args) {
|
|
@@ -760,10 +870,382 @@ function decideExpiredLeaseAction(args) {
|
|
|
760
870
|
return { tag: "skip", reason: "still-live" };
|
|
761
871
|
}
|
|
762
872
|
const nextAttempt = lease.attempt + 1;
|
|
763
|
-
|
|
873
|
+
const { runId, stepId, attempt } = lease;
|
|
874
|
+
return {
|
|
875
|
+
tag: "reap",
|
|
876
|
+
fact: Facts.leaseReaped({ runId, stepId, attempt, at: now, reapedAt: now }),
|
|
877
|
+
nextAttempt,
|
|
878
|
+
backoffMs: reapBackoff()
|
|
879
|
+
};
|
|
764
880
|
}
|
|
765
881
|
var DEFAULT_REAPER_INTERVAL_MS = 3e4;
|
|
766
882
|
|
|
883
|
+
// src/run-events.ts
|
|
884
|
+
function isTerminalRunEvent(event) {
|
|
885
|
+
return event.type === "flow.completed" || event.type === "flow.failed" || event.type === "flow.canceled";
|
|
886
|
+
}
|
|
887
|
+
var InMemoryRunEventHub = class {
|
|
888
|
+
perRun = /* @__PURE__ */ new Map();
|
|
889
|
+
all = /* @__PURE__ */ new Set();
|
|
890
|
+
publish(envelope) {
|
|
891
|
+
const targeted = this.perRun.get(envelope.runId);
|
|
892
|
+
if (targeted !== void 0) {
|
|
893
|
+
for (const h of [...targeted]) safely(h, envelope);
|
|
894
|
+
}
|
|
895
|
+
for (const h of [...this.all]) safely(h, envelope);
|
|
896
|
+
if (targeted !== void 0 && isTerminalRunEvent(envelope)) {
|
|
897
|
+
this.perRun.delete(envelope.runId);
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
watchRun(runId, handler) {
|
|
901
|
+
let set = this.perRun.get(runId);
|
|
902
|
+
if (set === void 0) {
|
|
903
|
+
set = /* @__PURE__ */ new Set();
|
|
904
|
+
this.perRun.set(runId, set);
|
|
905
|
+
}
|
|
906
|
+
set.add(handler);
|
|
907
|
+
return () => {
|
|
908
|
+
const current = this.perRun.get(runId);
|
|
909
|
+
if (current === void 0) return;
|
|
910
|
+
current.delete(handler);
|
|
911
|
+
if (current.size === 0) this.perRun.delete(runId);
|
|
912
|
+
};
|
|
913
|
+
}
|
|
914
|
+
watchRuns(handler) {
|
|
915
|
+
this.all.add(handler);
|
|
916
|
+
return () => {
|
|
917
|
+
this.all.delete(handler);
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
};
|
|
921
|
+
function safely(handler, envelope) {
|
|
922
|
+
try {
|
|
923
|
+
handler(envelope);
|
|
924
|
+
} catch {
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
// src/canonicalize.ts
|
|
929
|
+
var warnedAboutSourceHash = false;
|
|
930
|
+
function warnSourceHashOnce() {
|
|
931
|
+
if (warnedAboutSourceHash) return;
|
|
932
|
+
warnedAboutSourceHash = true;
|
|
933
|
+
console.warn(
|
|
934
|
+
"[nagi] canonicalize: hashing `when`/schema source via Function.prototype.toString(). Cosmetic source changes (minification, whitespace, identifier renames) will flip the flow hash even when behavior is unchanged."
|
|
935
|
+
);
|
|
936
|
+
}
|
|
937
|
+
async function canonicalize(flow) {
|
|
938
|
+
const withDefs = asStepMapWithDefs(flow.steps);
|
|
939
|
+
const ids = Object.keys(withDefs).sort();
|
|
940
|
+
const steps = [];
|
|
941
|
+
for (const id of ids) {
|
|
942
|
+
const step = withDefs[id];
|
|
943
|
+
if (step === void 0) continue;
|
|
944
|
+
steps.push(await canonicalizeStep(id, getDef(step)));
|
|
945
|
+
}
|
|
946
|
+
return {
|
|
947
|
+
flowId: flow.id,
|
|
948
|
+
inputSchema: await canonicalizeSchema(flow.input),
|
|
949
|
+
steps
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
async function canonicalizeStep(id, def) {
|
|
953
|
+
const needs = [...needsStepIds(def)].sort();
|
|
954
|
+
const base = { id, kind: def.kind, needs };
|
|
955
|
+
switch (def.kind) {
|
|
956
|
+
// Streaming and activity hash like a task: chunks are ephemeral and the
|
|
957
|
+
// tx boundary is execution, not DAG shape. `kind` alone tells them apart.
|
|
958
|
+
case "task":
|
|
959
|
+
case "activity":
|
|
960
|
+
case "streaming":
|
|
961
|
+
return canonicalizeHandler(base, def);
|
|
962
|
+
case "signal":
|
|
963
|
+
return canonicalizeSignal(base, def);
|
|
964
|
+
case "subflow":
|
|
965
|
+
return canonicalizeSubflow(base, def);
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
async function applyGuardAndTimeout(out, def) {
|
|
969
|
+
if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
|
|
970
|
+
if (def.timeoutMs !== void 0 && def.timeoutMs !== "unbounded")
|
|
971
|
+
out.timeoutMs = def.timeoutMs;
|
|
972
|
+
}
|
|
973
|
+
async function canonicalizeHandler(base, def) {
|
|
974
|
+
const out = { ...base };
|
|
975
|
+
await applyGuardAndTimeout(out, def);
|
|
976
|
+
if (def.retry !== void 0) out.retry = normalizeRetry(def.retry);
|
|
977
|
+
return out;
|
|
978
|
+
}
|
|
979
|
+
async function canonicalizeSignal(base, def) {
|
|
980
|
+
const out = { ...base };
|
|
981
|
+
await applyGuardAndTimeout(out, def);
|
|
982
|
+
out.signalSchema = await canonicalizeSchema(def.schema);
|
|
983
|
+
if (def.names !== void 0) {
|
|
984
|
+
out.signalNames = [...def.names].sort();
|
|
985
|
+
}
|
|
986
|
+
return out;
|
|
987
|
+
}
|
|
988
|
+
async function canonicalizeSubflow(base, def) {
|
|
989
|
+
const out = { ...base };
|
|
990
|
+
await applyGuardAndTimeout(out, def);
|
|
991
|
+
out.childFlowId = def.childFlowId;
|
|
992
|
+
out.subflowInputHash = await hashFnSource(def.buildInput);
|
|
993
|
+
return out;
|
|
994
|
+
}
|
|
995
|
+
function normalizeRetry(retry) {
|
|
996
|
+
return {
|
|
997
|
+
maxAttempts: retry.maxAttempts,
|
|
998
|
+
backoff: retry.backoff,
|
|
999
|
+
initialDelayMs: retry.initialDelayMs ?? DEFAULT_RETRY.initialDelayMs,
|
|
1000
|
+
maxDelayMs: retry.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs
|
|
1001
|
+
};
|
|
1002
|
+
}
|
|
1003
|
+
async function canonicalizeSchema(schema) {
|
|
1004
|
+
const props = schema["~standard"];
|
|
1005
|
+
return {
|
|
1006
|
+
vendor: props.vendor,
|
|
1007
|
+
version: props.version,
|
|
1008
|
+
validateHash: await hashFnSource(props.validate)
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
async function hashFnSource(fn) {
|
|
1012
|
+
warnSourceHashOnce();
|
|
1013
|
+
return sha256Hex(fn.toString());
|
|
1014
|
+
}
|
|
1015
|
+
async function sha256Canonical(dag) {
|
|
1016
|
+
return sha256Hex(stableStringify(dag));
|
|
1017
|
+
}
|
|
1018
|
+
async function fingerprintFlows(flows) {
|
|
1019
|
+
const entries = [];
|
|
1020
|
+
for (const f of flows) {
|
|
1021
|
+
const dag = await canonicalize(f);
|
|
1022
|
+
entries.push([f.id, await sha256Canonical(dag)]);
|
|
1023
|
+
}
|
|
1024
|
+
entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
1025
|
+
return sha256Hex(stableStringify(entries));
|
|
1026
|
+
}
|
|
1027
|
+
function stableStringify(value) {
|
|
1028
|
+
if (value === void 0) return "null";
|
|
1029
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
1030
|
+
if (Array.isArray(value)) {
|
|
1031
|
+
return `[${value.map(stableStringify).join(",")}]`;
|
|
1032
|
+
}
|
|
1033
|
+
const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
1034
|
+
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
|
|
1035
|
+
}
|
|
1036
|
+
async function sha256Hex(input) {
|
|
1037
|
+
const bytes = new TextEncoder().encode(input);
|
|
1038
|
+
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
1039
|
+
return hex(new Uint8Array(digest));
|
|
1040
|
+
}
|
|
1041
|
+
function hex(bytes) {
|
|
1042
|
+
let s = "";
|
|
1043
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
1044
|
+
s += bytes[i].toString(16).padStart(2, "0");
|
|
1045
|
+
}
|
|
1046
|
+
return s;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
// src/flows.ts
|
|
1050
|
+
function requireCurrent(resolution) {
|
|
1051
|
+
if (resolution.kind === "current") return resolution.flow;
|
|
1052
|
+
throw resolution.error;
|
|
1053
|
+
}
|
|
1054
|
+
function makeFlowOf(deps) {
|
|
1055
|
+
const { registry, store, emitLog } = deps;
|
|
1056
|
+
return async (runId, drift) => {
|
|
1057
|
+
const resolution = registry.resolve(await store.loadRunState(runId));
|
|
1058
|
+
if (resolution.kind === "current" || drift === "freeze") return resolution;
|
|
1059
|
+
try {
|
|
1060
|
+
return { kind: "current", flow: await registry.synthesize(resolution) };
|
|
1061
|
+
} catch (err) {
|
|
1062
|
+
if (!(err instanceof NagiRuntimeError)) throw err;
|
|
1063
|
+
emitLog({
|
|
1064
|
+
level: "warn",
|
|
1065
|
+
msg: "flowOf: drift synthesis failed \u2014 treating run as snapshot-gone",
|
|
1066
|
+
attrs: {
|
|
1067
|
+
runId: resolution.error.runId,
|
|
1068
|
+
flowId: resolution.error.flowId,
|
|
1069
|
+
pinnedHash: resolution.error.pinnedHash,
|
|
1070
|
+
error: err.message
|
|
1071
|
+
}
|
|
1072
|
+
});
|
|
1073
|
+
return resolution;
|
|
1074
|
+
}
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
function pinRun(runId, flow, flowOf) {
|
|
1078
|
+
const pinned = { kind: "current", flow };
|
|
1079
|
+
return async (id) => id === runId ? pinned : flowOf(id);
|
|
1080
|
+
}
|
|
1081
|
+
async function registerFlows(deps) {
|
|
1082
|
+
const { flows, store, clock } = deps;
|
|
1083
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1084
|
+
const hashById = /* @__PURE__ */ new Map();
|
|
1085
|
+
const streamingStepIds = /* @__PURE__ */ new Set();
|
|
1086
|
+
for (const flow of flows) {
|
|
1087
|
+
if (byId.has(flow.id)) {
|
|
1088
|
+
throw new NagiRuntimeError(
|
|
1089
|
+
`Duplicate flow id "${flow.id}" passed to nagi()`
|
|
1090
|
+
);
|
|
1091
|
+
}
|
|
1092
|
+
byId.set(flow.id, flow);
|
|
1093
|
+
for (const [stepId, step] of Object.entries(
|
|
1094
|
+
asStepMapWithDefs(flow.steps)
|
|
1095
|
+
)) {
|
|
1096
|
+
if (getDef(step).kind !== "streaming") continue;
|
|
1097
|
+
if (store.stream === void 0) {
|
|
1098
|
+
throw new NagiRuntimeError(
|
|
1099
|
+
`Flow "${flow.id}" has a streaming step "${stepId}" (b.streamingTask), but the store has no \`stream\` transport \u2014 it cannot carry ephemeral chunks. The in-memory store always exposes one; postgresStore() needs a \`listener\`. Otherwise remove the streaming step.`
|
|
1100
|
+
);
|
|
1101
|
+
}
|
|
1102
|
+
streamingStepIds.add(stepId);
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
for (const flow of flows) {
|
|
1106
|
+
const dag = await canonicalize(flow);
|
|
1107
|
+
const flowHash = await sha256Canonical(dag);
|
|
1108
|
+
hashById.set(flow.id, flowHash);
|
|
1109
|
+
await store.upsertSnapshot({
|
|
1110
|
+
flowHash,
|
|
1111
|
+
flowId: flow.id,
|
|
1112
|
+
dag
|
|
1113
|
+
});
|
|
1114
|
+
const previousHash = await store.getRef(flow.id);
|
|
1115
|
+
if (previousHash !== flowHash) {
|
|
1116
|
+
await store.setRef(flow.id, flowHash);
|
|
1117
|
+
await store.appendGlobalFact(
|
|
1118
|
+
Facts.flowRefUpdated({
|
|
1119
|
+
flowId: flow.id,
|
|
1120
|
+
from: previousHash,
|
|
1121
|
+
to: flowHash,
|
|
1122
|
+
at: clock.now()
|
|
1123
|
+
})
|
|
1124
|
+
);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
function require2(flowId) {
|
|
1128
|
+
const flow = byId.get(flowId);
|
|
1129
|
+
if (!flow) {
|
|
1130
|
+
throw new NagiRuntimeError(
|
|
1131
|
+
`Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
|
|
1132
|
+
);
|
|
1133
|
+
}
|
|
1134
|
+
return flow;
|
|
1135
|
+
}
|
|
1136
|
+
function hashOf(flowId) {
|
|
1137
|
+
const hash = hashById.get(flowId);
|
|
1138
|
+
if (hash === void 0) {
|
|
1139
|
+
throw new NagiRuntimeError(
|
|
1140
|
+
`Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
|
|
1141
|
+
);
|
|
1142
|
+
}
|
|
1143
|
+
return hash;
|
|
1144
|
+
}
|
|
1145
|
+
function resolve(state) {
|
|
1146
|
+
const { runId, flowId, flowHash: pinnedHash } = state;
|
|
1147
|
+
const live = byId.get(flowId);
|
|
1148
|
+
if (pinnedHash === void 0) {
|
|
1149
|
+
if (live === void 0) {
|
|
1150
|
+
throw new NagiRuntimeError(
|
|
1151
|
+
`Run ${runId} references flow "${flowId}" which is not registered with nagi().`
|
|
1152
|
+
);
|
|
1153
|
+
}
|
|
1154
|
+
return { kind: "current", flow: live };
|
|
1155
|
+
}
|
|
1156
|
+
const currentHash = live === void 0 ? null : hashOf(flowId);
|
|
1157
|
+
if (live !== void 0 && currentHash === pinnedHash) {
|
|
1158
|
+
return { kind: "current", flow: live };
|
|
1159
|
+
}
|
|
1160
|
+
const error = new NagiFlowSnapshotGoneError({
|
|
1161
|
+
runId,
|
|
1162
|
+
flowId,
|
|
1163
|
+
pinnedHash,
|
|
1164
|
+
currentHash
|
|
1165
|
+
});
|
|
1166
|
+
return isTerminalRun(state) ? { kind: "gone-terminal", error, live } : { kind: "gone-live", error, live };
|
|
1167
|
+
}
|
|
1168
|
+
const synthesizedByHash = /* @__PURE__ */ new Map();
|
|
1169
|
+
function synthesize(gone) {
|
|
1170
|
+
const { pinnedHash } = gone.error;
|
|
1171
|
+
const cached = synthesizedByHash.get(pinnedHash);
|
|
1172
|
+
if (cached !== void 0) return cached;
|
|
1173
|
+
const pending = synthesizeUncached(gone);
|
|
1174
|
+
synthesizedByHash.set(pinnedHash, pending);
|
|
1175
|
+
pending.catch(() => synthesizedByHash.delete(pinnedHash));
|
|
1176
|
+
return pending;
|
|
1177
|
+
}
|
|
1178
|
+
async function synthesizeUncached(gone) {
|
|
1179
|
+
const { runId, flowId, pinnedHash } = gone.error;
|
|
1180
|
+
if (gone.live === void 0) {
|
|
1181
|
+
throw new NagiRuntimeError(
|
|
1182
|
+
`Run ${runId} references flow "${flowId}" which is not registered with nagi().`
|
|
1183
|
+
);
|
|
1184
|
+
}
|
|
1185
|
+
const snapshot = await store.loadSnapshot(pinnedHash);
|
|
1186
|
+
if (snapshot === null) {
|
|
1187
|
+
throw new NagiRuntimeError(
|
|
1188
|
+
`Run ${runId} pinned to flow hash ${pinnedHash.slice(0, 12)}\u2026 but no snapshot with that hash was found. Nothing can resume it.`
|
|
1189
|
+
);
|
|
1190
|
+
}
|
|
1191
|
+
return synthesizeReplayFlow(
|
|
1192
|
+
snapshot.dag,
|
|
1193
|
+
gone.live
|
|
1194
|
+
);
|
|
1195
|
+
}
|
|
1196
|
+
return {
|
|
1197
|
+
get: (flowId) => byId.get(flowId),
|
|
1198
|
+
has: (flowId) => byId.has(flowId),
|
|
1199
|
+
require: require2,
|
|
1200
|
+
hashOf,
|
|
1201
|
+
isStreaming: (stepId) => streamingStepIds.has(stepId),
|
|
1202
|
+
resolve,
|
|
1203
|
+
synthesize
|
|
1204
|
+
};
|
|
1205
|
+
}
|
|
1206
|
+
function synthesizeReplayFlow(dag, liveFlow) {
|
|
1207
|
+
const liveSteps = asStepMapWithDefs(liveFlow.steps);
|
|
1208
|
+
const synthesized = {};
|
|
1209
|
+
for (const canonStep of dag.steps) {
|
|
1210
|
+
const liveStep = liveSteps[canonStep.id];
|
|
1211
|
+
if (liveStep === void 0) {
|
|
1212
|
+
throw new NagiRuntimeError(
|
|
1213
|
+
`Drift-allowed replay: step "${canonStep.id}" exists in snapshot but is missing from the live flow "${liveFlow.id}". Cannot synthesize a handler.`
|
|
1214
|
+
);
|
|
1215
|
+
}
|
|
1216
|
+
synthesized[canonStep.id] = attachDef(
|
|
1217
|
+
{ kind: canonStep.kind, id: canonStep.id },
|
|
1218
|
+
getDef(liveStep)
|
|
1219
|
+
);
|
|
1220
|
+
}
|
|
1221
|
+
for (const canonStep of dag.steps) {
|
|
1222
|
+
const shell = synthesized[canonStep.id];
|
|
1223
|
+
if (shell === void 0) continue;
|
|
1224
|
+
const synthesizedNeeds = {};
|
|
1225
|
+
for (const upstreamId of canonStep.needs) {
|
|
1226
|
+
const upstreamShell = synthesized[upstreamId];
|
|
1227
|
+
if (upstreamShell === void 0) {
|
|
1228
|
+
throw new NagiRuntimeError(
|
|
1229
|
+
`Drift-allowed replay: step "${canonStep.id}" needs upstream "${upstreamId}" which the snapshot does not declare.`
|
|
1230
|
+
);
|
|
1231
|
+
}
|
|
1232
|
+
synthesizedNeeds[upstreamId] = upstreamShell;
|
|
1233
|
+
}
|
|
1234
|
+
setDef(shell, { ...getDef(shell), needs: synthesizedNeeds });
|
|
1235
|
+
}
|
|
1236
|
+
return {
|
|
1237
|
+
id: liveFlow.id,
|
|
1238
|
+
input: liveFlow.input,
|
|
1239
|
+
steps: synthesized,
|
|
1240
|
+
...compact({
|
|
1241
|
+
output: liveFlow.output,
|
|
1242
|
+
onStart: liveFlow.onStart,
|
|
1243
|
+
onComplete: liveFlow.onComplete,
|
|
1244
|
+
onError: liveFlow.onError
|
|
1245
|
+
})
|
|
1246
|
+
};
|
|
1247
|
+
}
|
|
1248
|
+
|
|
767
1249
|
// src/validate.ts
|
|
768
1250
|
async function validate(schema, value) {
|
|
769
1251
|
const result = await schema["~standard"].validate(value);
|
|
@@ -839,10 +1321,9 @@ function decideTimeout(args) {
|
|
|
839
1321
|
};
|
|
840
1322
|
}
|
|
841
1323
|
function makeSignals(deps) {
|
|
842
|
-
const { dispatcher, store, clock,
|
|
1324
|
+
const { dispatcher, store, clock, flowOf, hooks, flowHooks, emitLog } = deps;
|
|
843
1325
|
async function signal(runId, signalName, payload) {
|
|
844
|
-
const
|
|
845
|
-
const flow = registry.require(runState.flowId);
|
|
1326
|
+
const flow = requireCurrent(await flowOf(runId));
|
|
846
1327
|
const resolved = resolveSignalStep(flow, signalName);
|
|
847
1328
|
if (resolved === null) {
|
|
848
1329
|
throw new NagiRuntimeError(
|
|
@@ -915,59 +1396,6 @@ function resolveSignalStep(flow, signalName) {
|
|
|
915
1396
|
}
|
|
916
1397
|
|
|
917
1398
|
// src/store-policy.ts
|
|
918
|
-
var QUERY_RUNS_DEFAULT_LIMIT = 50;
|
|
919
|
-
var QUERY_RUNS_MAX_LIMIT = 500;
|
|
920
|
-
function clampQueryLimit(limit) {
|
|
921
|
-
if (limit === void 0) return QUERY_RUNS_DEFAULT_LIMIT;
|
|
922
|
-
if (!Number.isInteger(limit) || limit < 1) return QUERY_RUNS_DEFAULT_LIMIT;
|
|
923
|
-
return Math.min(limit, QUERY_RUNS_MAX_LIMIT);
|
|
924
|
-
}
|
|
925
|
-
function compareRunOrder(a, b) {
|
|
926
|
-
const t = b.startedAt.getTime() - a.startedAt.getTime();
|
|
927
|
-
if (t !== 0) return t;
|
|
928
|
-
return a.runId < b.runId ? 1 : a.runId > b.runId ? -1 : 0;
|
|
929
|
-
}
|
|
930
|
-
function isPastCursor(row, cursor) {
|
|
931
|
-
return compareRunOrder(row, cursor) > 0;
|
|
932
|
-
}
|
|
933
|
-
function encodeRunCursor(c) {
|
|
934
|
-
const bytes = new TextEncoder().encode(
|
|
935
|
-
JSON.stringify({ t: c.startedAt.getTime(), r: c.runId })
|
|
936
|
-
);
|
|
937
|
-
let binary = "";
|
|
938
|
-
for (const b of bytes) binary += String.fromCharCode(b);
|
|
939
|
-
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
940
|
-
}
|
|
941
|
-
function decodeRunCursor(s) {
|
|
942
|
-
try {
|
|
943
|
-
const binary = atob(s.replace(/-/g, "+").replace(/_/g, "/"));
|
|
944
|
-
const bytes = Uint8Array.from(binary, (ch) => ch.charCodeAt(0));
|
|
945
|
-
const parsed = JSON.parse(new TextDecoder().decode(bytes));
|
|
946
|
-
if (typeof parsed === "object" && parsed !== null && typeof parsed.t === "number" && typeof parsed.r === "string") {
|
|
947
|
-
const { t, r } = parsed;
|
|
948
|
-
return { startedAt: new Date(t), runId: r };
|
|
949
|
-
}
|
|
950
|
-
throw new Error("malformed cursor body");
|
|
951
|
-
} catch (err) {
|
|
952
|
-
throw new Error(
|
|
953
|
-
`queryRuns: invalid cursor \u2014 ${err instanceof Error ? err.message : String(err)}`
|
|
954
|
-
);
|
|
955
|
-
}
|
|
956
|
-
}
|
|
957
|
-
function jsonContains(haystack, needle) {
|
|
958
|
-
if (Array.isArray(needle)) {
|
|
959
|
-
if (!Array.isArray(haystack)) return false;
|
|
960
|
-
return needle.every((n) => haystack.some((h) => jsonContains(h, n)));
|
|
961
|
-
}
|
|
962
|
-
if (needle !== null && typeof needle === "object") {
|
|
963
|
-
if (haystack === null || Array.isArray(haystack) || typeof haystack !== "object")
|
|
964
|
-
return false;
|
|
965
|
-
return Object.entries(needle).every(
|
|
966
|
-
([k, v]) => k in haystack && jsonContains(haystack[k], v)
|
|
967
|
-
);
|
|
968
|
-
}
|
|
969
|
-
return haystack === needle;
|
|
970
|
-
}
|
|
971
1399
|
var DEFAULT_SWEEP_LIMIT = 100;
|
|
972
1400
|
function selectExpired(items, args) {
|
|
973
1401
|
const nowMs = args.now.getTime();
|
|
@@ -992,35 +1420,29 @@ function selectPruneBatch(candidates, opts) {
|
|
|
992
1420
|
);
|
|
993
1421
|
return eligible.slice(0, opts.batchSize).map((e) => e.item);
|
|
994
1422
|
}
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
case "step.retried":
|
|
1012
|
-
case "step.skipped":
|
|
1013
|
-
case "step.abort-requested":
|
|
1014
|
-
case "signal.received":
|
|
1015
|
-
case "signal.buffered":
|
|
1016
|
-
case "once.recorded":
|
|
1017
|
-
case "match.arm-selected":
|
|
1018
|
-
case "lease.reaped":
|
|
1019
|
-
return NONE;
|
|
1423
|
+
function admitsRunEnd(status) {
|
|
1424
|
+
return status === "pending" || status === "running";
|
|
1425
|
+
}
|
|
1426
|
+
function supersede(args) {
|
|
1427
|
+
const { start, concurrency } = args;
|
|
1428
|
+
switch (concurrency.mode) {
|
|
1429
|
+
case "cancel-in-progress":
|
|
1430
|
+
return Array.from(args.priors, (runId) => ({
|
|
1431
|
+
runId,
|
|
1432
|
+
fact: Facts.flowCanceledByConcurrency({
|
|
1433
|
+
runId,
|
|
1434
|
+
canceledByRunId: start.runId,
|
|
1435
|
+
concurrencyKey: concurrency.key,
|
|
1436
|
+
at: start.at
|
|
1437
|
+
})
|
|
1438
|
+
}));
|
|
1020
1439
|
}
|
|
1021
1440
|
}
|
|
1022
1441
|
|
|
1023
1442
|
// src/stream-hub.ts
|
|
1443
|
+
function isStreamOver(state, stepId) {
|
|
1444
|
+
return isTerminalRun(state) || isStepTerminal(stepStateOf(state, stepId));
|
|
1445
|
+
}
|
|
1024
1446
|
var STREAM_SUBSCRIBER_BUFFER_CAP = 256;
|
|
1025
1447
|
var STREAM_REPLAY_BUFFER_CAP = 256;
|
|
1026
1448
|
function makeWake() {
|
|
@@ -1081,81 +1503,100 @@ var Subscriber = class {
|
|
|
1081
1503
|
}
|
|
1082
1504
|
}
|
|
1083
1505
|
};
|
|
1506
|
+
var STREAM_CLOSED_KEYS_CAP = 1024;
|
|
1507
|
+
var EMPTY_CLOSED_STREAM = {
|
|
1508
|
+
[Symbol.asyncIterator]() {
|
|
1509
|
+
return { next: async () => ({ value: void 0, done: true }) };
|
|
1510
|
+
}
|
|
1511
|
+
};
|
|
1084
1512
|
var InMemoryStreamHub = class _InMemoryStreamHub {
|
|
1513
|
+
// Open channels only: closing one deletes it and records its key.
|
|
1085
1514
|
channels = /* @__PURE__ */ new Map();
|
|
1515
|
+
closedKeys = /* @__PURE__ */ new Set();
|
|
1086
1516
|
static key(runId, stepId) {
|
|
1087
1517
|
return `${runId}::${stepId}`;
|
|
1088
1518
|
}
|
|
1089
|
-
|
|
1090
|
-
|
|
1519
|
+
openChannel(key) {
|
|
1520
|
+
if (this.closedKeys.has(key)) return void 0;
|
|
1091
1521
|
let channel = this.channels.get(key);
|
|
1092
1522
|
if (channel === void 0) {
|
|
1093
|
-
channel = { subscribers: /* @__PURE__ */ new Set(), replay: []
|
|
1523
|
+
channel = { subscribers: /* @__PURE__ */ new Set(), replay: [] };
|
|
1094
1524
|
this.channels.set(key, channel);
|
|
1095
1525
|
}
|
|
1096
1526
|
return channel;
|
|
1097
1527
|
}
|
|
1528
|
+
// Returns the subscribers to end, or undefined when no channel was open.
|
|
1529
|
+
closeChannel(key) {
|
|
1530
|
+
const channel = this.channels.get(key);
|
|
1531
|
+
if (channel === void 0) return void 0;
|
|
1532
|
+
this.channels.delete(key);
|
|
1533
|
+
this.closedKeys.add(key);
|
|
1534
|
+
if (this.closedKeys.size > STREAM_CLOSED_KEYS_CAP) {
|
|
1535
|
+
const oldest = this.closedKeys.values().next().value;
|
|
1536
|
+
if (oldest !== void 0) this.closedKeys.delete(oldest);
|
|
1537
|
+
}
|
|
1538
|
+
const subs = [...channel.subscribers];
|
|
1539
|
+
channel.subscribers.clear();
|
|
1540
|
+
channel.replay.length = 0;
|
|
1541
|
+
return subs;
|
|
1542
|
+
}
|
|
1098
1543
|
publishChunk(runId, stepId, chunk) {
|
|
1099
|
-
const channel = this.
|
|
1100
|
-
if (channel
|
|
1544
|
+
const channel = this.openChannel(_InMemoryStreamHub.key(runId, stepId));
|
|
1545
|
+
if (channel === void 0) return;
|
|
1101
1546
|
const event = { kind: "chunk", chunk };
|
|
1102
1547
|
channel.replay.push(event);
|
|
1103
1548
|
if (channel.replay.length > STREAM_REPLAY_BUFFER_CAP)
|
|
1104
1549
|
channel.replay.shift();
|
|
1105
1550
|
for (const sub of channel.subscribers) sub.push(event);
|
|
1106
1551
|
}
|
|
1552
|
+
// NB: signalRetry and the close* methods are no-ops when no channel exists.
|
|
1553
|
+
// Both adapters fire them for EVERY step — Postgres cluster-wide — including
|
|
1554
|
+
// non-streaming ones, so creating a channel here would leak one per step.
|
|
1107
1555
|
signalRetry(runId, stepId, attempt) {
|
|
1108
|
-
const channel = this.
|
|
1109
|
-
if (channel
|
|
1556
|
+
const channel = this.channels.get(_InMemoryStreamHub.key(runId, stepId));
|
|
1557
|
+
if (channel === void 0) return;
|
|
1110
1558
|
channel.replay.length = 0;
|
|
1111
1559
|
const event = { kind: "retry", attempt };
|
|
1112
1560
|
for (const sub of channel.subscribers) sub.push(event);
|
|
1113
1561
|
}
|
|
1114
|
-
// NB: no-op when no channel exists. InMemoryStore.appendFact fires this for
|
|
1115
|
-
// EVERY step.completed — including non-streaming steps that never published —
|
|
1116
|
-
// so creating a channel here would leak one per such step. Closed-ness is
|
|
1117
|
-
// authoritative in the durable facts, not the hub.
|
|
1118
1562
|
closeOk(runId, stepId) {
|
|
1119
|
-
const
|
|
1120
|
-
|
|
1121
|
-
channel.closed = true;
|
|
1122
|
-
channel.replay.length = 0;
|
|
1123
|
-
for (const sub of channel.subscribers) sub.close();
|
|
1124
|
-
channel.subscribers.clear();
|
|
1563
|
+
const subs = this.closeChannel(_InMemoryStreamHub.key(runId, stepId));
|
|
1564
|
+
for (const sub of subs ?? []) sub.close();
|
|
1125
1565
|
}
|
|
1126
1566
|
closeError(runId, stepId, error) {
|
|
1127
|
-
const
|
|
1128
|
-
if (channel === void 0 || channel.closed) return;
|
|
1129
|
-
channel.closed = true;
|
|
1130
|
-
channel.replay.length = 0;
|
|
1567
|
+
const subs = this.closeChannel(_InMemoryStreamHub.key(runId, stepId));
|
|
1131
1568
|
const event = { kind: "error", error };
|
|
1132
|
-
for (const sub of
|
|
1569
|
+
for (const sub of subs ?? []) {
|
|
1133
1570
|
sub.push(event);
|
|
1134
1571
|
sub.close();
|
|
1135
1572
|
}
|
|
1136
|
-
|
|
1573
|
+
}
|
|
1574
|
+
apply(runId, effect) {
|
|
1575
|
+
switch (effect.tag) {
|
|
1576
|
+
case "close-ok":
|
|
1577
|
+
this.closeOk(runId, effect.stepId);
|
|
1578
|
+
return;
|
|
1579
|
+
case "close-error":
|
|
1580
|
+
this.closeError(runId, effect.stepId, effect.error);
|
|
1581
|
+
return;
|
|
1582
|
+
case "retry":
|
|
1583
|
+
this.signalRetry(runId, effect.stepId, effect.nextAttempt);
|
|
1584
|
+
return;
|
|
1585
|
+
case "close-run":
|
|
1586
|
+
this.closeRun(runId);
|
|
1587
|
+
return;
|
|
1588
|
+
}
|
|
1137
1589
|
}
|
|
1138
1590
|
closeRun(runId) {
|
|
1139
1591
|
const prefix = `${runId}::`;
|
|
1140
|
-
for (const
|
|
1141
|
-
if (!key.startsWith(prefix)
|
|
1142
|
-
|
|
1143
|
-
channel.replay.length = 0;
|
|
1144
|
-
for (const sub of channel.subscribers) sub.close();
|
|
1145
|
-
channel.subscribers.clear();
|
|
1592
|
+
for (const key of this.channels.keys()) {
|
|
1593
|
+
if (!key.startsWith(prefix)) continue;
|
|
1594
|
+
for (const sub of this.closeChannel(key) ?? []) sub.close();
|
|
1146
1595
|
}
|
|
1147
1596
|
}
|
|
1148
1597
|
subscribeStream(runId, stepId, opts) {
|
|
1149
|
-
const channel = this.
|
|
1150
|
-
if (channel
|
|
1151
|
-
return {
|
|
1152
|
-
[Symbol.asyncIterator]() {
|
|
1153
|
-
return {
|
|
1154
|
-
next: async () => ({ value: void 0, done: true })
|
|
1155
|
-
};
|
|
1156
|
-
}
|
|
1157
|
-
};
|
|
1158
|
-
}
|
|
1598
|
+
const channel = this.openChannel(_InMemoryStreamHub.key(runId, stepId));
|
|
1599
|
+
if (channel === void 0) return EMPTY_CLOSED_STREAM;
|
|
1159
1600
|
const sub = new Subscriber();
|
|
1160
1601
|
if (opts?.replayBuffered === true) {
|
|
1161
1602
|
for (const event of channel.replay) sub.push(event);
|
|
@@ -1186,6 +1627,111 @@ var InMemoryStreamHub = class _InMemoryStreamHub {
|
|
|
1186
1627
|
}
|
|
1187
1628
|
};
|
|
1188
1629
|
|
|
1630
|
+
// src/read-model.ts
|
|
1631
|
+
var SETTLED = /* @__PURE__ */ new Set([
|
|
1632
|
+
"completed",
|
|
1633
|
+
"failed",
|
|
1634
|
+
"canceled",
|
|
1635
|
+
"skipped"
|
|
1636
|
+
]);
|
|
1637
|
+
function nextRunRow(prev, delta) {
|
|
1638
|
+
if (delta.row === "step") {
|
|
1639
|
+
return delta.status === "reset" && prev !== void 0 && (prev.status === "completed" || prev.status === "failed") ? {
|
|
1640
|
+
...prev,
|
|
1641
|
+
status: "running",
|
|
1642
|
+
output: null,
|
|
1643
|
+
error: null,
|
|
1644
|
+
completedAt: null
|
|
1645
|
+
} : prev;
|
|
1646
|
+
}
|
|
1647
|
+
switch (delta.status) {
|
|
1648
|
+
case "running":
|
|
1649
|
+
return prev ?? {
|
|
1650
|
+
flowId: delta.flowId,
|
|
1651
|
+
status: "running",
|
|
1652
|
+
input: delta.input,
|
|
1653
|
+
output: null,
|
|
1654
|
+
error: null,
|
|
1655
|
+
startedAt: delta.startedAt,
|
|
1656
|
+
completedAt: null,
|
|
1657
|
+
flowHash: delta.flowHash,
|
|
1658
|
+
codeVersion: delta.codeVersion,
|
|
1659
|
+
parent: delta.parent,
|
|
1660
|
+
canceledByRunId: null
|
|
1661
|
+
};
|
|
1662
|
+
case "completed":
|
|
1663
|
+
return prev && {
|
|
1664
|
+
...prev,
|
|
1665
|
+
status: "completed",
|
|
1666
|
+
output: delta.output,
|
|
1667
|
+
error: null,
|
|
1668
|
+
completedAt: delta.completedAt
|
|
1669
|
+
};
|
|
1670
|
+
case "failed":
|
|
1671
|
+
return prev && {
|
|
1672
|
+
...prev,
|
|
1673
|
+
status: "failed",
|
|
1674
|
+
output: null,
|
|
1675
|
+
error: delta.error,
|
|
1676
|
+
completedAt: delta.completedAt
|
|
1677
|
+
};
|
|
1678
|
+
case "canceled":
|
|
1679
|
+
return prev && {
|
|
1680
|
+
...prev,
|
|
1681
|
+
status: "canceled",
|
|
1682
|
+
output: null,
|
|
1683
|
+
error: null,
|
|
1684
|
+
canceledByRunId: delta.canceledByRunId,
|
|
1685
|
+
completedAt: delta.completedAt
|
|
1686
|
+
};
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
function nextStepRow(prev, delta) {
|
|
1690
|
+
if (delta.status === "reset") return void 0;
|
|
1691
|
+
if (prev !== void 0 && SETTLED.has(prev.status)) return prev;
|
|
1692
|
+
switch (delta.status) {
|
|
1693
|
+
case "running":
|
|
1694
|
+
if (prev !== void 0 && prev.attempt >= delta.attempt) return prev;
|
|
1695
|
+
return {
|
|
1696
|
+
attempt: delta.attempt,
|
|
1697
|
+
status: "running",
|
|
1698
|
+
startedAt: delta.startedAt,
|
|
1699
|
+
completedAt: null,
|
|
1700
|
+
output: null,
|
|
1701
|
+
error: null
|
|
1702
|
+
};
|
|
1703
|
+
case "backoff":
|
|
1704
|
+
if (prev === void 0 || prev.error !== null || prev.attempt !== delta.attempt) {
|
|
1705
|
+
return prev;
|
|
1706
|
+
}
|
|
1707
|
+
return { ...prev, error: delta.error };
|
|
1708
|
+
case "completed":
|
|
1709
|
+
return settle(prev, delta.attempt, delta, delta.output, null);
|
|
1710
|
+
case "failed":
|
|
1711
|
+
return settle(prev, delta.attempt, delta, null, delta.error);
|
|
1712
|
+
case "canceled":
|
|
1713
|
+
return settle(prev, delta.attempt, delta, null, delta.error);
|
|
1714
|
+
case "skipped":
|
|
1715
|
+
return settle(
|
|
1716
|
+
prev,
|
|
1717
|
+
prev?.attempt ?? 0,
|
|
1718
|
+
delta,
|
|
1719
|
+
null,
|
|
1720
|
+
null
|
|
1721
|
+
);
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
function settle(prev, attempt, delta, output, error) {
|
|
1725
|
+
return {
|
|
1726
|
+
attempt,
|
|
1727
|
+
status: delta.status,
|
|
1728
|
+
startedAt: prev?.startedAt ?? null,
|
|
1729
|
+
completedAt: delta.completedAt,
|
|
1730
|
+
output,
|
|
1731
|
+
error
|
|
1732
|
+
};
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1189
1735
|
// src/memory.ts
|
|
1190
1736
|
function leaseKey(runId, stepId, attempt) {
|
|
1191
1737
|
return `${runId}::${stepId}::${attempt}`;
|
|
@@ -1205,8 +1751,9 @@ var InMemoryStore = class {
|
|
|
1205
1751
|
keyByActiveRun = /* @__PURE__ */ new Map();
|
|
1206
1752
|
// Kept past terminal facts so a reopened run can re-take its slot.
|
|
1207
1753
|
slotByRun = /* @__PURE__ */ new Map();
|
|
1208
|
-
|
|
1209
|
-
|
|
1754
|
+
// The read model (Postgres: workflow_run / step_run), fed only by row deltas.
|
|
1755
|
+
runRows = /* @__PURE__ */ new Map();
|
|
1756
|
+
stepRows = /* @__PURE__ */ new Map();
|
|
1210
1757
|
streamHub = new InMemoryStreamHub();
|
|
1211
1758
|
// Durable signal-timeout deadlines (the Postgres `timer` table), distinct
|
|
1212
1759
|
// from InMemoryClock's setTimeout-based scheduler.
|
|
@@ -1216,6 +1763,18 @@ var InMemoryStore = class {
|
|
|
1216
1763
|
this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
|
|
1217
1764
|
}
|
|
1218
1765
|
async appendFact(runId, fact) {
|
|
1766
|
+
this.writeFact(runId, fact);
|
|
1767
|
+
}
|
|
1768
|
+
async endRun(runId, fact) {
|
|
1769
|
+
return this.writeFact(runId, fact);
|
|
1770
|
+
}
|
|
1771
|
+
// The one fact-write path. Synchronous on purpose: with no await between the
|
|
1772
|
+
// read that led to a write and the write itself, every caller gets the
|
|
1773
|
+
// atomicity the Postgres store takes a transaction for.
|
|
1774
|
+
writeFact(runId, fact) {
|
|
1775
|
+
if (isRunEnd(fact) && !admitsRunEnd(this.runRows.get(runId)?.status)) {
|
|
1776
|
+
return false;
|
|
1777
|
+
}
|
|
1219
1778
|
const list = this.facts.get(runId) ?? [];
|
|
1220
1779
|
if (fact.kind === "step.reset") {
|
|
1221
1780
|
const prior = foldRun(runId, list);
|
|
@@ -1237,36 +1796,34 @@ var InMemoryStore = class {
|
|
|
1237
1796
|
}
|
|
1238
1797
|
list.push(fact);
|
|
1239
1798
|
this.facts.set(runId, list);
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
}
|
|
1260
|
-
const effects = factEffects(fact);
|
|
1261
|
-
switch (effects.tag) {
|
|
1262
|
-
case "none":
|
|
1263
|
-
return;
|
|
1799
|
+
const { rows, release, stream, event } = factConsequences(fact);
|
|
1800
|
+
if (rows !== null) this.applyRows(runId, rows);
|
|
1801
|
+
if (release !== null) this.release(runId, release);
|
|
1802
|
+
if (stream !== null) this.streamHub.apply(runId, stream);
|
|
1803
|
+
if (event !== null) this.eventHub.publish({ ...event, runId });
|
|
1804
|
+
return true;
|
|
1805
|
+
}
|
|
1806
|
+
applyRows(runId, delta) {
|
|
1807
|
+
const run = nextRunRow(this.runRows.get(runId), delta);
|
|
1808
|
+
if (run !== void 0) this.runRows.set(runId, run);
|
|
1809
|
+
if (delta.row === "run") return;
|
|
1810
|
+
const steps = this.stepRows.get(runId) ?? /* @__PURE__ */ new Map();
|
|
1811
|
+
const step = nextStepRow(steps.get(delta.stepId), delta);
|
|
1812
|
+
if (step === void 0) steps.delete(delta.stepId);
|
|
1813
|
+
else steps.set(delta.stepId, step);
|
|
1814
|
+
this.stepRows.set(runId, steps);
|
|
1815
|
+
}
|
|
1816
|
+
release(runId, release) {
|
|
1817
|
+
switch (release.tag) {
|
|
1264
1818
|
case "release-step":
|
|
1265
|
-
this.releaseLeases(runId,
|
|
1266
|
-
if (
|
|
1267
|
-
this.signalTimers.delete(timerKey(runId,
|
|
1819
|
+
this.releaseLeases(runId, release.stepId);
|
|
1820
|
+
if (release.timer) {
|
|
1821
|
+
this.signalTimers.delete(timerKey(runId, release.stepId));
|
|
1268
1822
|
}
|
|
1269
1823
|
return;
|
|
1824
|
+
case "release-lease":
|
|
1825
|
+
this.leases.delete(leaseKey(runId, release.stepId, release.attempt));
|
|
1826
|
+
return;
|
|
1270
1827
|
case "release-run": {
|
|
1271
1828
|
const slot = this.keyByActiveRun.get(runId);
|
|
1272
1829
|
if (slot === void 0) return;
|
|
@@ -1286,63 +1843,48 @@ var InMemoryStore = class {
|
|
|
1286
1843
|
}
|
|
1287
1844
|
}
|
|
1288
1845
|
async tryStartRun(runId, fact, concurrency) {
|
|
1289
|
-
if (this.
|
|
1846
|
+
if (this.runRows.has(runId)) {
|
|
1290
1847
|
return { started: false, canceled: [] };
|
|
1291
1848
|
}
|
|
1292
1849
|
const canceled = [];
|
|
1293
1850
|
if (concurrency !== void 0) {
|
|
1294
1851
|
const slot = `${fact.flowId}::${concurrency.key}`;
|
|
1295
|
-
const
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
});
|
|
1303
|
-
await this.appendFact(priorRunId, cancelFact);
|
|
1304
|
-
canceled.push({ runId: priorRunId, fact: cancelFact });
|
|
1852
|
+
const prior = this.activeByKey.get(slot);
|
|
1853
|
+
for (const c of supersede({
|
|
1854
|
+
start: fact,
|
|
1855
|
+
concurrency,
|
|
1856
|
+
priors: prior === void 0 ? [] : [prior]
|
|
1857
|
+
})) {
|
|
1858
|
+
if (this.writeFact(c.runId, c.fact)) canceled.push(c);
|
|
1305
1859
|
}
|
|
1306
1860
|
this.activeByKey.set(slot, runId);
|
|
1307
1861
|
this.keyByActiveRun.set(runId, slot);
|
|
1308
1862
|
this.slotByRun.set(runId, slot);
|
|
1309
1863
|
}
|
|
1310
|
-
this.
|
|
1311
|
-
const parentRunId = fact.parent?.runId;
|
|
1312
|
-
if (parentRunId !== void 0) {
|
|
1313
|
-
const set = this.childrenByParent.get(parentRunId) ?? /* @__PURE__ */ new Set();
|
|
1314
|
-
set.add(runId);
|
|
1315
|
-
this.childrenByParent.set(parentRunId, set);
|
|
1316
|
-
}
|
|
1864
|
+
this.writeFact(runId, fact);
|
|
1317
1865
|
return { started: true, canceled };
|
|
1318
1866
|
}
|
|
1319
|
-
//
|
|
1320
|
-
//
|
|
1321
|
-
//
|
|
1867
|
+
// No real tx to join: every write here is visible, and announced, the moment
|
|
1868
|
+
// it happens, and nothing the caller does later can roll it back. Events stay
|
|
1869
|
+
// exactly as durable as the facts they report.
|
|
1322
1870
|
async tryStartRunOnTx(_tx, runId, fact, concurrency) {
|
|
1323
1871
|
return this.tryStartRun(runId, fact, concurrency);
|
|
1324
1872
|
}
|
|
1325
1873
|
async listChildren(parentRunId) {
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1874
|
+
return this.childRows(parentRunId).map(([runId]) => runId);
|
|
1875
|
+
}
|
|
1876
|
+
childRows(parentRunId) {
|
|
1877
|
+
return [...this.runRows].filter(
|
|
1878
|
+
([, row]) => row.parent?.runId === parentRunId
|
|
1879
|
+
);
|
|
1329
1880
|
}
|
|
1330
1881
|
// Does a non-terminal child exist for this (parentRunId, stepId)? Used by the
|
|
1331
1882
|
// reaper to leave a subflow step parked while its child still runs (instead
|
|
1332
|
-
// of re-dispatching it at attempt+1).
|
|
1333
|
-
// only, so filter on the child's parent.stepId.
|
|
1883
|
+
// of re-dispatching it at attempt+1).
|
|
1334
1884
|
hasActiveChild(parentRunId, parentStepId) {
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
const factList = this.facts.get(childId);
|
|
1339
|
-
if (factList === void 0) continue;
|
|
1340
|
-
const child = foldRun(childId, factList);
|
|
1341
|
-
if (child.parent?.stepId === parentStepId && !isTerminalRun(child)) {
|
|
1342
|
-
return true;
|
|
1343
|
-
}
|
|
1344
|
-
}
|
|
1345
|
-
return false;
|
|
1885
|
+
return this.childRows(parentRunId).some(
|
|
1886
|
+
([, row]) => row.parent?.stepId === parentStepId && (row.status === "pending" || row.status === "running")
|
|
1887
|
+
);
|
|
1346
1888
|
}
|
|
1347
1889
|
async loadRunState(runId) {
|
|
1348
1890
|
return foldRun(runId, this.facts.get(runId) ?? []);
|
|
@@ -1380,9 +1922,7 @@ var InMemoryStore = class {
|
|
|
1380
1922
|
});
|
|
1381
1923
|
for (const lease of candidates) {
|
|
1382
1924
|
const { runId, stepId, attempt } = lease;
|
|
1383
|
-
const
|
|
1384
|
-
const state = factList ? foldRun(runId, factList) : null;
|
|
1385
|
-
const stepStatus = state ? stepStatusOf(stepStateOf(state, stepId)) : "pending";
|
|
1925
|
+
const flowId = this.runRows.get(runId)?.flowId;
|
|
1386
1926
|
const decision = decideExpiredLeaseAction({
|
|
1387
1927
|
lease: {
|
|
1388
1928
|
runId,
|
|
@@ -1390,21 +1930,24 @@ var InMemoryStore = class {
|
|
|
1390
1930
|
attempt,
|
|
1391
1931
|
expiresAt: new Date(lease.expiresAt)
|
|
1392
1932
|
},
|
|
1393
|
-
stepStatus,
|
|
1933
|
+
stepStatus: this.stepRows.get(runId)?.get(stepId)?.status ?? "pending",
|
|
1394
1934
|
childActive: this.hasActiveChild(runId, stepId),
|
|
1395
1935
|
now
|
|
1396
1936
|
});
|
|
1397
1937
|
if (decision.tag === "skip") continue;
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1938
|
+
const key = leaseKey(runId, stepId, attempt);
|
|
1939
|
+
this.leases.delete(key);
|
|
1940
|
+
try {
|
|
1941
|
+
await queue.enqueue(runId, stepId, {
|
|
1942
|
+
attempt: decision.nextAttempt,
|
|
1943
|
+
delayMs: decision.backoffMs,
|
|
1944
|
+
...flowId !== void 0 ? { flowId } : {}
|
|
1945
|
+
});
|
|
1946
|
+
} catch (err) {
|
|
1947
|
+
this.leases.set(key, lease);
|
|
1948
|
+
throw err;
|
|
1949
|
+
}
|
|
1950
|
+
this.writeFact(runId, decision.fact);
|
|
1408
1951
|
reaped.push({
|
|
1409
1952
|
runId,
|
|
1410
1953
|
stepId,
|
|
@@ -1414,9 +1957,6 @@ var InMemoryStore = class {
|
|
|
1414
1957
|
}
|
|
1415
1958
|
return reaped;
|
|
1416
1959
|
}
|
|
1417
|
-
async settleStep(runId, _stepId, fact) {
|
|
1418
|
-
await this.appendFact(runId, fact);
|
|
1419
|
-
}
|
|
1420
1960
|
async settleSignal(args) {
|
|
1421
1961
|
const { runId, stepId, at, incoming } = args;
|
|
1422
1962
|
const runState = foldRun(runId, this.facts.get(runId) ?? []);
|
|
@@ -1425,11 +1965,11 @@ var InMemoryStore = class {
|
|
|
1425
1965
|
case "noop":
|
|
1426
1966
|
return decision.result;
|
|
1427
1967
|
case "buffer":
|
|
1428
|
-
if (decision.fact !== null)
|
|
1968
|
+
if (decision.fact !== null) this.writeFact(runId, decision.fact);
|
|
1429
1969
|
return decision.result;
|
|
1430
1970
|
case "deliver":
|
|
1431
|
-
|
|
1432
|
-
|
|
1971
|
+
this.writeFact(runId, decision.received);
|
|
1972
|
+
this.writeFact(runId, decision.completed);
|
|
1433
1973
|
return decision.result;
|
|
1434
1974
|
}
|
|
1435
1975
|
}
|
|
@@ -1452,7 +1992,7 @@ var InMemoryStore = class {
|
|
|
1452
1992
|
const decision = decideTimeout({ runState, stepId, fireAt, at: now });
|
|
1453
1993
|
this.signalTimers.delete(timerKey(runId, stepId));
|
|
1454
1994
|
if (decision.kind === "noop") continue;
|
|
1455
|
-
|
|
1995
|
+
this.writeFact(runId, decision.fact);
|
|
1456
1996
|
timedOut.push({ runId, stepId, attempt: decision.attempt, fireAt });
|
|
1457
1997
|
}
|
|
1458
1998
|
return timedOut;
|
|
@@ -1462,11 +2002,12 @@ var InMemoryStore = class {
|
|
|
1462
2002
|
if (!this.onces.has(key)) this.onces.set(key, value);
|
|
1463
2003
|
}
|
|
1464
2004
|
async getOnce(runId, stepId, scope) {
|
|
1465
|
-
|
|
2005
|
+
const value = this.onces.get(`${runId}::${stepId}::${scope}`);
|
|
2006
|
+
return value === void 0 ? { tag: "miss" } : { tag: "hit", value };
|
|
1466
2007
|
}
|
|
1467
2008
|
async runStep(runId, _stepId, _attempt, body) {
|
|
1468
2009
|
const result = await body(void 0);
|
|
1469
|
-
|
|
2010
|
+
this.writeFact(runId, result.fact);
|
|
1470
2011
|
return result.output;
|
|
1471
2012
|
}
|
|
1472
2013
|
async upsertSnapshot(args) {
|
|
@@ -1488,162 +2029,44 @@ var InMemoryStore = class {
|
|
|
1488
2029
|
readGlobalFacts() {
|
|
1489
2030
|
return this.globalFacts;
|
|
1490
2031
|
}
|
|
1491
|
-
async queryRuns(opts) {
|
|
1492
|
-
const where = opts.where ?? {};
|
|
1493
|
-
const wanted = where.status && new Set(where.status);
|
|
1494
|
-
const matches = (summary) => (where.flowId === void 0 || summary.flowId === where.flowId) && (!wanted || wanted.has(summary.status)) && (where.input === void 0 || jsonContains(summary.input, where.input));
|
|
1495
|
-
const summaries = [];
|
|
1496
|
-
for (const [runId, factList] of this.facts) {
|
|
1497
|
-
const summary = summarize(runId, factList);
|
|
1498
|
-
if (summary === null) continue;
|
|
1499
|
-
if (matches(summary)) summaries.push(summary);
|
|
1500
|
-
}
|
|
1501
|
-
for (const summary of this.summaries.values()) {
|
|
1502
|
-
if (matches(summary)) summaries.push(summary);
|
|
1503
|
-
}
|
|
1504
|
-
summaries.sort(compareRunOrder);
|
|
1505
|
-
if (opts.latest === true) {
|
|
1506
|
-
return { runs: summaries.slice(0, 1), cursor: null };
|
|
1507
|
-
}
|
|
1508
|
-
const limit = clampQueryLimit(opts.limit);
|
|
1509
|
-
const cursor = opts.cursor === void 0 ? null : decodeRunCursor(opts.cursor);
|
|
1510
|
-
const rest = cursor === null ? summaries : summaries.filter((s) => isPastCursor(s, cursor));
|
|
1511
|
-
const page = rest.slice(0, limit);
|
|
1512
|
-
const last = page[page.length - 1];
|
|
1513
|
-
const next = rest.length > limit && last !== void 0 ? encodeRunCursor({ startedAt: last.startedAt, runId: last.runId }) : null;
|
|
1514
|
-
return { runs: page, cursor: next };
|
|
1515
|
-
}
|
|
1516
2032
|
async describe(runId) {
|
|
1517
|
-
const
|
|
1518
|
-
if (
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
const
|
|
1522
|
-
if (first === void 0 || first.kind !== "flow.started") return null;
|
|
1523
|
-
const state = foldRun(runId, factList);
|
|
1524
|
-
const status = runStatusOf(state);
|
|
1525
|
-
let completedAt;
|
|
1526
|
-
let output;
|
|
1527
|
-
let error;
|
|
1528
|
-
let canceledByRunId;
|
|
1529
|
-
let concurrencyKey;
|
|
1530
|
-
for (let i = isTerminalRun(state) ? factList.length - 1 : -1; i >= 0; i--) {
|
|
1531
|
-
const f = factList[i];
|
|
1532
|
-
if (f === void 0) continue;
|
|
1533
|
-
if (f.kind === "flow.completed") {
|
|
1534
|
-
completedAt = f.at;
|
|
1535
|
-
output = f.output;
|
|
1536
|
-
break;
|
|
1537
|
-
}
|
|
1538
|
-
if (f.kind === "flow.failed") {
|
|
1539
|
-
completedAt = f.at;
|
|
1540
|
-
error = f.error;
|
|
1541
|
-
break;
|
|
1542
|
-
}
|
|
1543
|
-
if (f.kind === "flow.canceled") {
|
|
1544
|
-
completedAt = f.at;
|
|
1545
|
-
if (f.cause === "concurrency") {
|
|
1546
|
-
canceledByRunId = f.canceledByRunId;
|
|
1547
|
-
}
|
|
1548
|
-
break;
|
|
1549
|
-
}
|
|
1550
|
-
}
|
|
1551
|
-
const slot = this.keyByActiveRun.get(runId);
|
|
1552
|
-
if (slot !== void 0) {
|
|
1553
|
-
const sep = slot.indexOf("::");
|
|
1554
|
-
if (sep >= 0) concurrencyKey = slot.slice(sep + 2);
|
|
1555
|
-
}
|
|
1556
|
-
if (concurrencyKey === void 0) {
|
|
1557
|
-
for (const f of factList) {
|
|
1558
|
-
if (f.kind === "flow.canceled" && f.cause === "concurrency") {
|
|
1559
|
-
concurrencyKey = f.concurrencyKey;
|
|
1560
|
-
break;
|
|
1561
|
-
}
|
|
1562
|
-
}
|
|
1563
|
-
}
|
|
1564
|
-
const childSet = this.childrenByParent.get(runId);
|
|
1565
|
-
const children = childSet ? Array.from(childSet) : [];
|
|
1566
|
-
const parent = first.parent;
|
|
1567
|
-
const run = {
|
|
1568
|
-
runId,
|
|
1569
|
-
flowId: first.flowId,
|
|
1570
|
-
flowHash: first.flowHash ?? "",
|
|
1571
|
-
status,
|
|
1572
|
-
startedAt: first.at,
|
|
1573
|
-
input: first.input,
|
|
1574
|
-
children,
|
|
1575
|
-
...completedAt !== void 0 ? { completedAt } : {},
|
|
1576
|
-
...output !== void 0 ? { output } : {},
|
|
1577
|
-
...error !== void 0 ? { error } : {},
|
|
1578
|
-
...canceledByRunId !== void 0 ? { canceledByRunId } : {},
|
|
1579
|
-
...concurrencyKey !== void 0 ? { concurrencyKey } : {},
|
|
1580
|
-
...parent !== void 0 ? { parent } : {}
|
|
1581
|
-
};
|
|
1582
|
-
const steps = [];
|
|
1583
|
-
const startedAtByStep = /* @__PURE__ */ new Map();
|
|
1584
|
-
const completedAtByStep = /* @__PURE__ */ new Map();
|
|
1585
|
-
for (const f of factList) {
|
|
1586
|
-
if (f.kind === "step.started" && !startedAtByStep.has(f.stepId)) {
|
|
1587
|
-
startedAtByStep.set(f.stepId, f.at);
|
|
1588
|
-
}
|
|
1589
|
-
if ((f.kind === "step.completed" || f.kind === "step.failed" || f.kind === "step.canceled" || f.kind === "step.skipped") && !completedAtByStep.has(f.stepId)) {
|
|
1590
|
-
completedAtByStep.set(f.stepId, f.at);
|
|
1591
|
-
}
|
|
1592
|
-
}
|
|
1593
|
-
const now = Date.now();
|
|
1594
|
-
for (const [stepId, stepState] of Object.entries(state.steps)) {
|
|
1595
|
-
const status2 = stepStatusOf(stepState);
|
|
1596
|
-
const attempt = attemptOf(stepState);
|
|
1597
|
-
const out = outputOf(stepState);
|
|
1598
|
-
const err = errorOf(stepState);
|
|
1599
|
-
const startedAt = startedAtByStep.get(stepId);
|
|
1600
|
-
const completedAt2 = completedAtByStep.get(stepId);
|
|
1601
|
-
let lease;
|
|
1602
|
-
let bestExpiry = 0;
|
|
1603
|
-
for (const l of this.leases.values()) {
|
|
1604
|
-
if (l.runId !== runId || l.stepId !== stepId) continue;
|
|
1605
|
-
if (l.expiresAt > now && l.expiresAt > bestExpiry) {
|
|
1606
|
-
bestExpiry = l.expiresAt;
|
|
1607
|
-
}
|
|
1608
|
-
}
|
|
1609
|
-
if (bestExpiry > 0) lease = { expiresAt: new Date(bestExpiry) };
|
|
1610
|
-
steps.push({
|
|
1611
|
-
stepId,
|
|
1612
|
-
attempt,
|
|
1613
|
-
status: status2,
|
|
1614
|
-
...startedAt !== void 0 ? { startedAt } : {},
|
|
1615
|
-
...completedAt2 !== void 0 ? { completedAt: completedAt2 } : {},
|
|
1616
|
-
...out !== null ? { output: out } : {},
|
|
1617
|
-
...err !== void 0 ? { error: err } : {},
|
|
1618
|
-
...lease !== void 0 ? { lease } : {}
|
|
1619
|
-
});
|
|
1620
|
-
}
|
|
1621
|
-
steps.sort((a, b) => {
|
|
1622
|
-
const ta = a.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
|
|
1623
|
-
const tb = b.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
|
|
1624
|
-
if (ta !== tb) return ta - tb;
|
|
1625
|
-
return a.stepId < b.stepId ? -1 : a.stepId > b.stepId ? 1 : 0;
|
|
1626
|
-
});
|
|
1627
|
-
return { run, steps };
|
|
1628
|
-
}
|
|
1629
|
-
// A run pruned with keepSummary keeps its row in Postgres; the summary is
|
|
1630
|
-
// the in-memory equivalent, so describe() stays non-null for it.
|
|
1631
|
-
describeSummary(runId) {
|
|
1632
|
-
const s = this.summaries.get(runId);
|
|
1633
|
-
if (s === void 0) return null;
|
|
1634
|
-
const childSet = this.childrenByParent.get(runId);
|
|
2033
|
+
const row = this.runRows.get(runId);
|
|
2034
|
+
if (row === void 0) return null;
|
|
2035
|
+
const slot = this.slotByRun.get(runId);
|
|
2036
|
+
const children = this.childRows(runId).sort(([, a], [, b]) => a.startedAt.getTime() - b.startedAt.getTime()).map(([childId]) => childId);
|
|
2037
|
+
const steps = [...this.stepRows.get(runId) ?? []].map(([stepId, step]) => this.stepView(runId, stepId, step)).sort(compareStepOrder);
|
|
1635
2038
|
return {
|
|
1636
2039
|
run: {
|
|
1637
2040
|
runId,
|
|
1638
|
-
flowId:
|
|
1639
|
-
flowHash: "",
|
|
1640
|
-
status:
|
|
1641
|
-
startedAt:
|
|
1642
|
-
input:
|
|
1643
|
-
children
|
|
1644
|
-
...
|
|
2041
|
+
flowId: row.flowId,
|
|
2042
|
+
flowHash: row.flowHash ?? "",
|
|
2043
|
+
status: row.status,
|
|
2044
|
+
startedAt: row.startedAt,
|
|
2045
|
+
input: row.input,
|
|
2046
|
+
children,
|
|
2047
|
+
...row.completedAt !== null ? { completedAt: row.completedAt } : {},
|
|
2048
|
+
...row.output !== null ? { output: row.output } : {},
|
|
2049
|
+
...row.error !== null ? { error: row.error } : {},
|
|
2050
|
+
// Postgres: ON DELETE SET NULL — the view never names a pruned run.
|
|
2051
|
+
...row.canceledByRunId !== null && this.runRows.has(row.canceledByRunId) ? { canceledByRunId: row.canceledByRunId } : {},
|
|
2052
|
+
...slot !== void 0 ? { concurrencyKey: slot.slice(row.flowId.length + 2) } : {},
|
|
2053
|
+
...row.parent !== null ? { parent: row.parent } : {}
|
|
1645
2054
|
},
|
|
1646
|
-
steps
|
|
2055
|
+
steps
|
|
2056
|
+
};
|
|
2057
|
+
}
|
|
2058
|
+
stepView(runId, stepId, row) {
|
|
2059
|
+
const lease = this.leases.get(leaseKey(runId, stepId, row.attempt));
|
|
2060
|
+
const live = lease !== void 0 && lease.expiresAt > Date.now();
|
|
2061
|
+
return {
|
|
2062
|
+
stepId,
|
|
2063
|
+
attempt: row.attempt,
|
|
2064
|
+
status: row.status,
|
|
2065
|
+
...row.startedAt !== null ? { startedAt: row.startedAt } : {},
|
|
2066
|
+
...row.completedAt !== null ? { completedAt: row.completedAt } : {},
|
|
2067
|
+
...row.output !== null ? { output: row.output } : {},
|
|
2068
|
+
...row.error !== null ? { error: row.error } : {},
|
|
2069
|
+
...live ? { lease: { expiresAt: new Date(lease.expiresAt) } } : {}
|
|
1647
2070
|
};
|
|
1648
2071
|
}
|
|
1649
2072
|
async pruneFacts(opts) {
|
|
@@ -1652,24 +2075,15 @@ var InMemoryStore = class {
|
|
|
1652
2075
|
for (; ; ) {
|
|
1653
2076
|
const batch = selectPruneBatch(this.pruneCandidates(), opts);
|
|
1654
2077
|
if (batch.length === 0) break;
|
|
1655
|
-
for (const {
|
|
1656
|
-
const runId = summary.runId;
|
|
2078
|
+
for (const { runId, factCount } of batch) {
|
|
1657
2079
|
this.facts.delete(runId);
|
|
2080
|
+
this.stepRows.delete(runId);
|
|
1658
2081
|
deleteByRunPrefix(this.onces, runId);
|
|
1659
2082
|
deleteByRunPrefix(this.leases, runId);
|
|
1660
2083
|
deleteByRunPrefix(this.signalTimers, runId);
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
if (siblings !== void 0) {
|
|
1665
|
-
siblings.delete(runId);
|
|
1666
|
-
if (siblings.size === 0) this.childrenByParent.delete(parentRunId);
|
|
1667
|
-
}
|
|
1668
|
-
}
|
|
1669
|
-
if (opts.keepSummary) {
|
|
1670
|
-
this.summaries.set(runId, summary);
|
|
1671
|
-
} else {
|
|
1672
|
-
this.summaries.delete(runId);
|
|
2084
|
+
if (!opts.keepSummary) {
|
|
2085
|
+
this.runRows.delete(runId);
|
|
2086
|
+
this.slotByRun.delete(runId);
|
|
1673
2087
|
}
|
|
1674
2088
|
runsPruned += 1;
|
|
1675
2089
|
factsPruned += factCount;
|
|
@@ -1679,22 +2093,27 @@ var InMemoryStore = class {
|
|
|
1679
2093
|
}
|
|
1680
2094
|
pruneCandidates() {
|
|
1681
2095
|
const out = [];
|
|
1682
|
-
for (const [runId,
|
|
1683
|
-
const
|
|
1684
|
-
if (
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
2096
|
+
for (const [runId, row] of this.runRows) {
|
|
2097
|
+
const factList = this.facts.get(runId);
|
|
2098
|
+
if (factList === void 0) continue;
|
|
2099
|
+
out.push({
|
|
2100
|
+
runId,
|
|
2101
|
+
status: row.status,
|
|
2102
|
+
completedAt: row.completedAt,
|
|
2103
|
+
factCount: factList.length
|
|
2104
|
+
});
|
|
1688
2105
|
}
|
|
1689
2106
|
return out;
|
|
1690
2107
|
}
|
|
2108
|
+
eventHub = new InMemoryRunEventHub();
|
|
2109
|
+
events = {
|
|
2110
|
+
watchRun: (runId, handler) => this.eventHub.watchRun(runId, handler),
|
|
2111
|
+
watchRuns: (handler) => this.eventHub.watchRuns(handler)
|
|
2112
|
+
};
|
|
1691
2113
|
stream = {
|
|
1692
2114
|
subscribeStream: (runId, stepId, opts) => {
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
const runIsTerminal = isTerminalRun(state);
|
|
1696
|
-
if (runIsTerminal || stepStatus === "completed" || stepStatus === "failed" || stepStatus === "canceled" || stepStatus === "skipped") {
|
|
1697
|
-
return EMPTY_CLOSED_STREAM;
|
|
2115
|
+
if (isStreamOver(foldRun(runId, this.facts.get(runId) ?? []), stepId)) {
|
|
2116
|
+
return EMPTY_CLOSED_STREAM2;
|
|
1698
2117
|
}
|
|
1699
2118
|
return this.streamHub.subscribeStream(runId, stepId, opts);
|
|
1700
2119
|
},
|
|
@@ -1703,7 +2122,13 @@ var InMemoryStore = class {
|
|
|
1703
2122
|
}
|
|
1704
2123
|
};
|
|
1705
2124
|
};
|
|
1706
|
-
|
|
2125
|
+
function compareStepOrder(a, b) {
|
|
2126
|
+
const ta = a.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
|
|
2127
|
+
const tb = b.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
|
|
2128
|
+
if (ta !== tb) return ta - tb;
|
|
2129
|
+
return a.stepId < b.stepId ? -1 : a.stepId > b.stepId ? 1 : 0;
|
|
2130
|
+
}
|
|
2131
|
+
var EMPTY_CLOSED_STREAM2 = {
|
|
1707
2132
|
[Symbol.asyncIterator]() {
|
|
1708
2133
|
return { next: async () => ({ value: void 0, done: true }) };
|
|
1709
2134
|
}
|
|
@@ -1714,28 +2139,6 @@ function deleteByRunPrefix(map, runId) {
|
|
|
1714
2139
|
if (key.startsWith(prefix)) map.delete(key);
|
|
1715
2140
|
}
|
|
1716
2141
|
}
|
|
1717
|
-
function summarize(runId, facts) {
|
|
1718
|
-
const first = facts[0];
|
|
1719
|
-
if (first === void 0 || first.kind !== "flow.started") return null;
|
|
1720
|
-
const projected = foldRun(runId, facts);
|
|
1721
|
-
let completedAt = null;
|
|
1722
|
-
for (let i = isTerminalRun(projected) ? facts.length - 1 : -1; i >= 0; i--) {
|
|
1723
|
-
const f = facts[i];
|
|
1724
|
-
if (f === void 0) continue;
|
|
1725
|
-
if (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled") {
|
|
1726
|
-
completedAt = f.at;
|
|
1727
|
-
break;
|
|
1728
|
-
}
|
|
1729
|
-
}
|
|
1730
|
-
return {
|
|
1731
|
-
runId,
|
|
1732
|
-
flowId: first.flowId,
|
|
1733
|
-
status: runStatusOf(projected),
|
|
1734
|
-
startedAt: first.at,
|
|
1735
|
-
completedAt,
|
|
1736
|
-
input: first.input
|
|
1737
|
-
};
|
|
1738
|
-
}
|
|
1739
2142
|
var DEFAULT_QUEUE_LEASE_MS = 6e4;
|
|
1740
2143
|
var InMemoryQueue = class {
|
|
1741
2144
|
pending = [];
|
|
@@ -1828,6 +2231,6 @@ var InMemoryClock = class {
|
|
|
1828
2231
|
}
|
|
1829
2232
|
};
|
|
1830
2233
|
|
|
1831
|
-
export { DEFAULT_REAPER_INTERVAL_MS,
|
|
1832
|
-
//# sourceMappingURL=chunk-
|
|
1833
|
-
//# sourceMappingURL=chunk-
|
|
2234
|
+
export { DEFAULT_REAPER_INTERVAL_MS, DEFAULT_SWEEP_LIMIT, Facts, InMemoryClock, InMemoryQueue, InMemoryRunEventHub, InMemoryStore, InMemoryStreamHub, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiStepTimeoutError, NagiValidationError, STREAM_REPLAY_BUFFER_CAP, STREAM_SUBSCRIBER_BUFFER_CAP, admitsRunEnd, asStepMapWithDefs, attachDef, attemptOf, compact, decideExpiredLeaseAction, decideSignal, decideTimeout, defaultSnapshotGonePolicy, dequeueBackoff, errorOf, factConsequences, fingerprintFlows, foldRun, getDef, handlerDef, isAbortRequested, isRunEnd, isStepTerminal, isStreamOver, isTerminalRun, isTerminalRunEvent, makeEmit, makeFlowOf, makeSignals, needsStepIds, normalizeNeeds, outputOf, peekDef, pinRun, registerFlows, requireCurrent, resolveNeeds, resolveRetry, resolvedOf, runCancelCause, runStatusOf, selectExpired, selectPruneBatch, serializeError, stepBackoff, stepStateOf, stepStatusOf, supersede, unwrap, validate, validationError };
|
|
2235
|
+
//# sourceMappingURL=chunk-PUAV56FC.js.map
|
|
2236
|
+
//# sourceMappingURL=chunk-PUAV56FC.js.map
|