effect-machine 0.3.1 → 0.4.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 +24 -0
- package/dist/_virtual/_rolldown/runtime.js +18 -0
- package/dist/actor.d.ts +256 -0
- package/dist/actor.js +402 -0
- package/dist/cluster/entity-machine.d.ts +90 -0
- package/dist/cluster/entity-machine.js +80 -0
- package/dist/cluster/index.d.ts +3 -0
- package/dist/cluster/index.js +4 -0
- package/dist/cluster/to-entity.d.ts +64 -0
- package/dist/cluster/to-entity.js +53 -0
- package/dist/errors.d.ts +61 -0
- package/dist/errors.js +38 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +14 -0
- package/dist/inspection.d.ts +125 -0
- package/dist/inspection.js +50 -0
- package/dist/internal/brands.d.ts +40 -0
- package/dist/internal/brands.js +0 -0
- package/dist/internal/inspection.d.ts +11 -0
- package/dist/internal/inspection.js +15 -0
- package/dist/internal/transition.d.ts +160 -0
- package/dist/internal/transition.js +238 -0
- package/dist/internal/utils.d.ts +60 -0
- package/dist/internal/utils.js +46 -0
- package/dist/machine.d.ts +278 -0
- package/dist/machine.js +317 -0
- package/{src/persistence/adapter.ts → dist/persistence/adapter.d.ts} +40 -72
- package/dist/persistence/adapter.js +27 -0
- package/dist/persistence/adapters/in-memory.d.ts +32 -0
- package/dist/persistence/adapters/in-memory.js +176 -0
- package/dist/persistence/index.d.ts +5 -0
- package/dist/persistence/index.js +6 -0
- package/dist/persistence/persistent-actor.d.ts +50 -0
- package/dist/persistence/persistent-actor.js +358 -0
- package/{src/persistence/persistent-machine.ts → dist/persistence/persistent-machine.d.ts} +28 -54
- package/dist/persistence/persistent-machine.js +24 -0
- package/dist/schema.d.ts +141 -0
- package/dist/schema.js +165 -0
- package/dist/slot.d.ts +130 -0
- package/dist/slot.js +99 -0
- package/dist/testing.d.ts +142 -0
- package/dist/testing.js +138 -0
- package/package.json +28 -14
- package/src/actor.ts +0 -1058
- package/src/cluster/entity-machine.ts +0 -201
- package/src/cluster/index.ts +0 -43
- package/src/cluster/to-entity.ts +0 -99
- package/src/errors.ts +0 -64
- package/src/index.ts +0 -105
- package/src/inspection.ts +0 -178
- package/src/internal/brands.ts +0 -51
- package/src/internal/inspection.ts +0 -18
- package/src/internal/transition.ts +0 -489
- package/src/internal/utils.ts +0 -80
- package/src/machine.ts +0 -836
- package/src/persistence/adapters/in-memory.ts +0 -294
- package/src/persistence/index.ts +0 -24
- package/src/persistence/persistent-actor.ts +0 -791
- package/src/schema.ts +0 -362
- package/src/slot.ts +0 -281
- package/src/testing.ts +0 -284
- package/tsconfig.json +0 -65
package/dist/machine.js
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
import { __exportAll } from "./_virtual/_rolldown/runtime.js";
|
|
2
|
+
import { getTag } from "./internal/utils.js";
|
|
3
|
+
import { ProvisionValidationError, SlotProvisionError } from "./errors.js";
|
|
4
|
+
import { persist } from "./persistence/persistent-machine.js";
|
|
5
|
+
import { MachineContextTag } from "./slot.js";
|
|
6
|
+
import { findTransitions, invalidateIndex } from "./internal/transition.js";
|
|
7
|
+
import { createActor } from "./actor.js";
|
|
8
|
+
import { Cause, Effect, Exit, Option, Scope } from "effect";
|
|
9
|
+
|
|
10
|
+
//#region src/machine.ts
|
|
11
|
+
var machine_exports = /* @__PURE__ */ __exportAll({
|
|
12
|
+
BuiltMachine: () => BuiltMachine,
|
|
13
|
+
Machine: () => Machine,
|
|
14
|
+
findTransitions: () => findTransitions,
|
|
15
|
+
make: () => make,
|
|
16
|
+
spawn: () => spawn
|
|
17
|
+
});
|
|
18
|
+
/**
|
|
19
|
+
* A finalized machine ready for spawning.
|
|
20
|
+
*
|
|
21
|
+
* Created by calling `.build()` on a `Machine`. This is the only type
|
|
22
|
+
* accepted by `Machine.spawn` and `ActorSystem.spawn` (regular overload).
|
|
23
|
+
* Testing utilities (`simulate`, `createTestHarness`, etc.) still accept `Machine`.
|
|
24
|
+
*/
|
|
25
|
+
var BuiltMachine = class {
|
|
26
|
+
/** @internal */
|
|
27
|
+
_inner;
|
|
28
|
+
/** @internal */
|
|
29
|
+
constructor(machine) {
|
|
30
|
+
this._inner = machine;
|
|
31
|
+
}
|
|
32
|
+
get initial() {
|
|
33
|
+
return this._inner.initial;
|
|
34
|
+
}
|
|
35
|
+
persist(config) {
|
|
36
|
+
return this._inner.persist(config);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Machine definition with fluent builder API.
|
|
41
|
+
*
|
|
42
|
+
* Type parameters:
|
|
43
|
+
* - `State`: The state union type
|
|
44
|
+
* - `Event`: The event union type
|
|
45
|
+
* - `R`: Effect requirements
|
|
46
|
+
* - `_SD`: State schema definition (for compile-time validation)
|
|
47
|
+
* - `_ED`: Event schema definition (for compile-time validation)
|
|
48
|
+
* - `GD`: Guard definitions
|
|
49
|
+
* - `EFD`: Effect definitions
|
|
50
|
+
*/
|
|
51
|
+
var Machine = class Machine {
|
|
52
|
+
initial;
|
|
53
|
+
/** @internal */ _transitions;
|
|
54
|
+
/** @internal */ _spawnEffects;
|
|
55
|
+
/** @internal */ _backgroundEffects;
|
|
56
|
+
/** @internal */ _finalStates;
|
|
57
|
+
/** @internal */ _guardsSchema;
|
|
58
|
+
/** @internal */ _effectsSchema;
|
|
59
|
+
/** @internal */ _guardHandlers;
|
|
60
|
+
/** @internal */ _effectHandlers;
|
|
61
|
+
/** @internal */ _slots;
|
|
62
|
+
stateSchema;
|
|
63
|
+
eventSchema;
|
|
64
|
+
/**
|
|
65
|
+
* Context tag for accessing machine state/event/self in slot handlers.
|
|
66
|
+
* Uses shared module-level tag for all machines.
|
|
67
|
+
*/
|
|
68
|
+
Context = MachineContextTag;
|
|
69
|
+
get transitions() {
|
|
70
|
+
return this._transitions;
|
|
71
|
+
}
|
|
72
|
+
get spawnEffects() {
|
|
73
|
+
return this._spawnEffects;
|
|
74
|
+
}
|
|
75
|
+
get backgroundEffects() {
|
|
76
|
+
return this._backgroundEffects;
|
|
77
|
+
}
|
|
78
|
+
get finalStates() {
|
|
79
|
+
return this._finalStates;
|
|
80
|
+
}
|
|
81
|
+
get guardsSchema() {
|
|
82
|
+
return this._guardsSchema;
|
|
83
|
+
}
|
|
84
|
+
get effectsSchema() {
|
|
85
|
+
return this._effectsSchema;
|
|
86
|
+
}
|
|
87
|
+
/** @internal */
|
|
88
|
+
constructor(initial, stateSchema, eventSchema, guardsSchema, effectsSchema) {
|
|
89
|
+
this.initial = initial;
|
|
90
|
+
this._transitions = [];
|
|
91
|
+
this._spawnEffects = [];
|
|
92
|
+
this._backgroundEffects = [];
|
|
93
|
+
this._finalStates = /* @__PURE__ */ new Set();
|
|
94
|
+
this._guardsSchema = guardsSchema;
|
|
95
|
+
this._effectsSchema = effectsSchema;
|
|
96
|
+
this._guardHandlers = /* @__PURE__ */ new Map();
|
|
97
|
+
this._effectHandlers = /* @__PURE__ */ new Map();
|
|
98
|
+
this.stateSchema = stateSchema;
|
|
99
|
+
this.eventSchema = eventSchema;
|
|
100
|
+
this._slots = {
|
|
101
|
+
guards: this._guardsSchema !== void 0 ? this._guardsSchema._createSlots((name, params) => Effect.flatMap(Effect.serviceOptional(this.Context).pipe(Effect.orDie), (ctx) => {
|
|
102
|
+
const handler = this._guardHandlers.get(name);
|
|
103
|
+
if (handler === void 0) return Effect.die(new SlotProvisionError({
|
|
104
|
+
slotName: name,
|
|
105
|
+
slotType: "guard"
|
|
106
|
+
}));
|
|
107
|
+
const result = handler(params, ctx);
|
|
108
|
+
return typeof result === "boolean" ? Effect.succeed(result) : result;
|
|
109
|
+
})) : {},
|
|
110
|
+
effects: this._effectsSchema !== void 0 ? this._effectsSchema._createSlots((name, params) => Effect.flatMap(Effect.serviceOptional(this.Context).pipe(Effect.orDie), (ctx) => {
|
|
111
|
+
const handler = this._effectHandlers.get(name);
|
|
112
|
+
if (handler === void 0) return Effect.die(new SlotProvisionError({
|
|
113
|
+
slotName: name,
|
|
114
|
+
slotType: "effect"
|
|
115
|
+
}));
|
|
116
|
+
return handler(params, ctx);
|
|
117
|
+
})) : {}
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
on(stateOrStates, event, handler) {
|
|
121
|
+
const states = Array.isArray(stateOrStates) ? stateOrStates : [stateOrStates];
|
|
122
|
+
for (const s of states) this.addTransition(s, event, handler, false);
|
|
123
|
+
return this;
|
|
124
|
+
}
|
|
125
|
+
reenter(stateOrStates, event, handler) {
|
|
126
|
+
const states = Array.isArray(stateOrStates) ? stateOrStates : [stateOrStates];
|
|
127
|
+
for (const s of states) this.addTransition(s, event, handler, true);
|
|
128
|
+
return this;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Register a wildcard transition that fires from any state when no specific transition matches.
|
|
132
|
+
* Specific `.on()` transitions always take priority over `.onAny()`.
|
|
133
|
+
*/
|
|
134
|
+
onAny(event, handler) {
|
|
135
|
+
const transition = {
|
|
136
|
+
stateTag: "*",
|
|
137
|
+
eventTag: getTag(event),
|
|
138
|
+
handler,
|
|
139
|
+
reenter: false
|
|
140
|
+
};
|
|
141
|
+
this._transitions.push(transition);
|
|
142
|
+
invalidateIndex(this);
|
|
143
|
+
return this;
|
|
144
|
+
}
|
|
145
|
+
/** @internal */
|
|
146
|
+
addTransition(state, event, handler, reenter) {
|
|
147
|
+
const transition = {
|
|
148
|
+
stateTag: getTag(state),
|
|
149
|
+
eventTag: getTag(event),
|
|
150
|
+
handler,
|
|
151
|
+
reenter
|
|
152
|
+
};
|
|
153
|
+
this._transitions.push(transition);
|
|
154
|
+
invalidateIndex(this);
|
|
155
|
+
return this;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* State-scoped effect that is forked on state entry and automatically cancelled on state exit.
|
|
159
|
+
* Use effect slots defined via `Slot.Effects` for the actual work.
|
|
160
|
+
*
|
|
161
|
+
* @example
|
|
162
|
+
* ```ts
|
|
163
|
+
* const MyEffects = Slot.Effects({
|
|
164
|
+
* fetchData: { url: Schema.String },
|
|
165
|
+
* });
|
|
166
|
+
*
|
|
167
|
+
* machine
|
|
168
|
+
* .spawn(State.Loading, ({ effects, state }) => effects.fetchData({ url: state.url }))
|
|
169
|
+
* .build({
|
|
170
|
+
* fetchData: ({ url }, { self }) =>
|
|
171
|
+
* Effect.gen(function* () {
|
|
172
|
+
* yield* Effect.addFinalizer(() => Effect.log("Leaving Loading"));
|
|
173
|
+
* const data = yield* Http.get(url);
|
|
174
|
+
* yield* self.send(Event.Loaded({ data }));
|
|
175
|
+
* }),
|
|
176
|
+
* });
|
|
177
|
+
* ```
|
|
178
|
+
*/
|
|
179
|
+
spawn(state, handler) {
|
|
180
|
+
const stateTag = getTag(state);
|
|
181
|
+
this._spawnEffects.push({
|
|
182
|
+
stateTag,
|
|
183
|
+
handler
|
|
184
|
+
});
|
|
185
|
+
invalidateIndex(this);
|
|
186
|
+
return this;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* State-scoped task that runs on entry and sends success/failure events.
|
|
190
|
+
* Interrupts do not emit failure events.
|
|
191
|
+
*/
|
|
192
|
+
task(state, run, options) {
|
|
193
|
+
const handler = Effect.fn("effect-machine.task")(function* (ctx) {
|
|
194
|
+
const exit = yield* Effect.exit(run(ctx));
|
|
195
|
+
if (Exit.isSuccess(exit)) {
|
|
196
|
+
yield* ctx.self.send(options.onSuccess(exit.value, ctx));
|
|
197
|
+
yield* Effect.yieldNow();
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
const cause = exit.cause;
|
|
201
|
+
if (Cause.isInterruptedOnly(cause)) return;
|
|
202
|
+
if (options.onFailure !== void 0) {
|
|
203
|
+
yield* ctx.self.send(options.onFailure(cause, ctx));
|
|
204
|
+
yield* Effect.yieldNow();
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
return yield* Effect.failCause(cause).pipe(Effect.orDie);
|
|
208
|
+
});
|
|
209
|
+
return this.spawn(state, handler);
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Machine-lifetime effect that is forked on actor spawn and runs until the actor stops.
|
|
213
|
+
* Use effect slots defined via `Slot.Effects` for the actual work.
|
|
214
|
+
*
|
|
215
|
+
* @example
|
|
216
|
+
* ```ts
|
|
217
|
+
* const MyEffects = Slot.Effects({
|
|
218
|
+
* heartbeat: {},
|
|
219
|
+
* });
|
|
220
|
+
*
|
|
221
|
+
* machine
|
|
222
|
+
* .background(({ effects }) => effects.heartbeat())
|
|
223
|
+
* .build({
|
|
224
|
+
* heartbeat: (_, { self }) =>
|
|
225
|
+
* Effect.forever(
|
|
226
|
+
* Effect.sleep("30 seconds").pipe(Effect.andThen(self.send(Event.Ping)))
|
|
227
|
+
* ),
|
|
228
|
+
* });
|
|
229
|
+
* ```
|
|
230
|
+
*/
|
|
231
|
+
background(handler) {
|
|
232
|
+
this._backgroundEffects.push({ handler });
|
|
233
|
+
return this;
|
|
234
|
+
}
|
|
235
|
+
final(state) {
|
|
236
|
+
const stateTag = getTag(state);
|
|
237
|
+
this._finalStates.add(stateTag);
|
|
238
|
+
return this;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Finalize the machine. Returns a `BuiltMachine` — the only type accepted by `Machine.spawn`.
|
|
242
|
+
*
|
|
243
|
+
* - Machines with slots: pass implementations as the first argument.
|
|
244
|
+
* - Machines without slots: call with no arguments.
|
|
245
|
+
*/
|
|
246
|
+
build(...args) {
|
|
247
|
+
const handlers = args[0];
|
|
248
|
+
if (handlers !== void 0) {
|
|
249
|
+
const requiredSlots = /* @__PURE__ */ new Set();
|
|
250
|
+
if (this._guardsSchema !== void 0) for (const name of Object.keys(this._guardsSchema.definitions)) requiredSlots.add(name);
|
|
251
|
+
if (this._effectsSchema !== void 0) for (const name of Object.keys(this._effectsSchema.definitions)) requiredSlots.add(name);
|
|
252
|
+
const providedSlots = new Set(Object.keys(handlers));
|
|
253
|
+
const missing = [];
|
|
254
|
+
const extra = [];
|
|
255
|
+
for (const name of requiredSlots) if (!providedSlots.has(name)) missing.push(name);
|
|
256
|
+
for (const name of providedSlots) if (!requiredSlots.has(name)) extra.push(name);
|
|
257
|
+
if (missing.length > 0 || extra.length > 0) throw new ProvisionValidationError({
|
|
258
|
+
missing,
|
|
259
|
+
extra
|
|
260
|
+
});
|
|
261
|
+
const result = new Machine(this.initial, this.stateSchema, this.eventSchema, this._guardsSchema, this._effectsSchema);
|
|
262
|
+
result._transitions = [...this._transitions];
|
|
263
|
+
result._finalStates = new Set(this._finalStates);
|
|
264
|
+
result._spawnEffects = [...this._spawnEffects];
|
|
265
|
+
result._backgroundEffects = [...this._backgroundEffects];
|
|
266
|
+
const anyHandlers = handlers;
|
|
267
|
+
if (this._guardsSchema !== void 0) for (const name of Object.keys(this._guardsSchema.definitions)) result._guardHandlers.set(name, anyHandlers[name]);
|
|
268
|
+
if (this._effectsSchema !== void 0) for (const name of Object.keys(this._effectsSchema.definitions)) result._effectHandlers.set(name, anyHandlers[name]);
|
|
269
|
+
return new BuiltMachine(result);
|
|
270
|
+
}
|
|
271
|
+
return new BuiltMachine(this);
|
|
272
|
+
}
|
|
273
|
+
/** @internal Persist from raw Machine — prefer BuiltMachine.persist() */
|
|
274
|
+
persist(config) {
|
|
275
|
+
return persist(config)(this);
|
|
276
|
+
}
|
|
277
|
+
static make(config) {
|
|
278
|
+
return new Machine(config.initial, config.state, config.event, config.guards, config.effects);
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
const make = Machine.make;
|
|
282
|
+
/**
|
|
283
|
+
* Spawn an actor directly without ActorSystem ceremony.
|
|
284
|
+
* Accepts only `BuiltMachine` (call `.build()` first).
|
|
285
|
+
*
|
|
286
|
+
* **Single actor, no registry.** Caller manages lifetime via `actor.stop`.
|
|
287
|
+
* If a `Scope` exists in context, cleanup attaches automatically on scope close.
|
|
288
|
+
*
|
|
289
|
+
* For registry, lookup by ID, persistence, or multi-actor coordination,
|
|
290
|
+
* use `ActorSystemService` / `system.spawn` instead.
|
|
291
|
+
*
|
|
292
|
+
* @example
|
|
293
|
+
* ```ts
|
|
294
|
+
* // Fire-and-forget — caller manages lifetime
|
|
295
|
+
* const actor = yield* Machine.spawn(machine.build());
|
|
296
|
+
* yield* actor.send(Event.Start);
|
|
297
|
+
* yield* actor.awaitFinal;
|
|
298
|
+
* yield* actor.stop;
|
|
299
|
+
*
|
|
300
|
+
* // Scope-aware — auto-cleans up on scope close
|
|
301
|
+
* yield* Effect.scoped(Effect.gen(function* () {
|
|
302
|
+
* const actor = yield* Machine.spawn(machine.build());
|
|
303
|
+
* yield* actor.send(Event.Start);
|
|
304
|
+
* // actor.stop called automatically when scope closes
|
|
305
|
+
* }));
|
|
306
|
+
* ```
|
|
307
|
+
*/
|
|
308
|
+
const spawnImpl = Effect.fn("effect-machine.spawn")(function* (built, id) {
|
|
309
|
+
const actor = yield* createActor(id ?? `actor-${Math.random().toString(36).slice(2)}`, built._inner);
|
|
310
|
+
const maybeScope = yield* Effect.serviceOption(Scope.Scope);
|
|
311
|
+
if (Option.isSome(maybeScope)) yield* Scope.addFinalizer(maybeScope.value, actor.stop);
|
|
312
|
+
return actor;
|
|
313
|
+
});
|
|
314
|
+
const spawn = spawnImpl;
|
|
315
|
+
|
|
316
|
+
//#endregion
|
|
317
|
+
export { BuiltMachine, Machine, findTransitions, machine_exports, make, spawn };
|
|
@@ -1,14 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
import type { PersistentActorRef } from "./persistent-actor.js";
|
|
5
|
-
import type { DuplicateActorError } from "../errors.js";
|
|
1
|
+
import { DuplicateActorError } from "../errors.js";
|
|
2
|
+
import { PersistentActorRef } from "./persistent-actor.js";
|
|
3
|
+
import { Context, Effect, Option, Schema } from "effect";
|
|
6
4
|
|
|
5
|
+
//#region src/persistence/adapter.d.ts
|
|
7
6
|
/**
|
|
8
7
|
* Metadata for a persisted actor.
|
|
9
8
|
* Used for discovery and filtering during bulk restore.
|
|
10
9
|
*/
|
|
11
|
-
|
|
10
|
+
interface ActorMetadata {
|
|
12
11
|
readonly id: string;
|
|
13
12
|
/** User-provided identifier for the machine type */
|
|
14
13
|
readonly machineType: string;
|
|
@@ -18,46 +17,41 @@ export interface ActorMetadata {
|
|
|
18
17
|
/** Current state _tag value */
|
|
19
18
|
readonly stateTag: string;
|
|
20
19
|
}
|
|
21
|
-
|
|
22
20
|
/**
|
|
23
21
|
* Result of a bulk restore operation.
|
|
24
22
|
* Contains both successfully restored actors and failures.
|
|
25
23
|
*/
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
> {
|
|
24
|
+
interface RestoreResult<S extends {
|
|
25
|
+
readonly _tag: string;
|
|
26
|
+
}, E extends {
|
|
27
|
+
readonly _tag: string;
|
|
28
|
+
}, R = never> {
|
|
31
29
|
readonly restored: ReadonlyArray<PersistentActorRef<S, E, R>>;
|
|
32
30
|
readonly failed: ReadonlyArray<RestoreFailure>;
|
|
33
31
|
}
|
|
34
|
-
|
|
35
32
|
/**
|
|
36
33
|
* A single restore failure with actor ID and error details.
|
|
37
34
|
*/
|
|
38
|
-
|
|
35
|
+
interface RestoreFailure {
|
|
39
36
|
readonly id: string;
|
|
40
37
|
readonly error: PersistenceError | DuplicateActorError;
|
|
41
38
|
}
|
|
42
|
-
|
|
43
39
|
/**
|
|
44
40
|
* Snapshot of actor state at a point in time
|
|
45
41
|
*/
|
|
46
|
-
|
|
42
|
+
interface Snapshot<S> {
|
|
47
43
|
readonly state: S;
|
|
48
44
|
readonly version: number;
|
|
49
45
|
readonly timestamp: number;
|
|
50
46
|
}
|
|
51
|
-
|
|
52
47
|
/**
|
|
53
48
|
* Persisted event with metadata
|
|
54
49
|
*/
|
|
55
|
-
|
|
50
|
+
interface PersistedEvent<E> {
|
|
56
51
|
readonly event: E;
|
|
57
52
|
readonly version: number;
|
|
58
53
|
readonly timestamp: number;
|
|
59
54
|
}
|
|
60
|
-
|
|
61
55
|
/**
|
|
62
56
|
* Adapter for persisting actor state and events.
|
|
63
57
|
*
|
|
@@ -65,106 +59,80 @@ export interface PersistedEvent<E> {
|
|
|
65
59
|
* Schema parameters ensure type-safe serialization/deserialization.
|
|
66
60
|
* Schemas must have no context requirements (use Schema<S, SI, never>).
|
|
67
61
|
*/
|
|
68
|
-
|
|
62
|
+
interface PersistenceAdapter {
|
|
69
63
|
/**
|
|
70
64
|
* Save a snapshot of actor state.
|
|
71
65
|
* Implementations should use optimistic locking — fail if version mismatch.
|
|
72
66
|
*/
|
|
73
|
-
readonly saveSnapshot: <S, SI>(
|
|
74
|
-
id: string,
|
|
75
|
-
snapshot: Snapshot<S>,
|
|
76
|
-
schema: Schema.Schema<S, SI, never>,
|
|
77
|
-
) => Effect.Effect<void, PersistenceError | VersionConflictError>;
|
|
78
|
-
|
|
67
|
+
readonly saveSnapshot: <S, SI>(id: string, snapshot: Snapshot<S>, schema: Schema.Schema<S, SI, never>) => Effect.Effect<void, PersistenceError | VersionConflictError>;
|
|
79
68
|
/**
|
|
80
69
|
* Load the latest snapshot for an actor.
|
|
81
70
|
* Returns None if no snapshot exists.
|
|
82
71
|
*/
|
|
83
|
-
readonly loadSnapshot: <S, SI>(
|
|
84
|
-
id: string,
|
|
85
|
-
schema: Schema.Schema<S, SI, never>,
|
|
86
|
-
) => Effect.Effect<Option.Option<Snapshot<S>>, PersistenceError>;
|
|
87
|
-
|
|
72
|
+
readonly loadSnapshot: <S, SI>(id: string, schema: Schema.Schema<S, SI, never>) => Effect.Effect<Option.Option<Snapshot<S>>, PersistenceError>;
|
|
88
73
|
/**
|
|
89
74
|
* Append an event to the actor's event journal.
|
|
90
75
|
*/
|
|
91
|
-
readonly appendEvent: <E, EI>(
|
|
92
|
-
id: string,
|
|
93
|
-
event: PersistedEvent<E>,
|
|
94
|
-
schema: Schema.Schema<E, EI, never>,
|
|
95
|
-
) => Effect.Effect<void, PersistenceError>;
|
|
96
|
-
|
|
76
|
+
readonly appendEvent: <E, EI>(id: string, event: PersistedEvent<E>, schema: Schema.Schema<E, EI, never>) => Effect.Effect<void, PersistenceError>;
|
|
97
77
|
/**
|
|
98
78
|
* Load events from the journal, optionally after a specific version.
|
|
99
79
|
*/
|
|
100
|
-
readonly loadEvents: <E, EI>(
|
|
101
|
-
id: string,
|
|
102
|
-
schema: Schema.Schema<E, EI, never>,
|
|
103
|
-
afterVersion?: number,
|
|
104
|
-
) => Effect.Effect<ReadonlyArray<PersistedEvent<E>>, PersistenceError>;
|
|
105
|
-
|
|
80
|
+
readonly loadEvents: <E, EI>(id: string, schema: Schema.Schema<E, EI, never>, afterVersion?: number) => Effect.Effect<ReadonlyArray<PersistedEvent<E>>, PersistenceError>;
|
|
106
81
|
/**
|
|
107
82
|
* Delete all persisted data for an actor (snapshot + events).
|
|
108
83
|
*/
|
|
109
84
|
readonly deleteActor: (id: string) => Effect.Effect<void, PersistenceError>;
|
|
110
|
-
|
|
111
|
-
// --- Optional registry methods for actor discovery ---
|
|
112
|
-
|
|
113
85
|
/**
|
|
114
86
|
* List all persisted actor metadata.
|
|
115
87
|
* Optional — adapters without registry support can omit this.
|
|
116
88
|
*/
|
|
117
89
|
readonly listActors?: () => Effect.Effect<ReadonlyArray<ActorMetadata>, PersistenceError>;
|
|
118
|
-
|
|
119
90
|
/**
|
|
120
91
|
* Save or update actor metadata.
|
|
121
92
|
* Called on spawn and state transitions.
|
|
122
93
|
* Optional — adapters without registry support can omit this.
|
|
123
94
|
*/
|
|
124
95
|
readonly saveMetadata?: (metadata: ActorMetadata) => Effect.Effect<void, PersistenceError>;
|
|
125
|
-
|
|
126
96
|
/**
|
|
127
97
|
* Delete actor metadata.
|
|
128
98
|
* Called when actor is deleted.
|
|
129
99
|
* Optional — adapters without registry support can omit this.
|
|
130
100
|
*/
|
|
131
101
|
readonly deleteMetadata?: (id: string) => Effect.Effect<void, PersistenceError>;
|
|
132
|
-
|
|
133
102
|
/**
|
|
134
103
|
* Load metadata for a specific actor by ID.
|
|
135
104
|
* Returns None if no metadata exists.
|
|
136
105
|
* Optional — adapters without registry support can omit this.
|
|
137
106
|
*/
|
|
138
|
-
readonly loadMetadata?: (
|
|
139
|
-
id: string,
|
|
140
|
-
) => Effect.Effect<Option.Option<ActorMetadata>, PersistenceError>;
|
|
107
|
+
readonly loadMetadata?: (id: string) => Effect.Effect<Option.Option<ActorMetadata>, PersistenceError>;
|
|
141
108
|
}
|
|
142
|
-
|
|
109
|
+
declare const PersistenceError_base: Schema.TaggedErrorClass<PersistenceError, "PersistenceError", {
|
|
110
|
+
readonly _tag: Schema.tag<"PersistenceError">;
|
|
111
|
+
} & {
|
|
112
|
+
operation: typeof Schema.String;
|
|
113
|
+
actorId: typeof Schema.String;
|
|
114
|
+
cause: Schema.optional<typeof Schema.Unknown>;
|
|
115
|
+
message: Schema.optional<typeof Schema.String>;
|
|
116
|
+
}>;
|
|
143
117
|
/**
|
|
144
118
|
* Error type for persistence operations
|
|
145
119
|
*/
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
120
|
+
declare class PersistenceError extends PersistenceError_base {}
|
|
121
|
+
declare const VersionConflictError_base: Schema.TaggedErrorClass<VersionConflictError, "VersionConflictError", {
|
|
122
|
+
readonly _tag: Schema.tag<"VersionConflictError">;
|
|
123
|
+
} & {
|
|
124
|
+
actorId: typeof Schema.String;
|
|
125
|
+
expectedVersion: typeof Schema.Number;
|
|
126
|
+
actualVersion: typeof Schema.Number;
|
|
127
|
+
}>;
|
|
153
128
|
/**
|
|
154
129
|
* Version conflict error — snapshot version doesn't match expected
|
|
155
130
|
*/
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
{
|
|
159
|
-
actorId: Schema.String,
|
|
160
|
-
expectedVersion: Schema.Number,
|
|
161
|
-
actualVersion: Schema.Number,
|
|
162
|
-
},
|
|
163
|
-
) {}
|
|
164
|
-
|
|
131
|
+
declare class VersionConflictError extends VersionConflictError_base {}
|
|
132
|
+
declare const PersistenceAdapterTag_base: Context.TagClass<PersistenceAdapterTag, "effect-machine/src/persistence/adapter/PersistenceAdapterTag", PersistenceAdapter>;
|
|
165
133
|
/**
|
|
166
134
|
* PersistenceAdapter service tag
|
|
167
135
|
*/
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
136
|
+
declare class PersistenceAdapterTag extends PersistenceAdapterTag_base {}
|
|
137
|
+
//#endregion
|
|
138
|
+
export { ActorMetadata, PersistedEvent, PersistenceAdapter, PersistenceAdapterTag, PersistenceError, RestoreFailure, RestoreResult, Snapshot, VersionConflictError };
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { Context, Schema } from "effect";
|
|
2
|
+
|
|
3
|
+
//#region src/persistence/adapter.ts
|
|
4
|
+
/**
|
|
5
|
+
* Error type for persistence operations
|
|
6
|
+
*/
|
|
7
|
+
var PersistenceError = class extends Schema.TaggedError()("PersistenceError", {
|
|
8
|
+
operation: Schema.String,
|
|
9
|
+
actorId: Schema.String,
|
|
10
|
+
cause: Schema.optional(Schema.Unknown),
|
|
11
|
+
message: Schema.optional(Schema.String)
|
|
12
|
+
}) {};
|
|
13
|
+
/**
|
|
14
|
+
* Version conflict error — snapshot version doesn't match expected
|
|
15
|
+
*/
|
|
16
|
+
var VersionConflictError = class extends Schema.TaggedError()("VersionConflictError", {
|
|
17
|
+
actorId: Schema.String,
|
|
18
|
+
expectedVersion: Schema.Number,
|
|
19
|
+
actualVersion: Schema.Number
|
|
20
|
+
}) {};
|
|
21
|
+
/**
|
|
22
|
+
* PersistenceAdapter service tag
|
|
23
|
+
*/
|
|
24
|
+
var PersistenceAdapterTag = class extends Context.Tag("effect-machine/src/persistence/adapter/PersistenceAdapterTag")() {};
|
|
25
|
+
|
|
26
|
+
//#endregion
|
|
27
|
+
export { PersistenceAdapterTag, PersistenceError, VersionConflictError };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { PersistenceAdapter, PersistenceAdapterTag } from "../adapter.js";
|
|
2
|
+
import { Effect, Layer } from "effect";
|
|
3
|
+
|
|
4
|
+
//#region src/persistence/adapters/in-memory.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Create an in-memory persistence adapter effect.
|
|
7
|
+
* Returns the adapter directly for custom layer composition.
|
|
8
|
+
*/
|
|
9
|
+
declare const makeInMemoryPersistenceAdapter: Effect.Effect<PersistenceAdapter, never, never>;
|
|
10
|
+
/**
|
|
11
|
+
* In-memory persistence adapter layer.
|
|
12
|
+
* Data is not persisted across process restarts.
|
|
13
|
+
*
|
|
14
|
+
* NOTE: Each `Effect.provide(InMemoryPersistenceAdapter)` creates a NEW adapter
|
|
15
|
+
* with empty storage. For tests that need persistent storage across multiple
|
|
16
|
+
* runPromise calls, use `makeInMemoryPersistenceAdapter` with a shared scope.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* const program = Effect.gen(function* () {
|
|
21
|
+
* const system = yield* ActorSystemService;
|
|
22
|
+
* const actor = yield* system.spawn("my-actor", persistentMachine);
|
|
23
|
+
* // ...
|
|
24
|
+
* }).pipe(
|
|
25
|
+
* Effect.provide(InMemoryPersistenceAdapter),
|
|
26
|
+
* Effect.provide(ActorSystemDefault),
|
|
27
|
+
* );
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
declare const InMemoryPersistenceAdapter: Layer.Layer<PersistenceAdapterTag>;
|
|
31
|
+
//#endregion
|
|
32
|
+
export { InMemoryPersistenceAdapter, makeInMemoryPersistenceAdapter };
|