deltafold 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +33 -1
  2. package/dist/changelog.d.ts +10 -10
  3. package/dist/changelog.js +4 -4
  4. package/dist/changelog.js.map +1 -1
  5. package/dist/{document-BZcZo9nr.js → document-HfPyYxEd.js} +20 -20
  6. package/dist/{document-BZcZo9nr.js.map → document-HfPyYxEd.js.map} +1 -1
  7. package/dist/{document-DWHsgywm.d.ts → document-f2Zy7NQO.d.ts} +41 -41
  8. package/dist/{document-DWHsgywm.d.ts.map → document-f2Zy7NQO.d.ts.map} +1 -1
  9. package/dist/html.d.ts +2 -2
  10. package/dist/html.js +2 -2
  11. package/dist/html.js.map +1 -1
  12. package/dist/index.d.ts +437 -105
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +750 -273
  15. package/dist/index.js.map +1 -1
  16. package/dist/markdown.d.ts +2 -2
  17. package/dist/markdown.js +2 -2
  18. package/dist/markdown.js.map +1 -1
  19. package/dist/{mdast-DiRsYwPU.js → mdast-Oqkh0Gs1.js} +2 -2
  20. package/dist/{mdast-DiRsYwPU.js.map → mdast-Oqkh0Gs1.js.map} +1 -1
  21. package/dist/{package-BfBYnaCz.d.ts → package-BsMlK5xD.d.ts} +126 -116
  22. package/dist/{package-BfBYnaCz.d.ts.map → package-BsMlK5xD.d.ts.map} +1 -1
  23. package/package.json +5 -5
  24. package/src/features/documents/changelog.ts +8 -8
  25. package/src/features/documents/document.ts +39 -39
  26. package/src/features/documents/index.ts +2 -2
  27. package/src/features/execution/executor.ts +485 -313
  28. package/src/features/execution/handler.ts +30 -30
  29. package/src/features/execution/interaction.ts +11 -11
  30. package/src/features/execution/observation.ts +489 -0
  31. package/src/features/execution/observer.ts +395 -0
  32. package/src/features/package.ts +13 -8
  33. package/src/features/planning/history.ts +10 -10
  34. package/src/features/planning/identifiers.ts +7 -4
  35. package/src/features/planning/resolve-error.ts +13 -13
  36. package/src/features/planning/resolve.ts +11 -4
  37. package/src/features/planning/validate.ts +1 -1
  38. package/src/foundation/action.ts +17 -17
  39. package/src/foundation/change.ts +10 -10
  40. package/src/foundation/instruction.ts +5 -5
  41. package/src/foundation/migration.ts +12 -12
  42. package/src/foundation/plan.ts +23 -18
  43. package/src/foundation/rule.ts +6 -6
  44. package/src/foundation/shortcut.ts +6 -6
  45. package/src/foundation/version.ts +6 -6
  46. package/src/index.ts +14 -12
  47. package/src/renderers/html.ts +1 -1
  48. package/src/renderers/markdown.ts +1 -1
@@ -0,0 +1,489 @@
1
+ import {
2
+ Cause,
3
+ Clock,
4
+ Deferred,
5
+ Duration,
6
+ Effect,
7
+ Exit,
8
+ Fiber,
9
+ Option,
10
+ Predicate,
11
+ Semaphore,
12
+ } from "effect";
13
+
14
+ import type * as Plan from "../../foundation/plan.ts";
15
+ import type { Occurrence, Step } from "../../foundation/plan.ts";
16
+ import type { Outcome, Report } from "./executor.ts";
17
+ import type { Phase } from "./handler.ts";
18
+ import type * as Observer from "./observer.ts";
19
+
20
+ /** Finds the identifier of the plan step that declared an occurrence's migration side. */
21
+ type StepIdOf = (occurrence: Occurrence) => string;
22
+
23
+ const stepIdsOf =
24
+ (plan: Plan.Any): StepIdOf =>
25
+ (occurrence) =>
26
+ plan.steps.find(
27
+ (step) =>
28
+ step.migration === occurrence.migration && step.direction === occurrence.direction,
29
+ )?.id ?? occurrence.migration.id;
30
+
31
+ /** Declared occurrences behind an occurrence, through nested replacements, in order. */
32
+ const leavesOf = (occurrence: Occurrence): ReadonlyArray<Occurrence> =>
33
+ occurrence.origin._tag === "Declared"
34
+ ? [occurrence]
35
+ : occurrence.origin.replaces.flatMap(leavesOf);
36
+
37
+ const sourcesOf = (occurrence: Occurrence, stepIdOf: StepIdOf): ReadonlyArray<string> => [
38
+ ...new Set(leavesOf(occurrence).map(stepIdOf)),
39
+ ];
40
+
41
+ const occurrencesOfNode = (node: Plan.Node): ReadonlyArray<Occurrence> => {
42
+ switch (node._tag) {
43
+ case "Occurrence":
44
+ return [node];
45
+ case "Sequence":
46
+ return node.children.flatMap(occurrencesOfNode);
47
+ }
48
+
49
+ return node.branches.flatMap(occurrencesOfNode);
50
+ };
51
+
52
+ const stepInfoOf = (
53
+ step: Step,
54
+ index: number,
55
+ plan: Plan.Any,
56
+ stepIdOf: StepIdOf,
57
+ ): Observer.StepInfo => {
58
+ const occurrences = occurrencesOfNode(step.node);
59
+ const base = {
60
+ id: step.id,
61
+ index,
62
+ migration: step.migration.id,
63
+ direction: step.direction,
64
+ from: step.from.id,
65
+ to: step.to.id,
66
+ occurrences: occurrences.map((occurrence) => occurrence.id),
67
+ absorbs: [
68
+ ...new Set(occurrences.flatMap((occurrence) => sourcesOf(occurrence, stepIdOf))),
69
+ ].filter((id) => id !== step.id),
70
+ };
71
+ if (occurrences.length > 0) return { ...base, kind: "execute" };
72
+ if (!step.omitted) return { ...base, kind: "prose" };
73
+ const omitted = plan.explanations.find(
74
+ (explanation) =>
75
+ explanation._tag === "OmittedStep" &&
76
+ explanation.migration.id === step.migration.id &&
77
+ explanation.direction === step.direction,
78
+ );
79
+
80
+ return {
81
+ ...base,
82
+ kind: "omitted",
83
+ reason:
84
+ omitted?._tag === "OmittedStep" && omitted.reason === "all-actions-removed"
85
+ ? "all-actions-removed"
86
+ : "noop",
87
+ };
88
+ };
89
+
90
+ const actionInfoOf = (
91
+ occurrence: Occurrence,
92
+ step: string,
93
+ stepIdOf: StepIdOf,
94
+ ): Observer.ActionInfo => ({
95
+ occurrence: occurrence.id,
96
+ action: occurrence.action.id,
97
+ kind: occurrence.action.kind,
98
+ description: occurrence.action.description,
99
+ migration: occurrence.migration.id,
100
+ direction: occurrence.direction,
101
+ step,
102
+ origin:
103
+ occurrence.origin._tag === "Declared"
104
+ ? { _tag: "Declared" }
105
+ : {
106
+ _tag: "Replacement",
107
+ rule: occurrence.origin.rule.id,
108
+ replaces: occurrence.origin.replaces.map((replaced) => replaced.id),
109
+ },
110
+ sources: sourcesOf(occurrence, stepIdOf),
111
+ });
112
+
113
+ /**
114
+ * Reads a handler error's tag once, so a getter cannot pass the check with one value and
115
+ * return another. A tag that cannot be read, even by a throwing getter, is absent.
116
+ */
117
+ const errorTagOf = (error: unknown): string | undefined => {
118
+ try {
119
+ if (!Predicate.hasProperty(error, "_tag")) return undefined;
120
+ const tag: unknown = error._tag;
121
+
122
+ return typeof tag === "string" ? tag : undefined;
123
+ } catch {
124
+ return undefined;
125
+ }
126
+ };
127
+
128
+ /** Copies only the fields observers may see. */
129
+ const summaryOf = (outcome: Outcome): Observer.OutcomeSummary => {
130
+ switch (outcome._tag) {
131
+ case "Completed":
132
+ return outcome.performer === "manual"
133
+ ? { _tag: "Completed", performer: "manual", confirmation: outcome.confirmation }
134
+ : { _tag: "Completed", performer: "automated" };
135
+ case "Skipped":
136
+ return { _tag: "Skipped", reason: outcome.reason };
137
+ case "Declined":
138
+ return { _tag: "Declined" };
139
+ case "Failed":
140
+ return { _tag: "Failed", phase: outcome.phase, errorTag: errorTagOf(outcome.error) };
141
+ case "Interrupted":
142
+ return {
143
+ _tag: "Interrupted",
144
+ phase: outcome.phase,
145
+ reason: outcome.reason,
146
+ settled: outcome.settled,
147
+ };
148
+ case "Unattempted":
149
+ return { _tag: "Unattempted" };
150
+ case "WouldExecute":
151
+ return {
152
+ _tag: "WouldExecute",
153
+ evaluated: outcome.evaluated,
154
+ performer: outcome.performer,
155
+ };
156
+ case "WouldSkip":
157
+ return { _tag: "WouldSkip", reason: outcome.reason };
158
+ case "Undetermined":
159
+ return { _tag: "Undetermined", reason: outcome.reason, performer: outcome.performer };
160
+ }
161
+
162
+ return { _tag: "PreparationFailed", errorTag: errorTagOf(outcome.error) };
163
+ };
164
+
165
+ const emptyCounts = (): { -readonly [K in keyof Observer.Counts]: number } => ({
166
+ Completed: 0,
167
+ Skipped: 0,
168
+ Declined: 0,
169
+ Failed: 0,
170
+ Interrupted: 0,
171
+ Unattempted: 0,
172
+ WouldExecute: 0,
173
+ WouldSkip: 0,
174
+ Undetermined: 0,
175
+ PreparationFailed: 0,
176
+ unsettled: 0,
177
+ });
178
+
179
+ /** Emits events for one run. Without observers, every method is a no-op. */
180
+ export type Emitter<R> = {
181
+ readonly runStarted: Effect.Effect<void, never, R>;
182
+ readonly stepStarted: (step: Step) => Effect.Effect<void, never, R>;
183
+ readonly stepSettled: (step: Step) => Effect.Effect<void, never, R>;
184
+ readonly phaseStarted: (occurrence: Occurrence, phase: Phase) => Effect.Effect<void, never, R>;
185
+ /**
186
+ * Emits the occurrence's current outcome from the shared outcome map, if it has one or
187
+ * has started. An occurrence that never started and has no outcome emits nothing.
188
+ */
189
+ readonly settled: (occurrence: Occurrence) => Effect.Effect<void, never, R>;
190
+ readonly runFinished: (status: Report["status"]) => Effect.Effect<void, never, R>;
191
+ /** Emits a report-less `RunFinished` after fiber interruption, if the run had started. */
192
+ readonly interrupted: Effect.Effect<void, never, R>;
193
+ readonly failures: ReadonlyArray<Observer.ObservationFailure>;
194
+ };
195
+
196
+ const noop: Emitter<never> = {
197
+ runStarted: Effect.void,
198
+ stepStarted: () => Effect.void,
199
+ stepSettled: () => Effect.void,
200
+ phaseStarted: () => Effect.void,
201
+ settled: () => Effect.void,
202
+ runFinished: () => Effect.void,
203
+ interrupted: Effect.void,
204
+ failures: [],
205
+ };
206
+
207
+ export type EmitterOptions<R> = {
208
+ readonly plan: Plan.Any;
209
+ readonly mode: Report["mode"];
210
+ readonly runId: string | undefined;
211
+ readonly observers: ReadonlyArray<Observer.Observer<R>>;
212
+ readonly outcomes: ReadonlyMap<string, Outcome>;
213
+ /** Completes when cancellation or a timeout stops the run. */
214
+ readonly stopped: Deferred.Deferred<void>;
215
+ readonly grace: Duration.Input;
216
+ /** Receives a fiber that ends when an abandoned callback stops, to keep services open. */
217
+ readonly retain: (fiber: Fiber.Fiber<void>) => void;
218
+ };
219
+
220
+ /**
221
+ * Delivery is awaited and serialized: one event at a time, to each observer in order.
222
+ * Counters change under the same lock, so each event's progress is consistent with the
223
+ * order observers see. Observer failures are recorded and never reach the run.
224
+ */
225
+ export const makeEmitter = <R>(options: EmitterOptions<R>): Effect.Effect<Emitter<R>> =>
226
+ Effect.gen(function* () {
227
+ const { plan, observers, outcomes, stopped, grace, retain } = options;
228
+ if (observers.length === 0) return noop;
229
+ const stepIdOf = stepIdsOf(plan);
230
+
231
+ const lock = yield* Semaphore.make(1);
232
+ const failures: Array<Observer.ObservationFailure> = [];
233
+ const run: Observer.Run = {
234
+ id: options.runId,
235
+ mode: options.mode,
236
+ from: plan.from.id,
237
+ to: plan.to.id,
238
+ route: plan.route.id,
239
+ };
240
+ const steps = plan.steps.map((step, index) => stepInfoOf(step, index, plan, stepIdOf));
241
+ const infoOf = new Map(plan.steps.map((step, index) => [step, steps[index]]));
242
+ const ownerOf = new Map<string, string>();
243
+ for (const info of steps) for (const id of info.occurrences) ownerOf.set(id, info.id);
244
+
245
+ const state: {
246
+ seq: number;
247
+ running: Set<string>;
248
+ actionsFinished: number;
249
+ stepsFinished: number;
250
+ started: boolean;
251
+ finished: boolean;
252
+ /** The event being delivered and the observer it is with, until every observer has it. */
253
+ delivering: { readonly event: Observer.Event; readonly observer: number } | undefined;
254
+ } = {
255
+ seq: 0,
256
+ running: new Set<string>(),
257
+ actionsFinished: 0,
258
+ stepsFinished: 0,
259
+ started: false,
260
+ finished: false,
261
+ delivering: undefined,
262
+ };
263
+ const stepsTotal = steps.filter((info) => info.kind !== "omitted").length;
264
+ const progress = (): Observer.Progress => ({
265
+ steps: { total: stepsTotal, finished: state.stepsFinished },
266
+ actions: {
267
+ total: plan.occurrences.length,
268
+ running: state.running.size,
269
+ finished: state.actionsFinished,
270
+ },
271
+ });
272
+
273
+ const countsOf = (occurrences: ReadonlyArray<Occurrence>, inFlight: boolean) => {
274
+ const counts = emptyCounts();
275
+ for (const occurrence of occurrences) {
276
+ const outcome = outcomes.get(occurrence.id);
277
+ if (outcome === undefined && inFlight && state.running.has(occurrence.id)) {
278
+ counts.Interrupted += 1;
279
+ counts.unsettled += 1;
280
+ continue;
281
+ }
282
+ const tag = outcome?._tag ?? "Unattempted";
283
+ counts[tag] += 1;
284
+ if (outcome?._tag === "Interrupted" && !outcome.settled) counts.unsettled += 1;
285
+ }
286
+
287
+ return counts;
288
+ };
289
+
290
+ /**
291
+ * Interrupts an abandoned delivery without waiting for it to stop. The run's services
292
+ * stay open until it does.
293
+ */
294
+ const abandon = (fiber: Fiber.Fiber<Exit.Exit<unknown, unknown>>) =>
295
+ Effect.map(Effect.forkDetach(Fiber.interrupt(fiber)), retain);
296
+
297
+ /**
298
+ * Bounds a delivery once the run has been stopped, or always when `bounded` is set.
299
+ * The callback runs in its own fiber, with the run's services, so a delivery that
300
+ * cannot be interrupted is still abandoned when the bound passes.
301
+ */
302
+ const deliver = (
303
+ observer: Observer.Observer<R>,
304
+ event: Observer.Event,
305
+ bounded: boolean,
306
+ ): Effect.Effect<Option.Option<Exit.Exit<unknown, unknown>>, never, R> =>
307
+ Effect.uninterruptibleMask((restore) =>
308
+ Effect.gen(function* () {
309
+ const fiber = yield* Effect.forkDetach(
310
+ Effect.interruptible(observer.notify(event)),
311
+ {
312
+ startImmediately: true,
313
+ },
314
+ );
315
+ const limit = bounded
316
+ ? Effect.sleep(grace)
317
+ : Effect.andThen(Deferred.await(stopped), Effect.sleep(grace));
318
+ const result = yield* restore(
319
+ Effect.raceFirst(
320
+ Effect.map(Fiber.await(fiber), (exit) =>
321
+ Option.some(Exit.isSuccess(exit) ? exit.value : exit),
322
+ ),
323
+ Effect.as(limit, Option.none<Exit.Exit<unknown, unknown>>()),
324
+ ),
325
+ ).pipe(Effect.onInterrupt(() => abandon(fiber)));
326
+ if (Option.isNone(result)) yield* abandon(fiber);
327
+
328
+ return result;
329
+ }),
330
+ );
331
+
332
+ const record = (
333
+ observer: number,
334
+ event: Observer.Event,
335
+ result: Option.Option<Exit.Exit<unknown, unknown>>,
336
+ ) => {
337
+ if (Option.isNone(result)) {
338
+ failures.push({
339
+ observer,
340
+ event: event._tag,
341
+ seq: event.seq,
342
+ reason: "abandoned",
343
+ cause: Cause.interrupt(),
344
+ });
345
+ } else if (Exit.isFailure(result.value)) {
346
+ failures.push({
347
+ observer,
348
+ event: event._tag,
349
+ seq: event.seq,
350
+ reason: "failed",
351
+ cause: result.value.cause,
352
+ });
353
+ }
354
+ };
355
+
356
+ /** Delivers an event to each observer from `first` on, in order. */
357
+ const deliverFrom = (event: Observer.Event, first: number, bounded: boolean) =>
358
+ Effect.gen(function* () {
359
+ for (const [offset, observer] of observers.slice(first).entries()) {
360
+ const index = first + offset;
361
+ state.delivering = { event, observer: index };
362
+ record(index, event, yield* deliver(observer, event, bounded));
363
+ }
364
+ state.delivering = undefined;
365
+ });
366
+
367
+ const emit = (
368
+ update: () => void,
369
+ build: (base: {
370
+ readonly run: Observer.Run;
371
+ readonly seq: number;
372
+ readonly timestamp: number;
373
+ readonly progress: Observer.Progress;
374
+ }) => Observer.Event,
375
+ bounded = false,
376
+ ): Effect.Effect<void, never, R> =>
377
+ lock.withPermits(1)(
378
+ Effect.gen(function* () {
379
+ update();
380
+ const timestamp = yield* Clock.currentTimeMillis;
381
+ const event = build({ run, seq: state.seq, timestamp, progress: progress() });
382
+ state.seq += 1;
383
+ yield* deliverFrom(event, 0, bounded);
384
+ }),
385
+ );
386
+
387
+ const stepEvent = (step: Step) => infoOf.get(step) ?? stepInfoOf(step, -1, plan, stepIdOf);
388
+ const actionOf = (occurrence: Occurrence) =>
389
+ actionInfoOf(occurrence, ownerOf.get(occurrence.id) ?? stepIdOf(occurrence), stepIdOf);
390
+
391
+ const finish = (status: Report["status"], report: boolean, bounded: boolean) =>
392
+ emit(
393
+ () => {
394
+ state.finished = true;
395
+ },
396
+ (base) => ({
397
+ ...base,
398
+ _tag: "RunFinished",
399
+ status,
400
+ counts: countsOf(plan.occurrences, !report),
401
+ report,
402
+ }),
403
+ bounded,
404
+ );
405
+
406
+ /**
407
+ * Ends the stream after fiber interruption. The delivery the interruption cut short is
408
+ * abandoned. If it was `RunFinished`, the observers that had not received it get a
409
+ * report-less one with the same `seq` instead, so each observer hears exactly one.
410
+ */
411
+ const interrupted = Effect.suspend(() => {
412
+ const cut = state.delivering;
413
+ if (cut !== undefined) {
414
+ record(cut.observer, cut.event, Option.none());
415
+ state.delivering = undefined;
416
+ }
417
+ if (!state.started) return Effect.void;
418
+ if (!state.finished) return finish("interrupted", false, true);
419
+ if (cut?.event._tag !== "RunFinished") return Effect.void;
420
+ const event: Observer.Event = {
421
+ ...cut.event,
422
+ status: "interrupted",
423
+ counts: countsOf(plan.occurrences, true),
424
+ report: false,
425
+ };
426
+
427
+ return lock.withPermits(1)(deliverFrom(event, cut.observer + 1, true));
428
+ });
429
+
430
+ return {
431
+ runStarted: emit(
432
+ () => {
433
+ state.started = true;
434
+ },
435
+ (base) => ({ ...base, _tag: "RunStarted", steps }),
436
+ ),
437
+ stepStarted: (step) =>
438
+ emit(
439
+ () => {},
440
+ (base) => ({ ...base, _tag: "StepStarted", step: stepEvent(step) }),
441
+ ),
442
+ stepSettled: (step) =>
443
+ emit(
444
+ () => {
445
+ state.stepsFinished += 1;
446
+ },
447
+ (base) => ({
448
+ ...base,
449
+ _tag: "StepSettled",
450
+ step: stepEvent(step),
451
+ counts: countsOf(occurrencesOfNode(step.node), false),
452
+ }),
453
+ ),
454
+ phaseStarted: (occurrence, phase) =>
455
+ emit(
456
+ () => {
457
+ state.running.add(occurrence.id);
458
+ },
459
+ (base) => ({
460
+ ...base,
461
+ _tag: "ActionPhaseStarted",
462
+ action: actionOf(occurrence),
463
+ phase,
464
+ }),
465
+ ),
466
+ settled: (occurrence) =>
467
+ Effect.suspend(() =>
468
+ !outcomes.has(occurrence.id) && !state.running.has(occurrence.id)
469
+ ? Effect.void
470
+ : emit(
471
+ () => {
472
+ state.running.delete(occurrence.id);
473
+ state.actionsFinished += 1;
474
+ },
475
+ (base) => ({
476
+ ...base,
477
+ _tag: "ActionSettled",
478
+ action: actionOf(occurrence),
479
+ outcome: summaryOf(
480
+ outcomes.get(occurrence.id) ?? { _tag: "Unattempted" },
481
+ ),
482
+ }),
483
+ ),
484
+ ),
485
+ runFinished: (status) => finish(status, true, false),
486
+ interrupted,
487
+ failures,
488
+ };
489
+ });