deltafold 0.0.0 → 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.
- package/README.md +278 -4
- package/dist/changelog.d.ts +116 -0
- package/dist/changelog.d.ts.map +1 -0
- package/dist/changelog.js +304 -0
- package/dist/changelog.js.map +1 -0
- package/dist/document-BZcZo9nr.js +171 -0
- package/dist/document-BZcZo9nr.js.map +1 -0
- package/dist/document-DWHsgywm.d.ts +257 -0
- package/dist/document-DWHsgywm.d.ts.map +1 -0
- package/dist/html.d.ts +8 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +13 -0
- package/dist/html.js.map +1 -0
- package/dist/index.d.ts +517 -1
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2126 -0
- package/dist/index.js.map +1 -0
- package/dist/markdown.d.ts +8 -0
- package/dist/markdown.d.ts.map +1 -0
- package/dist/markdown.js +16 -0
- package/dist/markdown.js.map +1 -0
- package/dist/mdast-DiRsYwPU.js +108 -0
- package/dist/mdast-DiRsYwPU.js.map +1 -0
- package/dist/package-BfBYnaCz.d.ts +1125 -0
- package/dist/package-BfBYnaCz.d.ts.map +1 -0
- package/dist/rolldown-runtime-D8jQpDG7.js +12 -0
- package/package.json +13 -1
- package/src/features/documents/changelog.ts +450 -0
- package/src/features/documents/document.ts +357 -0
- package/src/features/documents/index.ts +4 -0
- package/src/features/documents/public-document.ts +31 -0
- package/src/features/documents/sections.ts +44 -0
- package/src/features/execution/executor.ts +968 -0
- package/src/features/execution/handler.ts +485 -0
- package/src/features/execution/settlement.ts +52 -0
- package/src/features/package.ts +32 -0
- package/src/features/planning/guide.ts +56 -0
- package/src/features/planning/history.ts +174 -0
- package/src/features/planning/identifiers.ts +43 -0
- package/src/features/planning/resolve-error.ts +201 -0
- package/src/features/planning/resolve.ts +724 -0
- package/src/features/planning/rewrite.ts +331 -0
- package/src/features/planning/validate.ts +388 -0
- package/src/foundation/action.ts +188 -0
- package/src/foundation/change.ts +147 -0
- package/src/foundation/instruction.ts +110 -0
- package/src/foundation/migration.ts +236 -0
- package/src/foundation/plan.ts +245 -0
- package/src/foundation/rule.ts +74 -0
- package/src/foundation/shortcut.ts +79 -0
- package/src/foundation/template.ts +28 -0
- package/src/foundation/version.ts +78 -0
- package/src/index.ts +22 -11
- package/src/renderers/html.ts +12 -0
- package/src/renderers/markdown.ts +12 -0
- package/src/renderers/mdast.ts +120 -0
- package/src/types.ts +2 -0
|
@@ -0,0 +1,968 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Cause,
|
|
3
|
+
Context,
|
|
4
|
+
Data,
|
|
5
|
+
Deferred,
|
|
6
|
+
Duration,
|
|
7
|
+
Effect,
|
|
8
|
+
Equal,
|
|
9
|
+
Exit,
|
|
10
|
+
Fiber,
|
|
11
|
+
Layer,
|
|
12
|
+
Option,
|
|
13
|
+
Scope,
|
|
14
|
+
} from "effect";
|
|
15
|
+
|
|
16
|
+
import type * as Action from "../../foundation/action.ts";
|
|
17
|
+
import type * as Plan from "../../foundation/plan.ts";
|
|
18
|
+
import type { Node, Occurrence } from "../../foundation/plan.ts";
|
|
19
|
+
import * as Handler from "./handler.ts";
|
|
20
|
+
import { SettlementReference } from "./settlement.ts";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* What happened to one occurrence, or what a dry run predicts.
|
|
24
|
+
*
|
|
25
|
+
* @since @next
|
|
26
|
+
*/
|
|
27
|
+
export type Outcome<E = unknown> =
|
|
28
|
+
| { readonly _tag: "Completed" }
|
|
29
|
+
| { readonly _tag: "Skipped"; readonly reason: string }
|
|
30
|
+
| {
|
|
31
|
+
readonly _tag: "Failed";
|
|
32
|
+
readonly phase: Handler.Phase;
|
|
33
|
+
/** The typed failure, when the cause has one. Defects only appear in `cause`. */
|
|
34
|
+
readonly error: E | undefined;
|
|
35
|
+
readonly cause: Cause.Cause<E>;
|
|
36
|
+
}
|
|
37
|
+
| {
|
|
38
|
+
readonly _tag: "Interrupted";
|
|
39
|
+
readonly phase: Handler.Phase;
|
|
40
|
+
/** `handler`: an Effect handler interrupted itself. */
|
|
41
|
+
readonly reason: InterruptReason;
|
|
42
|
+
/**
|
|
43
|
+
* Whether the interrupted work is known to have stopped. An interrupted Promise
|
|
44
|
+
* that has not settled within the grace period may still be changing external
|
|
45
|
+
* state.
|
|
46
|
+
*/
|
|
47
|
+
readonly settled: boolean;
|
|
48
|
+
}
|
|
49
|
+
/** Not started because execution stopped first. */
|
|
50
|
+
| { readonly _tag: "Unattempted" }
|
|
51
|
+
/** `evaluated`: whether a prepare phase ran and decided to apply. */
|
|
52
|
+
| { readonly _tag: "WouldExecute"; readonly evaluated: boolean }
|
|
53
|
+
| { readonly _tag: "WouldSkip"; readonly reason: string }
|
|
54
|
+
| { readonly _tag: "Undetermined"; readonly reason: string }
|
|
55
|
+
| {
|
|
56
|
+
readonly _tag: "PreparationFailed";
|
|
57
|
+
readonly error: E | undefined;
|
|
58
|
+
readonly cause: Cause.Cause<E>;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** @since @next */
|
|
62
|
+
export type OccurrenceReport<A extends Action.Any = Action.Any, E = unknown> = {
|
|
63
|
+
readonly occurrence: Occurrence<A>;
|
|
64
|
+
readonly outcome: Outcome<E>;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/** @since @next */
|
|
68
|
+
export type Report<A extends Action.Any = Action.Any, E = unknown> = {
|
|
69
|
+
readonly _tag: "Report";
|
|
70
|
+
readonly mode: "execute" | "dry-run";
|
|
71
|
+
readonly status:
|
|
72
|
+
| "completed"
|
|
73
|
+
| "failed"
|
|
74
|
+
| "interrupted"
|
|
75
|
+
| "not-started"
|
|
76
|
+
| "would-complete"
|
|
77
|
+
| "would-fail";
|
|
78
|
+
readonly from: string;
|
|
79
|
+
readonly to: string;
|
|
80
|
+
readonly route: string;
|
|
81
|
+
/** Every occurrence in plan order. */
|
|
82
|
+
readonly occurrences: ReadonlyArray<OccurrenceReport<A, E>>;
|
|
83
|
+
/**
|
|
84
|
+
* Whether any apply phase started. A started apply phase may have partially changed
|
|
85
|
+
* state.
|
|
86
|
+
*/
|
|
87
|
+
readonly bodiesStarted: boolean;
|
|
88
|
+
/** Progress is not persisted. Rerunning the plan repeats completed actions. */
|
|
89
|
+
readonly persistence: "none";
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* A handler is missing, duplicated, or bound to a different definition.
|
|
94
|
+
*
|
|
95
|
+
* @since @next
|
|
96
|
+
*/
|
|
97
|
+
export type CoverageIssue = {
|
|
98
|
+
readonly _tag: "Missing" | "Duplicate" | "Mismatched";
|
|
99
|
+
readonly occurrenceId: string;
|
|
100
|
+
readonly actionId: string;
|
|
101
|
+
readonly description: string;
|
|
102
|
+
readonly migrationId: string;
|
|
103
|
+
/** The rule that produced the occurrence, for replacements. */
|
|
104
|
+
readonly rule: string | undefined;
|
|
105
|
+
/** The occurrences a replacement stands for, so the missing handler is discoverable. */
|
|
106
|
+
readonly replaces: ReadonlyArray<{
|
|
107
|
+
readonly occurrenceId: string;
|
|
108
|
+
readonly description: string;
|
|
109
|
+
}>;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const HandlerCoverageBase = Data.TaggedError("HandlerCoverageError");
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Handler coverage failed before any handler phase ran. Every occurrence needs exactly
|
|
116
|
+
* one handler, for the same action definition: the same identifier, kind, and payload.
|
|
117
|
+
* For an occurrence that a rule produced, the issue names the rule and the occurrences
|
|
118
|
+
* it replaced.
|
|
119
|
+
*
|
|
120
|
+
* @since @next
|
|
121
|
+
*/
|
|
122
|
+
export class HandlerCoverageError<A extends Action.Any = Action.Any> extends HandlerCoverageBase<{
|
|
123
|
+
readonly issues: ReadonlyArray<CoverageIssue>;
|
|
124
|
+
readonly report: Report<A, never>;
|
|
125
|
+
}> {
|
|
126
|
+
override get message() {
|
|
127
|
+
return `Handler coverage failed for ${this.issues.length} occurrence(s): ${this.issues
|
|
128
|
+
.map(
|
|
129
|
+
(issue) =>
|
|
130
|
+
`${issue._tag.toLowerCase()} handler for "${issue.actionId}" (${issue.description})`,
|
|
131
|
+
)
|
|
132
|
+
.join("; ")}.`;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const ExecutionFailedBase = Data.TaggedError("ExecutionFailed");
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* An occurrence failed. Execution stopped admitting new actions; started ones settled.
|
|
140
|
+
*
|
|
141
|
+
* @since @next
|
|
142
|
+
*/
|
|
143
|
+
export class ExecutionFailed<
|
|
144
|
+
A extends Action.Any = Action.Any,
|
|
145
|
+
E = unknown,
|
|
146
|
+
> extends ExecutionFailedBase<{
|
|
147
|
+
readonly failures: ReadonlyArray<OccurrenceReport<A, E>>;
|
|
148
|
+
readonly report: Report<A, E>;
|
|
149
|
+
}> {
|
|
150
|
+
override get message() {
|
|
151
|
+
return `Execution failed at ${this.failures
|
|
152
|
+
.map((failure) => `"${failure.occurrence.id}"`)
|
|
153
|
+
.join(", ")}. Completed actions were not rolled back.`;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const ExecutionInterruptedBase = Data.TaggedError("ExecutionInterrupted");
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Why an execution or an occurrence was interrupted: explicit cancellation, a configured
|
|
161
|
+
* timeout, or an Effect handler that interrupted itself.
|
|
162
|
+
*
|
|
163
|
+
* @since @next
|
|
164
|
+
*/
|
|
165
|
+
export type InterruptReason = "cancelled" | "timeout" | "handler";
|
|
166
|
+
|
|
167
|
+
const interruptedBy: Record<InterruptReason, string> = {
|
|
168
|
+
cancelled: "cancelled",
|
|
169
|
+
timeout: "stopped by a timeout",
|
|
170
|
+
handler: "interrupted by a handler",
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Explicit cancellation, a configured timeout, or a handler's own interruption stopped
|
|
175
|
+
* execution.
|
|
176
|
+
*
|
|
177
|
+
* @since @next
|
|
178
|
+
*/
|
|
179
|
+
export class ExecutionInterrupted<
|
|
180
|
+
A extends Action.Any = Action.Any,
|
|
181
|
+
E = unknown,
|
|
182
|
+
> extends ExecutionInterruptedBase<{
|
|
183
|
+
readonly reason: InterruptReason;
|
|
184
|
+
readonly report: Report<A, E>;
|
|
185
|
+
}> {
|
|
186
|
+
override get message() {
|
|
187
|
+
const pending = this.report.occurrences.filter(
|
|
188
|
+
(entry) => entry.outcome._tag === "Interrupted" && !entry.outcome.settled,
|
|
189
|
+
);
|
|
190
|
+
const suffix =
|
|
191
|
+
pending.length === 0
|
|
192
|
+
? ""
|
|
193
|
+
: ` ${pending.length} interrupted action(s) had not settled and may still be running.`;
|
|
194
|
+
|
|
195
|
+
return `Execution was ${interruptedBy[this.reason]}.${suffix}`;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** @since @next */
|
|
200
|
+
export type ExecutionError<A extends Action.Any, E> =
|
|
201
|
+
| HandlerCoverageError<A>
|
|
202
|
+
| ExecutionFailed<A, E>
|
|
203
|
+
| ExecutionInterrupted<A, E>;
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Action identifiers of a statically covered plan that no handler in the array
|
|
207
|
+
* implements.
|
|
208
|
+
*
|
|
209
|
+
* @since @next
|
|
210
|
+
*/
|
|
211
|
+
export type Uncovered<A extends Action.Any, H, C extends Plan.Coverage> = "runtime" extends C
|
|
212
|
+
? never
|
|
213
|
+
: A extends Action.Any
|
|
214
|
+
? string extends A["id"]
|
|
215
|
+
? never
|
|
216
|
+
: A["id"] extends Handler.ActionId<H>
|
|
217
|
+
? never
|
|
218
|
+
: A["id"]
|
|
219
|
+
: never;
|
|
220
|
+
|
|
221
|
+
/** Rejects a handler array that leaves statically known actions uncovered, naming them. */
|
|
222
|
+
type CoverageCheck<A extends Action.Any, H, C extends Plan.Coverage> = [
|
|
223
|
+
Uncovered<A, H, C>,
|
|
224
|
+
] extends [never]
|
|
225
|
+
? unknown
|
|
226
|
+
: { readonly handlers: `Missing a handler for action "${Uncovered<A, H, C>}"` };
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Errors an execution can report for its occurrences.
|
|
230
|
+
*
|
|
231
|
+
* @since @next
|
|
232
|
+
*/
|
|
233
|
+
export type Errors<H> = Handler.Error<H>;
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Effect services an execution requires: the services of its handlers.
|
|
237
|
+
*
|
|
238
|
+
* @since @next
|
|
239
|
+
*/
|
|
240
|
+
export type Requirements<H> = Handler.Services<H>;
|
|
241
|
+
|
|
242
|
+
/** @since @next */
|
|
243
|
+
export type Options<H extends Handler.Any> = {
|
|
244
|
+
readonly handlers?: ReadonlyArray<H>;
|
|
245
|
+
/**
|
|
246
|
+
* Run prepare phases without running any apply phase. A prepare phase that may
|
|
247
|
+
* depend on an earlier action is reported `Undetermined`, because the dry run does
|
|
248
|
+
* not apply that action.
|
|
249
|
+
*/
|
|
250
|
+
readonly dryRun?: boolean;
|
|
251
|
+
/**
|
|
252
|
+
* Limit for each phase of an occurrence: the prepare phase and the apply phase each
|
|
253
|
+
* get the full limit. Exceeding it interrupts that action and stops admitting new
|
|
254
|
+
* ones. It applies to dry-run prepare phases too.
|
|
255
|
+
*/
|
|
256
|
+
readonly timeout?: Duration.Input;
|
|
257
|
+
/**
|
|
258
|
+
* How long to wait for an interrupted Promise callback to settle before reporting it
|
|
259
|
+
* as possibly still running. Defaults to 5 seconds.
|
|
260
|
+
*/
|
|
261
|
+
readonly settleTimeout?: Duration.Input;
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
/** A handler as the executor runs it: its action is erased, its channels are not. */
|
|
265
|
+
type Internal<E, R> = Handler.Handler<Action.Any, E, R>;
|
|
266
|
+
|
|
267
|
+
type Resolved<E, R> = Map<string, Internal<E, R>>;
|
|
268
|
+
|
|
269
|
+
const describeReplaces = (occurrence: Occurrence) =>
|
|
270
|
+
occurrence.origin._tag === "Replacement"
|
|
271
|
+
? occurrence.origin.replaces.map((replaced) => ({
|
|
272
|
+
occurrenceId: replaced.id,
|
|
273
|
+
description: replaced.action.description,
|
|
274
|
+
}))
|
|
275
|
+
: [];
|
|
276
|
+
|
|
277
|
+
const coverage = <E, R>(
|
|
278
|
+
plan: Plan.Any,
|
|
279
|
+
handlers: ReadonlyArray<Internal<E, R>>,
|
|
280
|
+
): { readonly resolved: Resolved<E, R>; readonly issues: ReadonlyArray<CoverageIssue> } => {
|
|
281
|
+
const byAction = new Map<string, Array<Internal<E, R>>>();
|
|
282
|
+
for (const handler of handlers) {
|
|
283
|
+
const list = byAction.get(handler.action.id) ?? [];
|
|
284
|
+
list.push(handler);
|
|
285
|
+
byAction.set(handler.action.id, list);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const resolved: Resolved<E, R> = new Map();
|
|
289
|
+
const issues: Array<CoverageIssue> = [];
|
|
290
|
+
for (const occurrence of plan.occurrences) {
|
|
291
|
+
const issue = (tag: CoverageIssue["_tag"]) =>
|
|
292
|
+
issues.push({
|
|
293
|
+
_tag: tag,
|
|
294
|
+
occurrenceId: occurrence.id,
|
|
295
|
+
actionId: occurrence.action.id,
|
|
296
|
+
description: occurrence.action.description,
|
|
297
|
+
migrationId: occurrence.migration.id,
|
|
298
|
+
rule:
|
|
299
|
+
occurrence.origin._tag === "Replacement"
|
|
300
|
+
? occurrence.origin.rule.id
|
|
301
|
+
: undefined,
|
|
302
|
+
replaces: describeReplaces(occurrence),
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
const candidates = byAction.get(occurrence.action.id) ?? [];
|
|
306
|
+
const [selected] = candidates;
|
|
307
|
+
if (candidates.length > 1) issue("Duplicate");
|
|
308
|
+
else if (selected === undefined) issue("Missing");
|
|
309
|
+
else if (
|
|
310
|
+
selected.action.kind !== occurrence.action.kind ||
|
|
311
|
+
!Equal.equals(selected.action.payload, occurrence.action.payload)
|
|
312
|
+
) {
|
|
313
|
+
issue("Mismatched");
|
|
314
|
+
} else resolved.set(occurrence.id, selected);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
return { resolved, issues };
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
const report = <A extends Action.Any, E>(
|
|
321
|
+
plan: Plan.Plan<A, Plan.Coverage>,
|
|
322
|
+
mode: Report["mode"],
|
|
323
|
+
status: Report["status"],
|
|
324
|
+
outcomes: ReadonlyMap<string, Outcome<E>>,
|
|
325
|
+
bodiesStarted: boolean,
|
|
326
|
+
): Report<A, E> => ({
|
|
327
|
+
_tag: "Report",
|
|
328
|
+
mode,
|
|
329
|
+
status,
|
|
330
|
+
from: plan.from.id,
|
|
331
|
+
to: plan.to.id,
|
|
332
|
+
route: plan.route.id,
|
|
333
|
+
occurrences: plan.occurrences.map((occurrence) => ({
|
|
334
|
+
occurrence,
|
|
335
|
+
outcome: outcomes.get(occurrence.id) ?? { _tag: "Unattempted" },
|
|
336
|
+
})),
|
|
337
|
+
bodiesStarted,
|
|
338
|
+
persistence: "none",
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
const failureOf = <E>(cause: Cause.Cause<E>) => ({
|
|
342
|
+
error: Option.getOrUndefined(Cause.findErrorOption(cause)),
|
|
343
|
+
cause,
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
/** The exit an occurrence's scope closes with, so finalizers see how it ended. */
|
|
347
|
+
const exitOf = <E>(outcome: Outcome<E> | undefined): Exit.Exit<void, E> => {
|
|
348
|
+
switch (outcome?._tag) {
|
|
349
|
+
case "Failed":
|
|
350
|
+
case "PreparationFailed":
|
|
351
|
+
return Exit.failCause(outcome.cause);
|
|
352
|
+
case "Interrupted":
|
|
353
|
+
return Exit.interrupt();
|
|
354
|
+
default:
|
|
355
|
+
return Exit.void;
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
const forEachBranch = <R>(
|
|
360
|
+
branches: ReadonlyArray<Node>,
|
|
361
|
+
concurrency: Action.Concurrency,
|
|
362
|
+
run: (node: Node) => Effect.Effect<void, never, R>,
|
|
363
|
+
) => Effect.forEach(branches, run, { concurrency, discard: true });
|
|
364
|
+
|
|
365
|
+
/** Registers a callback that cancels the execution. Only `runPromise` uses it. */
|
|
366
|
+
type Subscribe = (cancel: () => void) => void;
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Receives the fiber that closes an occurrence scope after an interrupted Promise
|
|
370
|
+
* settles, so the caller can keep the services it built open until then.
|
|
371
|
+
*/
|
|
372
|
+
type Retain = (fiber: Fiber.Fiber<void>) => void;
|
|
373
|
+
|
|
374
|
+
type StopReason = "failure" | InterruptReason;
|
|
375
|
+
|
|
376
|
+
type PhaseResult<T, E> =
|
|
377
|
+
| { readonly _tag: "Done"; readonly exit: Exit.Exit<T, E> }
|
|
378
|
+
| {
|
|
379
|
+
readonly _tag: "Interrupted";
|
|
380
|
+
readonly reason: "cancelled" | "timeout";
|
|
381
|
+
readonly settled: boolean;
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
type ControlOptions = Pick<Options<never>, "timeout" | "settleTimeout">;
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Logs a cleanup failure that the report cannot carry, with the occurrence or the
|
|
388
|
+
* services layer that owned the resources.
|
|
389
|
+
*/
|
|
390
|
+
const logCleanupFailure = (owner: Record<string, string>) => (cause: Cause.Cause<unknown>) =>
|
|
391
|
+
Effect.logError("deltafold: cleanup failed", cause).pipe(Effect.annotateLogs(owner));
|
|
392
|
+
|
|
393
|
+
/** Admission state, cancellation, and timeouts shared by real and dry runs. */
|
|
394
|
+
const makeControl = (options: ControlOptions, subscribe: Subscribe | undefined) =>
|
|
395
|
+
Effect.gen(function* () {
|
|
396
|
+
const halt: { reason: StopReason | undefined } = { reason: undefined };
|
|
397
|
+
const cancelled = yield* Deferred.make<"cancelled">();
|
|
398
|
+
const settleTimeout = options.settleTimeout ?? Duration.seconds(5);
|
|
399
|
+
|
|
400
|
+
const stop = (reason: StopReason) => {
|
|
401
|
+
halt.reason ??= reason;
|
|
402
|
+
};
|
|
403
|
+
subscribe?.(() => {
|
|
404
|
+
stop("cancelled");
|
|
405
|
+
Deferred.doneUnsafe(cancelled, Exit.succeed("cancelled"));
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Runs one phase, racing it against cancellation and its own timeout. An
|
|
410
|
+
* interrupted Promise that outlives the settlement grace period goes to `unsettled`.
|
|
411
|
+
*/
|
|
412
|
+
const runPhase = <T, E, R>(
|
|
413
|
+
work: Effect.Effect<T, E, R>,
|
|
414
|
+
unsettled: Array<Promise<void>>,
|
|
415
|
+
): Effect.Effect<PhaseResult<T, E>, never, R> =>
|
|
416
|
+
Effect.gen(function* () {
|
|
417
|
+
let settled = true;
|
|
418
|
+
const tracked = work.pipe(
|
|
419
|
+
Effect.provideService(SettlementReference, {
|
|
420
|
+
grace: settleTimeout,
|
|
421
|
+
unsettled: (promise) => {
|
|
422
|
+
settled = false;
|
|
423
|
+
unsettled.push(promise);
|
|
424
|
+
},
|
|
425
|
+
}),
|
|
426
|
+
);
|
|
427
|
+
const stopSignals: Array<Effect.Effect<"cancelled" | "timeout">> = [
|
|
428
|
+
Deferred.await(cancelled),
|
|
429
|
+
];
|
|
430
|
+
if (options.timeout !== undefined) {
|
|
431
|
+
stopSignals.push(Effect.as(Effect.sleep(options.timeout), "timeout" as const));
|
|
432
|
+
}
|
|
433
|
+
const result = yield* Effect.raceFirst(
|
|
434
|
+
Effect.map(Effect.exit(tracked), (exit) => ({ _tag: "Done" as const, exit })),
|
|
435
|
+
Effect.raceAll(stopSignals).pipe(
|
|
436
|
+
// Stop admission as soon as the signal fires. The race returns only after
|
|
437
|
+
// the interrupted work has had its settlement grace period.
|
|
438
|
+
Effect.tap((reason) => Effect.sync(() => stop(reason))),
|
|
439
|
+
Effect.map((reason) => ({ _tag: "Stop" as const, reason })),
|
|
440
|
+
),
|
|
441
|
+
);
|
|
442
|
+
if (result._tag === "Done") return result;
|
|
443
|
+
|
|
444
|
+
// A timeout interrupts only this action. Siblings settle as after any failure.
|
|
445
|
+
return { _tag: "Interrupted" as const, reason: result.reason, settled };
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
return { halt, stop, runPhase };
|
|
449
|
+
});
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Runs one occurrence in its own scope, which both phases share. `use` returns the
|
|
453
|
+
* exit to close the scope with. The scope closes as soon as the occurrence ends, and
|
|
454
|
+
* a failing finalizer goes to `onCleanupFailure`. If an interrupted Promise has not
|
|
455
|
+
* settled, the scope stays open until it does, possibly forever; a failing
|
|
456
|
+
* finalizer is then logged, because the report may already have been returned.
|
|
457
|
+
*/
|
|
458
|
+
const inScope = <E, R>(
|
|
459
|
+
retain: Retain,
|
|
460
|
+
occurrenceId: string,
|
|
461
|
+
use: (
|
|
462
|
+
scope: Scope.Scope,
|
|
463
|
+
unsettled: Array<Promise<void>>,
|
|
464
|
+
) => Effect.Effect<Exit.Exit<void, E>, never, R>,
|
|
465
|
+
onCleanupFailure: (cause: Cause.Cause<never>) => Effect.Effect<void>,
|
|
466
|
+
): Effect.Effect<void, never, R> =>
|
|
467
|
+
Effect.uninterruptibleMask((restore) =>
|
|
468
|
+
Effect.gen(function* () {
|
|
469
|
+
const scope = yield* Scope.make();
|
|
470
|
+
const unsettled: Array<Promise<void>> = [];
|
|
471
|
+
const used = yield* Effect.exit(restore(use(scope, unsettled)));
|
|
472
|
+
const end = Exit.isSuccess(used) ? used.value : used;
|
|
473
|
+
if (unsettled.length > 0) {
|
|
474
|
+
const fiber = yield* Effect.forkDetach(
|
|
475
|
+
Effect.promise(() => Promise.all(unsettled)).pipe(
|
|
476
|
+
Effect.andThen(Scope.close(scope, end)),
|
|
477
|
+
Effect.catchCause(logCleanupFailure({ occurrence: occurrenceId })),
|
|
478
|
+
),
|
|
479
|
+
);
|
|
480
|
+
retain(fiber);
|
|
481
|
+
} else {
|
|
482
|
+
const closed = yield* Effect.exit(Scope.close(scope, end));
|
|
483
|
+
if (Exit.isFailure(closed)) yield* onCleanupFailure(closed.cause);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
return yield* used;
|
|
487
|
+
}),
|
|
488
|
+
).pipe(Effect.asVoid);
|
|
489
|
+
|
|
490
|
+
const interrupted = <A extends Action.Any, E>(
|
|
491
|
+
plan: Plan.Plan<A, Plan.Coverage>,
|
|
492
|
+
mode: Report["mode"],
|
|
493
|
+
reason: InterruptReason,
|
|
494
|
+
outcomes: ReadonlyMap<string, Outcome<E>>,
|
|
495
|
+
bodiesStarted: boolean,
|
|
496
|
+
) =>
|
|
497
|
+
new ExecutionInterrupted({
|
|
498
|
+
reason,
|
|
499
|
+
report: report(plan, mode, "interrupted", outcomes, bodiesStarted),
|
|
500
|
+
});
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* The outcome of a phase that did not succeed. `undefined` when it succeeded. An Effect
|
|
504
|
+
* handler that interrupted itself stops admission.
|
|
505
|
+
*/
|
|
506
|
+
const unsuccessful = <T, E>(
|
|
507
|
+
phase: Handler.Phase,
|
|
508
|
+
result: PhaseResult<T, E>,
|
|
509
|
+
stop: (reason: StopReason) => void,
|
|
510
|
+
): Outcome<E> | undefined => {
|
|
511
|
+
if (result._tag === "Interrupted") {
|
|
512
|
+
return {
|
|
513
|
+
_tag: "Interrupted",
|
|
514
|
+
phase,
|
|
515
|
+
reason: result.reason,
|
|
516
|
+
settled: result.settled,
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
if (Exit.isFailure(result.exit) && Cause.hasInterruptsOnly(result.exit.cause)) {
|
|
520
|
+
stop("handler");
|
|
521
|
+
|
|
522
|
+
return { _tag: "Interrupted", phase, reason: "handler", settled: true };
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
return undefined;
|
|
526
|
+
};
|
|
527
|
+
|
|
528
|
+
const execute = <A extends Action.Any, E, R>(
|
|
529
|
+
plan: Plan.Plan<A, Plan.Coverage>,
|
|
530
|
+
resolved: Resolved<E, R>,
|
|
531
|
+
options: ControlOptions,
|
|
532
|
+
subscribe: Subscribe | undefined,
|
|
533
|
+
retain: Retain,
|
|
534
|
+
): Effect.Effect<Report<A, E>, ExecutionFailed<A, E> | ExecutionInterrupted<A, E>, R> =>
|
|
535
|
+
Effect.gen(function* () {
|
|
536
|
+
const outcomes = new Map<string, Outcome<E>>();
|
|
537
|
+
const { halt, stop, runPhase } = yield* makeControl(options, subscribe);
|
|
538
|
+
let bodiesStarted = false;
|
|
539
|
+
|
|
540
|
+
const runOccurrence = (occurrence: Occurrence) => {
|
|
541
|
+
if (halt.reason !== undefined) return Effect.void;
|
|
542
|
+
|
|
543
|
+
const handler = resolved.get(occurrence.id);
|
|
544
|
+
if (handler === undefined) return Effect.void;
|
|
545
|
+
|
|
546
|
+
let phase: Handler.Phase = "prepare";
|
|
547
|
+
const end = (outcome: Outcome<E>) => {
|
|
548
|
+
outcomes.set(occurrence.id, outcome);
|
|
549
|
+
|
|
550
|
+
return exitOf(outcome);
|
|
551
|
+
};
|
|
552
|
+
const fail = (cause: Cause.Cause<E>) => {
|
|
553
|
+
stop("failure");
|
|
554
|
+
|
|
555
|
+
return end({ _tag: "Failed", phase, ...failureOf(cause) });
|
|
556
|
+
};
|
|
557
|
+
|
|
558
|
+
const use = (scope: Scope.Scope, unsettled: Array<Promise<void>>) =>
|
|
559
|
+
Effect.gen(function* () {
|
|
560
|
+
let step: Handler.Step<E, R>;
|
|
561
|
+
if (handler.prepares) {
|
|
562
|
+
const preparation = yield* runPhase(handler.prepare(scope), unsettled);
|
|
563
|
+
const stopped = unsuccessful("prepare", preparation, stop);
|
|
564
|
+
if (stopped !== undefined) return end(stopped);
|
|
565
|
+
if (preparation._tag !== "Done") return Exit.void;
|
|
566
|
+
if (Exit.isFailure(preparation.exit)) return fail(preparation.exit.cause);
|
|
567
|
+
step = preparation.exit.value;
|
|
568
|
+
// The occurrence has started, so a sibling failure or timeout lets it
|
|
569
|
+
// finish. Cancellation that arrived while preparing keeps it from
|
|
570
|
+
// applying, and the prepared value is discarded.
|
|
571
|
+
if (step._tag === "Apply" && halt.reason === "cancelled") return Exit.void;
|
|
572
|
+
} else {
|
|
573
|
+
const started = yield* Effect.exit(handler.prepare(scope));
|
|
574
|
+
if (Exit.isFailure(started)) return fail(started.cause);
|
|
575
|
+
step = started.value;
|
|
576
|
+
}
|
|
577
|
+
if (step._tag === "Skip") return end({ _tag: "Skipped", reason: step.reason });
|
|
578
|
+
|
|
579
|
+
phase = "apply";
|
|
580
|
+
bodiesStarted = true;
|
|
581
|
+
const applied = yield* runPhase(step.apply, unsettled);
|
|
582
|
+
const stopped = unsuccessful("apply", applied, stop);
|
|
583
|
+
if (stopped !== undefined) return end(stopped);
|
|
584
|
+
if (applied._tag !== "Done") return Exit.void;
|
|
585
|
+
if (Exit.isFailure(applied.exit)) return fail(applied.exit.cause);
|
|
586
|
+
|
|
587
|
+
return end({ _tag: "Completed" });
|
|
588
|
+
});
|
|
589
|
+
|
|
590
|
+
// A finalizer that fails before the report is part of the execution: it fails an
|
|
591
|
+
// occurrence that otherwise ended normally. An interrupted occurrence keeps its
|
|
592
|
+
// outcome, and the failure is logged.
|
|
593
|
+
const onCleanupFailure = (cause: Cause.Cause<never>) =>
|
|
594
|
+
Effect.suspend(() => {
|
|
595
|
+
const outcome = outcomes.get(occurrence.id);
|
|
596
|
+
if (outcome?._tag === "Interrupted") {
|
|
597
|
+
return logCleanupFailure({ occurrence: occurrence.id })(cause);
|
|
598
|
+
}
|
|
599
|
+
stop("failure");
|
|
600
|
+
outcomes.set(occurrence.id, {
|
|
601
|
+
_tag: "Failed",
|
|
602
|
+
phase,
|
|
603
|
+
...failureOf(
|
|
604
|
+
outcome?._tag === "Failed"
|
|
605
|
+
? Cause.combine(outcome.cause, cause)
|
|
606
|
+
: cause,
|
|
607
|
+
),
|
|
608
|
+
});
|
|
609
|
+
|
|
610
|
+
return Effect.void;
|
|
611
|
+
});
|
|
612
|
+
|
|
613
|
+
return inScope(retain, occurrence.id, use, onCleanupFailure);
|
|
614
|
+
};
|
|
615
|
+
|
|
616
|
+
const runNode = (node: Node): Effect.Effect<void, never, R> => {
|
|
617
|
+
switch (node._tag) {
|
|
618
|
+
case "Occurrence":
|
|
619
|
+
return runOccurrence(node);
|
|
620
|
+
case "Sequence":
|
|
621
|
+
return Effect.forEach(node.children, runNode, { discard: true });
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
// Sibling failures stop admission through `halt`; they never interrupt branches.
|
|
625
|
+
return forEachBranch(node.branches, node.concurrency, runNode);
|
|
626
|
+
};
|
|
627
|
+
|
|
628
|
+
for (const step of plan.steps) {
|
|
629
|
+
// Migration steps are barriers: a step starts only after the previous one settled.
|
|
630
|
+
if (halt.reason !== undefined) break;
|
|
631
|
+
yield* runNode(step.node);
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
if (halt.reason === undefined)
|
|
635
|
+
return report(plan, "execute", "completed", outcomes, bodiesStarted);
|
|
636
|
+
if (halt.reason === "failure") {
|
|
637
|
+
const result = report(plan, "execute", "failed", outcomes, bodiesStarted);
|
|
638
|
+
|
|
639
|
+
return yield* new ExecutionFailed({
|
|
640
|
+
failures: result.occurrences.filter((entry) => entry.outcome._tag === "Failed"),
|
|
641
|
+
report: result,
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
return yield* interrupted(plan, "execute", halt.reason, outcomes, bodiesStarted);
|
|
646
|
+
});
|
|
647
|
+
|
|
648
|
+
const dryRun = <A extends Action.Any, E, R>(
|
|
649
|
+
plan: Plan.Plan<A, Plan.Coverage>,
|
|
650
|
+
resolved: Resolved<E, R>,
|
|
651
|
+
options: ControlOptions,
|
|
652
|
+
subscribe: Subscribe | undefined,
|
|
653
|
+
retain: Retain,
|
|
654
|
+
): Effect.Effect<Report<A, E>, ExecutionInterrupted<A, E>, R> =>
|
|
655
|
+
Effect.gen(function* () {
|
|
656
|
+
const outcomes = new Map<string, Outcome<E>>();
|
|
657
|
+
const { halt, stop, runPhase } = yield* makeControl(options, subscribe);
|
|
658
|
+
let failedAt: string | undefined;
|
|
659
|
+
|
|
660
|
+
/** Runs a prepare phase in the occurrence's scope and records what it predicts. */
|
|
661
|
+
const prepare = (id: string, handler: Internal<E, R>) => {
|
|
662
|
+
const end = (outcome: Outcome<E>) => {
|
|
663
|
+
outcomes.set(id, outcome);
|
|
664
|
+
|
|
665
|
+
return exitOf(outcome);
|
|
666
|
+
};
|
|
667
|
+
const use = (scope: Scope.Scope, unsettled: Array<Promise<void>>) =>
|
|
668
|
+
Effect.gen(function* () {
|
|
669
|
+
const preparation = yield* runPhase(handler.prepare(scope), unsettled);
|
|
670
|
+
const stopped = unsuccessful("prepare", preparation, stop);
|
|
671
|
+
if (stopped !== undefined) return end(stopped);
|
|
672
|
+
if (preparation._tag !== "Done") return Exit.void;
|
|
673
|
+
if (Exit.isFailure(preparation.exit)) {
|
|
674
|
+
failedAt = id;
|
|
675
|
+
|
|
676
|
+
return end({
|
|
677
|
+
_tag: "PreparationFailed",
|
|
678
|
+
...failureOf(preparation.exit.cause),
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
// A dry run never applies: the prepared value is discarded.
|
|
682
|
+
const step = preparation.exit.value;
|
|
683
|
+
|
|
684
|
+
return end(
|
|
685
|
+
step._tag === "Skip"
|
|
686
|
+
? { _tag: "WouldSkip", reason: step.reason }
|
|
687
|
+
: { _tag: "WouldExecute", evaluated: true },
|
|
688
|
+
);
|
|
689
|
+
});
|
|
690
|
+
const onCleanupFailure = (cause: Cause.Cause<never>) =>
|
|
691
|
+
Effect.suspend(() => {
|
|
692
|
+
const outcome = outcomes.get(id);
|
|
693
|
+
if (outcome?._tag === "Interrupted") {
|
|
694
|
+
return logCleanupFailure({ occurrence: id })(cause);
|
|
695
|
+
}
|
|
696
|
+
failedAt ??= id;
|
|
697
|
+
outcomes.set(id, {
|
|
698
|
+
_tag: "PreparationFailed",
|
|
699
|
+
...failureOf(
|
|
700
|
+
outcome?._tag === "PreparationFailed"
|
|
701
|
+
? Cause.combine(outcome.cause, cause)
|
|
702
|
+
: cause,
|
|
703
|
+
),
|
|
704
|
+
});
|
|
705
|
+
|
|
706
|
+
return Effect.void;
|
|
707
|
+
});
|
|
708
|
+
|
|
709
|
+
return inScope(retain, id, use, onCleanupFailure);
|
|
710
|
+
};
|
|
711
|
+
|
|
712
|
+
/** Returns whether the node would or might change state. */
|
|
713
|
+
const visit = (node: Node, dirty: boolean): Effect.Effect<boolean, never, R> =>
|
|
714
|
+
Effect.gen(function* () {
|
|
715
|
+
if (node._tag === "Sequence") {
|
|
716
|
+
let current = dirty;
|
|
717
|
+
for (const child of node.children) current = yield* visit(child, current);
|
|
718
|
+
|
|
719
|
+
return current;
|
|
720
|
+
}
|
|
721
|
+
if (node._tag === "Parallel") {
|
|
722
|
+
// Branches are independent: each starts from the state before the group.
|
|
723
|
+
// They are evaluated one at a time so the report is deterministic.
|
|
724
|
+
let changed = dirty;
|
|
725
|
+
for (const branch of node.branches)
|
|
726
|
+
changed = (yield* visit(branch, dirty)) || changed;
|
|
727
|
+
|
|
728
|
+
return changed;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
const handler = resolved.get(node.id);
|
|
732
|
+
if (handler === undefined || halt.reason !== undefined) return dirty;
|
|
733
|
+
if (failedAt !== undefined) {
|
|
734
|
+
outcomes.set(node.id, {
|
|
735
|
+
_tag: "Undetermined",
|
|
736
|
+
reason: `Execution would stop at the failed preparation of "${failedAt}".`,
|
|
737
|
+
});
|
|
738
|
+
|
|
739
|
+
return true;
|
|
740
|
+
}
|
|
741
|
+
if (!handler.prepares) {
|
|
742
|
+
outcomes.set(node.id, { _tag: "WouldExecute", evaluated: false });
|
|
743
|
+
|
|
744
|
+
return true;
|
|
745
|
+
}
|
|
746
|
+
if (dirty) {
|
|
747
|
+
outcomes.set(node.id, {
|
|
748
|
+
_tag: "Undetermined",
|
|
749
|
+
reason: "The prepare phase depends on earlier actions that a dry run does not apply.",
|
|
750
|
+
});
|
|
751
|
+
|
|
752
|
+
return true;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
yield* prepare(node.id, handler);
|
|
756
|
+
|
|
757
|
+
return outcomes.get(node.id)?._tag !== "WouldSkip";
|
|
758
|
+
});
|
|
759
|
+
|
|
760
|
+
// Later migrations conservatively depend on every earlier migration.
|
|
761
|
+
let dirty = false;
|
|
762
|
+
for (const step of plan.steps) dirty = yield* visit(step.node, dirty);
|
|
763
|
+
|
|
764
|
+
if (halt.reason !== undefined && halt.reason !== "failure") {
|
|
765
|
+
return yield* interrupted(plan, "dry-run", halt.reason, outcomes, false);
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
return report(
|
|
769
|
+
plan,
|
|
770
|
+
"dry-run",
|
|
771
|
+
failedAt === undefined ? "would-complete" : "would-fail",
|
|
772
|
+
outcomes,
|
|
773
|
+
false,
|
|
774
|
+
);
|
|
775
|
+
});
|
|
776
|
+
|
|
777
|
+
const run = <A extends Action.Any, C extends Plan.Coverage, H extends Handler.Any>(
|
|
778
|
+
plan: Plan.Plan<A, C>,
|
|
779
|
+
options: Options<H>,
|
|
780
|
+
subscribe: Subscribe | undefined,
|
|
781
|
+
retain: Retain,
|
|
782
|
+
): Effect.Effect<Report<A, Errors<H>>, ExecutionError<A, Errors<H>>, Requirements<H>> => {
|
|
783
|
+
// Handlers are covariant in their errors and services, and `Errors<H>` and
|
|
784
|
+
// `Requirements<H>` collect them from each handler in `H`, so every handler fits this
|
|
785
|
+
// shape. From here on the compiler checks both channels.
|
|
786
|
+
const handlers: ReadonlyArray<Internal<Errors<H>, Requirements<H>>> = options.handlers ?? [];
|
|
787
|
+
|
|
788
|
+
return Effect.gen(function* () {
|
|
789
|
+
const checked = coverage(plan, handlers);
|
|
790
|
+
if (checked.issues.length > 0) {
|
|
791
|
+
return yield* new HandlerCoverageError({
|
|
792
|
+
issues: checked.issues,
|
|
793
|
+
report: report(
|
|
794
|
+
plan,
|
|
795
|
+
options.dryRun === true ? "dry-run" : "execute",
|
|
796
|
+
"not-started",
|
|
797
|
+
new Map<string, Outcome<never>>(),
|
|
798
|
+
false,
|
|
799
|
+
),
|
|
800
|
+
});
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
return options.dryRun === true
|
|
804
|
+
? yield* dryRun(plan, checked.resolved, options, subscribe, retain)
|
|
805
|
+
: yield* execute(plan, checked.resolved, options, subscribe, retain);
|
|
806
|
+
});
|
|
807
|
+
};
|
|
808
|
+
|
|
809
|
+
/**
|
|
810
|
+
* Runs a plan as an Effect. Coverage is checked before any handler phase runs. Steps
|
|
811
|
+
* are sequential barriers; parallel groups run their branches concurrently. On failure,
|
|
812
|
+
* no new action starts, and actions already running settle before the effect fails
|
|
813
|
+
* with the partial report.
|
|
814
|
+
*
|
|
815
|
+
* Each occurrence has its own scope, shared by its phases and closed when it ends. An
|
|
816
|
+
* interrupted Promise that has not settled keeps its occurrence's scope open until it
|
|
817
|
+
* settles, after the effect has ended. Services that the caller provides stay the
|
|
818
|
+
* caller's to release.
|
|
819
|
+
*
|
|
820
|
+
* To cancel, interrupt the fiber. Interruption reaches running actions and aborts the
|
|
821
|
+
* signal passed to Promise callbacks. The effect then ends as interrupted, without a
|
|
822
|
+
* report.
|
|
823
|
+
*
|
|
824
|
+
* @since @next
|
|
825
|
+
*/
|
|
826
|
+
export const effect = <
|
|
827
|
+
A extends Action.Any,
|
|
828
|
+
C extends Plan.Coverage,
|
|
829
|
+
H extends Handler.Any = never,
|
|
830
|
+
>(
|
|
831
|
+
plan: Plan.Plan<A, C>,
|
|
832
|
+
options: Options<H> & CoverageCheck<A, H, C>,
|
|
833
|
+
): Effect.Effect<Report<A, Errors<H>>, ExecutionError<A, Errors<H>>, Requirements<H>> =>
|
|
834
|
+
run(plan, options, undefined, () => {});
|
|
835
|
+
|
|
836
|
+
type ServicesOption<R, LE> = [R] extends [never]
|
|
837
|
+
? {
|
|
838
|
+
/** Handlers without Effect services need none. */
|
|
839
|
+
readonly services?: Context.Context<never> | Layer.Layer<never, LE>;
|
|
840
|
+
}
|
|
841
|
+
: {
|
|
842
|
+
/** Supplies the handlers' Effect services. */
|
|
843
|
+
readonly services: Context.Context<R> | Layer.Layer<R, LE>;
|
|
844
|
+
};
|
|
845
|
+
|
|
846
|
+
/** @since @next */
|
|
847
|
+
export type PromiseOptions<H extends Handler.Any> = Options<H> & {
|
|
848
|
+
/**
|
|
849
|
+
* Explicit cancellation. Aborting stops admission, interrupts running actions, and
|
|
850
|
+
* rejects with `ExecutionInterrupted` and the partial report.
|
|
851
|
+
*/
|
|
852
|
+
readonly signal?: AbortSignal;
|
|
853
|
+
};
|
|
854
|
+
|
|
855
|
+
/**
|
|
856
|
+
* Runs a plan and returns a Promise. It rejects with `HandlerCoverageError`,
|
|
857
|
+
* `ExecutionFailed`, or `ExecutionInterrupted`, each carrying the partial report.
|
|
858
|
+
* Building a supplied services layer can also reject with the layer's own error,
|
|
859
|
+
* without a report.
|
|
860
|
+
*
|
|
861
|
+
* A services layer is built for this run. A services context stays owned by the
|
|
862
|
+
* caller. A Promise callback that ignores its signal can keep running after
|
|
863
|
+
* cancellation or a timeout, beyond `settleTimeout`; the report marks it as possibly
|
|
864
|
+
* still running. Its occurrence's scope and the run's services layer then stay open
|
|
865
|
+
* until it settles, possibly forever, and close in that order. A cleanup failure after
|
|
866
|
+
* the Promise resolved is logged through Effect.
|
|
867
|
+
*
|
|
868
|
+
* @since @next
|
|
869
|
+
*/
|
|
870
|
+
export const runPromise = <
|
|
871
|
+
A extends Action.Any,
|
|
872
|
+
C extends Plan.Coverage,
|
|
873
|
+
H extends Handler.Any = never,
|
|
874
|
+
LE = never,
|
|
875
|
+
>(
|
|
876
|
+
plan: Plan.Plan<A, C>,
|
|
877
|
+
options: PromiseOptions<H> & ServicesOption<Requirements<H>, LE> & CoverageCheck<A, H, C>,
|
|
878
|
+
): Promise<Report<A, Errors<H>>> => {
|
|
879
|
+
const { signal } = options;
|
|
880
|
+
const notStarted = () =>
|
|
881
|
+
new ExecutionInterrupted({
|
|
882
|
+
reason: "cancelled",
|
|
883
|
+
report: report(
|
|
884
|
+
plan,
|
|
885
|
+
options.dryRun === true ? "dry-run" : "execute",
|
|
886
|
+
"interrupted",
|
|
887
|
+
new Map<string, Outcome<Errors<H>>>(),
|
|
888
|
+
false,
|
|
889
|
+
),
|
|
890
|
+
});
|
|
891
|
+
if (signal?.aborted === true) return Promise.reject(notStarted());
|
|
892
|
+
|
|
893
|
+
// Until the run installs its own cancellation, an abort stops building the services
|
|
894
|
+
// layer. Afterwards the run stops admission and reports partial progress.
|
|
895
|
+
const abortedBeforeRun = Deferred.makeUnsafe<void>();
|
|
896
|
+
let cancelRun: (() => void) | undefined;
|
|
897
|
+
const onAbort = () => {
|
|
898
|
+
if (cancelRun === undefined) Deferred.doneUnsafe(abortedBeforeRun, Effect.void);
|
|
899
|
+
else cancelRun();
|
|
900
|
+
};
|
|
901
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
902
|
+
const subscribe: Subscribe | undefined =
|
|
903
|
+
signal === undefined
|
|
904
|
+
? undefined
|
|
905
|
+
: (cancel) => {
|
|
906
|
+
cancelRun = cancel;
|
|
907
|
+
if (signal.aborted) cancel();
|
|
908
|
+
};
|
|
909
|
+
const retained: Array<Fiber.Fiber<void>> = [];
|
|
910
|
+
const program = run(plan, options, subscribe, (fiber) => retained.push(fiber));
|
|
911
|
+
const services: Context.Context<never> | Layer.Layer<never, LE> | undefined = options.services;
|
|
912
|
+
const provided =
|
|
913
|
+
services === undefined
|
|
914
|
+
? program
|
|
915
|
+
: Context.isContext(services)
|
|
916
|
+
? Effect.provideContext(program, services)
|
|
917
|
+
: // runPromise is the entry point: the caller's layer is built for this one run,
|
|
918
|
+
// in a scope that outlives the run while retained occurrence scopes are open.
|
|
919
|
+
Effect.uninterruptibleMask((restore) =>
|
|
920
|
+
Effect.gen(function* () {
|
|
921
|
+
const scope = yield* Scope.make();
|
|
922
|
+
const built = yield* Effect.exit(
|
|
923
|
+
restore(Layer.buildWithScope(services, scope)),
|
|
924
|
+
);
|
|
925
|
+
if (Exit.isFailure(built)) {
|
|
926
|
+
yield* Scope.close(scope, built);
|
|
927
|
+
|
|
928
|
+
return yield* built;
|
|
929
|
+
}
|
|
930
|
+
const exit = yield* Effect.exit(
|
|
931
|
+
restore(Effect.provideContext(program, built.value)),
|
|
932
|
+
);
|
|
933
|
+
if (retained.length === 0) yield* Scope.close(scope, exit);
|
|
934
|
+
else {
|
|
935
|
+
yield* Effect.forkDetach(
|
|
936
|
+
Fiber.awaitAll(retained).pipe(
|
|
937
|
+
Effect.andThen(Scope.close(scope, exit)),
|
|
938
|
+
Effect.catchCause(
|
|
939
|
+
logCleanupFailure({ owner: "services layer" }),
|
|
940
|
+
),
|
|
941
|
+
),
|
|
942
|
+
);
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
return yield* exit;
|
|
946
|
+
}),
|
|
947
|
+
);
|
|
948
|
+
const cancellable =
|
|
949
|
+
signal === undefined
|
|
950
|
+
? provided
|
|
951
|
+
: Effect.raceFirst(
|
|
952
|
+
provided,
|
|
953
|
+
Effect.andThen(Deferred.await(abortedBeforeRun), Effect.fail(notStarted())),
|
|
954
|
+
);
|
|
955
|
+
|
|
956
|
+
return Effect.runPromiseExit(
|
|
957
|
+
// `ServicesOption` requires services that cover every requirement. A layer that
|
|
958
|
+
// fails to build rejects with its own error.
|
|
959
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion, effecttsgo/unsafe-effect-type-assertion
|
|
960
|
+
cancellable as Effect.Effect<Report<A, Errors<H>>, ExecutionError<A, Errors<H>> | LE>,
|
|
961
|
+
)
|
|
962
|
+
.finally(() => signal?.removeEventListener("abort", onAbort))
|
|
963
|
+
.then((exit) => {
|
|
964
|
+
if (Exit.isSuccess(exit)) return exit.value;
|
|
965
|
+
|
|
966
|
+
throw Cause.squash(exit.cause);
|
|
967
|
+
});
|
|
968
|
+
};
|