deltafold 0.0.1 → 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.
@@ -1,19 +1,21 @@
1
- import { Context, Data, Effect, Predicate, Schema } from "effect";
1
+ import { Context, Data, Effect, Predicate, Schema, Scope } from "effect";
2
2
 
3
3
  import type * as Action from "../../foundation/action.ts";
4
4
  import type { ValueOf } from "../../types.ts";
5
5
  import { trackPromise } from "./settlement.ts";
6
6
 
7
7
  /**
8
- * Where a handler failure happened.
8
+ * Where a handler failure happened: the read-only prepare phase, or the apply phase that
9
+ * changes state.
9
10
  *
10
11
  * @since @next
11
12
  */
12
- export type Phase = "precondition" | "body";
13
+ export type Phase = "prepare" | "apply";
13
14
 
14
15
  /**
15
16
  * A Promise handler rejected or threw a value that none of its declared error guards
16
- * recognized.
17
+ * recognized, or its prepare phase returned something other than `Handler.prepared` or
18
+ * `Handler.skip`.
17
19
  *
18
20
  * @since @next
19
21
  */
@@ -24,27 +26,110 @@ export class UnexpectedHandlerError extends Data.TaggedError("UnexpectedHandlerE
24
26
  readonly cause: unknown;
25
27
  }> {
26
28
  override get message() {
27
- return `Handler for action "${this.actionId}" failed unexpectedly in its ${this.phase}`;
29
+ return `Handler for action "${this.actionId}" failed unexpectedly in its ${this.phase} phase`;
28
30
  }
29
31
  }
30
32
 
33
+ const PreparationTypeId = "~deltafold/Preparation";
34
+
35
+ /**
36
+ * A prepare phase decided to apply. The apply phase receives `value` unchanged; the
37
+ * executor never reads, validates, or serializes it.
38
+ *
39
+ * @since @next
40
+ */
41
+ export type Prepared<out P> = {
42
+ readonly [PreparationTypeId]: typeof PreparationTypeId;
43
+ readonly _tag: "Prepared";
44
+ readonly value: P;
45
+ };
46
+
47
+ /**
48
+ * A prepare phase decided that the action does not apply. The occurrence is skipped
49
+ * with `reason`.
50
+ *
51
+ * @since @next
52
+ */
53
+ export type Skip = {
54
+ readonly [PreparationTypeId]: typeof PreparationTypeId;
55
+ readonly _tag: "Skip";
56
+ readonly reason: string;
57
+ };
58
+
59
+ /**
60
+ * What a prepare phase returns: `Handler.prepared(value)` or `Handler.skip(reason)`.
61
+ *
62
+ * @since @next
63
+ */
64
+ export type Preparation<P> = Prepared<P> | Skip;
65
+
66
+ /** The value that a prepare phase passes to its apply phase. */
67
+ type PreparedValue<T> = T extends Prepared<infer P> ? P : never;
68
+
69
+ /**
70
+ * Ends a prepare phase with the value its apply phase receives. Wrapping the value keeps
71
+ * it apart from a skip, whatever its shape.
72
+ *
73
+ * @since @next
74
+ */
75
+ export function prepared(): Prepared<void>;
76
+ export function prepared<P>(value: P): Prepared<P>;
77
+ export function prepared(value?: unknown): Prepared<unknown> {
78
+ return { [PreparationTypeId]: PreparationTypeId, _tag: "Prepared", value };
79
+ }
80
+
81
+ /**
82
+ * Ends a prepare phase by skipping the occurrence. The apply phase does not run.
83
+ *
84
+ * @since @next
85
+ */
86
+ export const skip = (reason: string): Skip => ({
87
+ [PreparationTypeId]: PreparationTypeId,
88
+ _tag: "Skip",
89
+ reason,
90
+ });
91
+
92
+ const isPreparation = (value: unknown): value is Preparation<unknown> =>
93
+ Predicate.hasProperty(value, PreparationTypeId);
94
+
95
+ const notAPreparation = () =>
96
+ new TypeError("A prepare phase must return Handler.prepared(value) or Handler.skip(reason)");
97
+
98
+ /**
99
+ * How an occurrence continues after its prepare phase: skipped, or applied by an effect
100
+ * that already holds the prepared value.
101
+ *
102
+ * @since @next
103
+ */
104
+ export type Step<E, R> =
105
+ | Skip
106
+ | { readonly _tag: "Apply"; readonly apply: Effect.Effect<void, E, R> };
107
+
108
+ const applyStep = <E, R>(apply: Effect.Effect<void, E, R>): Step<E, R> => ({
109
+ _tag: "Apply",
110
+ apply,
111
+ });
112
+
31
113
  const TypeId = "~deltafold/Handler";
32
114
 
33
115
  /**
34
- * Implements one action instance. `E` and `R` are the errors and Effect services of the
35
- * body and precondition together.
116
+ * Implements one action instance. `E` and `R` are the errors and Effect services of both
117
+ * phases together. A prepared value stays inside the handler, so handlers with
118
+ * different prepared values share this type.
36
119
  *
37
120
  * @since @next
38
121
  */
39
122
  export type Handler<out A extends Action.Any, out E = never, out R = never> = {
40
123
  readonly [TypeId]: typeof TypeId;
41
124
  readonly action: A;
42
- /** Runs the action body. */
43
- readonly body: Effect.Effect<void, E, R>;
44
- /** Decides whether the body applies. `false` skips the occurrence. */
45
- readonly precondition: Effect.Effect<boolean, E, R> | undefined;
46
- /** Explains a skip when the precondition returns `false`. */
47
- readonly skipReason: string;
125
+ /** Whether the handler has a prepare phase. */
126
+ readonly prepares: boolean;
127
+ /**
128
+ * Runs the prepare phase, if any, and resolves to the next step. Both phases share
129
+ * `scope`, the occurrence's scope, so resources acquired while preparing stay open
130
+ * until the executor closes it after the occurrence ends.
131
+ */
132
+ readonly prepare: (scope: Scope.Scope) => Effect.Effect<Step<E, R>, E, R>;
48
133
  };
49
134
 
50
135
  /**
@@ -78,13 +163,11 @@ export type ActionId<H> = H extends Handler<infer A, any, any> ? A["id"] : never
78
163
  /** @since @next */
79
164
  export const isHandler = (value: unknown): value is Any => Predicate.hasProperty(value, TypeId);
80
165
 
81
- type SkipReason<P> = string | ((payload: P) => string);
82
-
83
- const skipReasonOf = <P>(action: Action.Action<string, P>, reason: SkipReason<P> | undefined) => {
84
- if (reason === undefined) return "Precondition returned false";
85
-
86
- return typeof reason === "string" ? reason : reason(action.payload);
87
- };
166
+ const make = <A extends Action.Any, E, R>(
167
+ action: A,
168
+ prepares: boolean,
169
+ prepare: (scope: Scope.Scope) => Effect.Effect<Step<E, R>, E, R>,
170
+ ): Handler<A, E, R> => ({ [TypeId]: TypeId, action, prepares, prepare });
88
171
 
89
172
  /**
90
173
  * Named Effect services that a Promise handler declares.
@@ -107,6 +190,31 @@ export type PromiseContext<S extends ServiceMap = NoServices> = {
107
190
  readonly services: { readonly [K in keyof S]: S[K]["Service"] };
108
191
  };
109
192
 
193
+ /**
194
+ * The second argument of a Promise apply phase: the Promise context and the action
195
+ * payload.
196
+ *
197
+ * @since @next
198
+ */
199
+ export type PromiseApplyContext<Payload, S extends ServiceMap = NoServices> = PromiseContext<S> & {
200
+ readonly payload: Payload;
201
+ };
202
+
203
+ /**
204
+ * A Promise handler with a prepare phase. `prepare` reads state and returns
205
+ * `Handler.prepared(value)` or `Handler.skip(reason)`; `apply` receives the value. Each
206
+ * phase gets its own signal.
207
+ *
208
+ * @since @next
209
+ */
210
+ export type PromisePhases<Payload, T extends Preparation<unknown>, S extends ServiceMap> = {
211
+ readonly prepare: (payload: Payload, context: PromiseContext<S>) => PromiseLike<T> | T;
212
+ readonly apply: (
213
+ prepared: PreparedValue<T>,
214
+ context: PromiseApplyContext<Payload, S>,
215
+ ) => PromiseLike<unknown>;
216
+ };
217
+
110
218
  type ServiceIds<S extends ServiceMap> = ValueOf<{
111
219
  [K in keyof S]: S[K] extends Context.Key<infer I, any> ? I : never;
112
220
  }>;
@@ -127,7 +235,7 @@ type GuardedError<G> = G extends Schema.Top
127
235
  : never;
128
236
 
129
237
  /** @since @next */
130
- export type PromiseOptions<P, S extends ServiceMap, G extends ReadonlyArray<ErrorGuard>> = {
238
+ export type PromiseOptions<S extends ServiceMap, G extends ReadonlyArray<ErrorGuard>> = {
131
239
  /** Effect services resolved for the callbacks and added to the handler requirements. */
132
240
  readonly services?: S;
133
241
  /**
@@ -136,9 +244,6 @@ export type PromiseOptions<P, S extends ServiceMap, G extends ReadonlyArray<Erro
136
244
  * those errors.
137
245
  */
138
246
  readonly errors?: G;
139
- /** Read-only precondition. Returning `false` skips the occurrence. */
140
- readonly when?: (payload: P, context: PromiseContext<S>) => boolean | PromiseLike<boolean>;
141
- readonly skipReason?: SkipReason<P>;
142
247
  };
143
248
 
144
249
  const declaredError =
@@ -146,10 +251,19 @@ const declaredError =
146
251
  (cause: unknown): cause is GuardedError<G[number]> =>
147
252
  guards.some((guard) => (Schema.isSchema(guard) ? Schema.is(guard)(cause) : guard(cause)));
148
253
 
254
+ type PromiseHandler<A extends Action.Any, S extends ServiceMap, G> = Handler<
255
+ A,
256
+ GuardedError<G> | UnexpectedHandlerError,
257
+ ServiceIds<S>
258
+ >;
259
+
149
260
  /**
150
261
  * Implements an action with Promise callbacks. The callbacks run lazily through
151
- * `Effect.tryPromise`, and receive its `AbortSignal` and the declared services in
152
- * their second argument.
262
+ * `Effect.tryPromise`, and receive its `AbortSignal` and the declared services.
263
+ *
264
+ * Pass one callback to apply the action directly, or `{ prepare, apply }` to decide
265
+ * first. `prepare` must only read: a dry run calls it and never calls `apply`. A real
266
+ * run calls `apply` once with the prepared value.
153
267
  *
154
268
  * @example
155
269
  * ```ts
@@ -162,17 +276,53 @@ const declaredError =
162
276
  * );
163
277
  * ```
164
278
  *
279
+ * @example
280
+ * ```ts
281
+ * Handler.promise(renameTimeout, {
282
+ * prepare: async ({ file, from }, { signal }) => {
283
+ * const config = await readConfig(file, { signal });
284
+ * return from in config ? Handler.prepared(config) : Handler.skip(`${file} has no ${from}`);
285
+ * },
286
+ * apply: async (config, { payload, signal }) => {
287
+ * await writeConfig(payload.file, rename(config, payload), { signal });
288
+ * },
289
+ * });
290
+ * ```
291
+ *
165
292
  * @since @next
166
293
  */
167
- export const promise = <
294
+ export function promise<
295
+ A extends Action.Any,
296
+ const S extends ServiceMap = NoServices,
297
+ const G extends ReadonlyArray<ErrorGuard> = [],
298
+ >(
299
+ action: A,
300
+ apply: (payload: A["payload"], context: PromiseContext<S>) => PromiseLike<unknown>,
301
+ options?: PromiseOptions<S, G>,
302
+ ): PromiseHandler<A, S, G[number]>;
303
+ export function promise<
168
304
  A extends Action.Any,
305
+ T extends Preparation<unknown> = Skip,
169
306
  const S extends ServiceMap = NoServices,
170
307
  const G extends ReadonlyArray<ErrorGuard> = [],
171
308
  >(
172
309
  action: A,
173
- run: (payload: A["payload"], context: PromiseContext<S>) => PromiseLike<unknown>,
174
- options?: PromiseOptions<A["payload"], S, G>,
175
- ): Handler<A, GuardedError<G[number]> | UnexpectedHandlerError, ServiceIds<S>> => {
310
+ phases: PromisePhases<A["payload"], T, S>,
311
+ options?: PromiseOptions<S, G>,
312
+ ): PromiseHandler<A, S, G[number]>;
313
+ export function promise<
314
+ A extends Action.Any,
315
+ S extends ServiceMap,
316
+ G extends ReadonlyArray<ErrorGuard>,
317
+ >(
318
+ action: A,
319
+ run:
320
+ | ((payload: A["payload"], context: PromiseContext<S>) => PromiseLike<unknown>)
321
+ | PromisePhases<A["payload"], Preparation<unknown>, S>,
322
+ options?: PromiseOptions<S, G>,
323
+ ): PromiseHandler<A, S, G[number]> {
324
+ type E = GuardedError<G[number]> | UnexpectedHandlerError;
325
+
176
326
  const isDeclared = declaredError(options?.errors ?? []);
177
327
  const services: ServiceMap = options?.services ?? {};
178
328
  // The handler requires exactly the declared services. Reading them from its context
@@ -189,69 +339,147 @@ export const promise = <
189
339
  ]),
190
340
  ) as { readonly [K in keyof S]: S[K]["Service"] },
191
341
  );
342
+ const unexpected = (phase: Phase, cause: unknown) =>
343
+ new UnexpectedHandlerError({ actionId: action.id, kind: action.kind, phase, cause });
192
344
 
193
345
  const adapt = <T>(
194
346
  phase: Phase,
195
347
  callback: (context: PromiseContext<S>) => PromiseLike<T> | T,
196
- ): Effect.Effect<T, GuardedError<G[number]> | UnexpectedHandlerError, ServiceIds<S>> =>
348
+ ): Effect.Effect<T, E, ServiceIds<S>> =>
197
349
  Effect.flatMap(resolve, (resolved) =>
198
350
  trackPromise((capture) =>
199
351
  Effect.tryPromise({
200
352
  // Declaring `signal` makes Effect.tryPromise allocate an AbortController.
201
353
  try: (signal) =>
202
354
  capture(Promise.resolve(callback({ signal, services: resolved }))),
203
- catch: (cause) =>
204
- isDeclared(cause)
205
- ? cause
206
- : new UnexpectedHandlerError({
207
- actionId: action.id,
208
- kind: action.kind,
209
- phase,
210
- cause,
211
- }),
355
+ catch: (cause) => (isDeclared(cause) ? cause : unexpected(phase, cause)),
212
356
  }),
213
357
  ),
214
358
  );
215
359
 
216
- const when = options?.when;
217
-
218
- return {
219
- [TypeId]: TypeId,
220
- action,
221
- body: Effect.asVoid(adapt("body", (context) => run(action.payload, context))),
222
- precondition:
223
- when === undefined
224
- ? undefined
225
- : adapt("precondition", (context) => when(action.payload, context)),
226
- skipReason: skipReasonOf(action, options?.skipReason),
227
- };
228
- };
360
+ if (Predicate.isFunction(run)) {
361
+ const apply = Effect.asVoid(adapt("apply", (context) => run(action.payload, context)));
229
362
 
230
- /** @since @next */
231
- export type EffectOptions<P, E, R> = {
232
- /** Read-only precondition. Succeeding with `false` skips the occurrence. */
233
- readonly when?: (payload: P) => Effect.Effect<boolean, E, R>;
234
- readonly skipReason?: SkipReason<P>;
363
+ return make(action, false, () => Effect.succeed(applyStep(apply)));
364
+ }
365
+
366
+ const prepare = adapt("prepare", (context) => run.prepare(action.payload, context)).pipe(
367
+ Effect.filterOrFail(isPreparation, () => unexpected("prepare", notAPreparation())),
368
+ Effect.map((preparation): Step<E, ServiceIds<S>> =>
369
+ preparation._tag === "Skip"
370
+ ? preparation
371
+ : applyStep(
372
+ Effect.asVoid(
373
+ adapt("apply", (context) =>
374
+ run.apply(preparation.value, {
375
+ ...context,
376
+ payload: action.payload,
377
+ }),
378
+ ),
379
+ ),
380
+ ),
381
+ ),
382
+ );
383
+
384
+ return make(action, true, () => prepare);
385
+ }
386
+
387
+ /**
388
+ * The second argument of an Effect apply phase.
389
+ *
390
+ * @since @next
391
+ */
392
+ export type EffectApplyContext<Payload> = { readonly payload: Payload };
393
+
394
+ /**
395
+ * An Effect handler with a prepare phase. `prepare` reads state and succeeds with
396
+ * `Handler.prepared(value)` or `Handler.skip(reason)`; `apply` receives the value.
397
+ *
398
+ * @since @next
399
+ */
400
+ export type EffectPhases<Payload, T extends Preparation<unknown>, E1, R1, E2, R2> = {
401
+ readonly prepare: (payload: Payload) => Effect.Effect<T, E1, R1>;
402
+ readonly apply: (
403
+ prepared: PreparedValue<T>,
404
+ context: EffectApplyContext<Payload>,
405
+ ) => Effect.Effect<unknown, E2, R2>;
235
406
  };
236
407
 
237
408
  /**
238
- * Implements an action with an Effect. The body keeps its own errors and services, and
239
- * stops through native Effect interruption.
409
+ * Implements an action with an Effect. The handler keeps its own errors and services,
410
+ * and stops through native Effect interruption.
411
+ *
412
+ * Pass one function to apply the action directly, or `{ prepare, apply }` to decide
413
+ * first. `prepare` must only read: a dry run runs it and never runs `apply`. A real run
414
+ * runs `apply` once with the prepared value. Both phases run in the occurrence's
415
+ * `Scope`, so a resource acquired while preparing, such as a lock, stays open until the
416
+ * occurrence ends; the handler does not require `Scope`.
417
+ *
418
+ * @example
419
+ * ```ts
420
+ * Handler.effect(renameTimeout, {
421
+ * prepare: ({ file, from }) =>
422
+ * Effect.gen(function* () {
423
+ * const files = yield* ConfigFiles;
424
+ * const config = yield* files.lock(file);
425
+ * return from in config.data ? Handler.prepared(config) : Handler.skip(`${file} has no ${from}`);
426
+ * }),
427
+ * apply: (config, { payload }) => config.write(rename(config.data, payload)),
428
+ * });
429
+ * ```
240
430
  *
241
431
  * @since @next
242
432
  */
243
- export const effect = <A extends Action.Any, E = never, R = never, E2 = never, R2 = never>(
433
+ export function effect<A extends Action.Any, E = never, R = never>(
244
434
  action: A,
245
- run: (payload: A["payload"]) => Effect.Effect<unknown, E, R>,
246
- options: EffectOptions<A["payload"], E2, R2> = {},
247
- ): Handler<A, E | E2, R | R2> => {
248
- const when = options.when;
249
-
250
- return {
251
- [TypeId]: TypeId,
252
- action,
253
- body: Effect.asVoid(Effect.suspend(() => run(action.payload))),
254
- precondition: when === undefined ? undefined : Effect.suspend(() => when(action.payload)),
255
- skipReason: skipReasonOf(action, options.skipReason),
256
- };
257
- };
435
+ apply: (payload: A["payload"]) => Effect.Effect<unknown, E, R>,
436
+ ): Handler<A, E, Exclude<R, Scope.Scope>>;
437
+ export function effect<
438
+ A extends Action.Any,
439
+ T extends Preparation<unknown> = Skip,
440
+ E1 = never,
441
+ R1 = never,
442
+ E2 = never,
443
+ R2 = never,
444
+ >(
445
+ action: A,
446
+ phases: EffectPhases<A["payload"], T, E1, R1, E2, R2>,
447
+ ): Handler<A, E1 | E2, Exclude<R1 | R2, Scope.Scope>>;
448
+ export function effect<A extends Action.Any, E1, R1, E2, R2>(
449
+ action: A,
450
+ run:
451
+ | ((payload: A["payload"]) => Effect.Effect<unknown, E1, R1>)
452
+ | EffectPhases<A["payload"], Preparation<unknown>, E1, R1, E2, R2>,
453
+ ): Handler<A, E1 | E2, Exclude<R1 | R2, Scope.Scope>> {
454
+ type E = E1 | E2;
455
+ type R = Exclude<R1 | R2, Scope.Scope>;
456
+
457
+ if (Predicate.isFunction(run)) {
458
+ const apply = Effect.asVoid(Effect.suspend(() => run(action.payload)));
459
+
460
+ return make(action, false, (scope) =>
461
+ Effect.succeed(applyStep<E, R>(Scope.provide(apply, scope))),
462
+ );
463
+ }
464
+
465
+ return make(action, true, (scope) =>
466
+ Effect.suspend(() => run.prepare(action.payload)).pipe(
467
+ Scope.provide(scope),
468
+ Effect.filterOrElse(isPreparation, () => Effect.die(notAPreparation())),
469
+ Effect.map((preparation): Step<E, R> =>
470
+ preparation._tag === "Skip"
471
+ ? preparation
472
+ : applyStep(
473
+ Scope.provide(
474
+ Effect.asVoid(
475
+ Effect.suspend(() =>
476
+ run.apply(preparation.value, { payload: action.payload }),
477
+ ),
478
+ ),
479
+ scope,
480
+ ),
481
+ ),
482
+ ),
483
+ ),
484
+ );
485
+ }
@@ -7,16 +7,18 @@ import { Context, Duration, Effect, Option } from "effect";
7
7
  export type Settlement = {
8
8
  /** How long to keep waiting for an interrupted Promise before reporting it pending. */
9
9
  readonly grace: Duration.Input;
10
- readonly record: (settled: boolean) => void;
10
+ /** Receives an interrupted Promise that did not settle within the grace period. */
11
+ readonly unsettled: (promise: Promise<void>) => void;
11
12
  };
12
13
 
13
14
  export const SettlementReference = Context.Reference<Settlement>("deltafold/Settlement", {
14
- defaultValue: () => ({ grace: Duration.zero, record: () => {} }),
15
+ defaultValue: () => ({ grace: Duration.zero, unsettled: () => {} }),
15
16
  });
16
17
 
17
18
  /**
18
19
  * Runs a Promise-producing effect. If it is interrupted after the Promise started,
19
- * waits up to the settlement grace period and records whether the Promise settled.
20
+ * waits up to the settlement grace period and hands a still-pending Promise to the
21
+ * settlement, which can hold resources until it settles.
20
22
  */
21
23
  export const trackPromise = <T, E, R>(
22
24
  start: (capture: (promise: Promise<T>) => Promise<T>) => Effect.Effect<T, E, R>,
@@ -35,14 +37,15 @@ export const trackPromise = <T, E, R>(
35
37
  const started = pending;
36
38
  if (started === undefined) return;
37
39
 
40
+ const settles = started.then(
41
+ () => undefined,
42
+ () => undefined,
43
+ );
38
44
  const settlement = yield* SettlementReference;
39
- const settled = yield* Effect.promise(() =>
40
- started.then(
41
- () => undefined,
42
- () => undefined,
43
- ),
44
- ).pipe(Effect.timeoutOption(settlement.grace));
45
- settlement.record(Option.isSome(settled));
45
+ const settled = yield* Effect.promise(() => settles).pipe(
46
+ Effect.timeoutOption(settlement.grace),
47
+ );
48
+ if (Option.isNone(settled)) settlement.unsettled(settles);
46
49
  }),
47
50
  ),
48
51
  );