Repository navigation
Replies: 2 comments
|
@davidkpiano the addition of Is this the intended approach for recursively executing effects on child / parent actors within an actor hierarchy? const runtime: ActorSystemRuntime = {
spawnActor: (_source, actor) => {
log('spawnActor', actor.id);
},
startActor: async (actor) => {
log('startActor', actor.id);
// get start effects of the child actor
const [, startEffects] = initialTransition(
actor.logic,
actor.getSnapshot(),
actor.options.input // make sure to pass the input
);
// Execute the child effects
await executeEffects(startEffects, runtime);
},
stopActor: async (actor) => {
log('stopActor', actor.id);
// get stop effects of the child actor
const [, exitEffects] = transition(actor.logic, actor.getSnapshot(), {
type: XSTATE_STOP
});
// Execute the child effects
await executeEffects(exitEffects, runtime);
},
terminateActor: async (actor, termination) => {
log('terminateActor', actor.id, termination.status);
// get parent actor from the private prop
const parent = actor._parent;
if (!parent) return;
// on actor termination - build the done / error event
const event =
termination.status === 'done'
? createDoneActorEvent(actor.id, termination.output)
: createErrorActorEvent(actor.id, termination.error);
// pass the event to the parent and retrieve the parent's effects.
const [, parentEffects] = transition(
parent.logic,
parent.getSnapshot(),
event
);
// Execute the child effects
await executeEffects(parentEffects, runtime);
},
sendEvent: (source, target, event) => {
log('sendEvent', `${source.id} → ${target.id}`, event.type);
},
emitEvent: (source, event) => {
log('emitEvent', source.id, event.type);
},
scheduleTimer: (source, id, delay) => {
log('scheduleTimer', source.id, id, `${delay}ms`);
},
cancelTimer: (source, id) => {
log('cancelTimer', source.id, id);
},
cancelAllTimers: (source) => {
log('cancelAllTimers', source.id);
}
};The use case I imagine is something like this:
const grandchildMachine = createMachine({
id: 'grandchild',
initial: 'idle',
states: {
idle: {
timeout: 1000,
onTimeout: { target: 'ended' }
},
ended: { type: 'final' }
}
});
const childMachine = createMachine({
id: 'child',
actorSources: { grandchild: grandchildMachine },
context: (input) => ({ value: input.value }),
initial: 'idle',
states: {
idle: {
invoke: {
id: 'grandchild',
src: 'grandchild',
onDone: { target: 'ended' }
}
},
ended: {
type: 'final'
}
}
});
const rootMachine = createMachine({
id: 'root',
actorSources: { child: childMachine },
initial: 'first',
states: {
first: {
invoke: {
id: 'child',
src: 'child',
onDone: { target: 'ended' },
input: () => ({ value: 'hello' })
},
on: { NEXT: { target: 'second' } }
},
second: {
on: { PREV: { target: 'first' } }
},
ended: {
type: 'final'
}
}
}); |
|
@davidkpiano I'm struggling with how to transition and persist a child actor, and I'd really appreciate it if you could point me in the right direction. I'm building a durable XState runtime on top of Convex. On every transition I persist the entire snapshot tree to a document, then restore it when the next event arrives. For a single actor this works cleanly: const persistedSnapshot = await loadSnapshot();
const snapshot = parentMachine.restoreSnapshot(persistedSnapshot);
const [nextSnapshot, effects] = transition(
parentMachine,
snapshot,
event
);
await executeEffects(effects, runtime);
await saveSnapshot(nextSnapshot);The challenge begins once an event needs to be delivered directly to a child actor, for example, when a child has its own delayed transitions. SetupA child machine with a timeout, invoked by a parent: import { createMachine, transition } from 'xstate';
const childMachine = createMachine({
id: 'child',
initial: 'idle',
states: {
idle: {
after: {
1000: { target: 'timedOut' }
}
},
timedOut: {}
}
});
const parentMachine = createMachine({
id: 'parent',
invoke: {
id: 'child-invocation',
systemId: 'child',
src: childMachine
}
});To handle timers durably, I've configured When a timeout fires, the server wakes up and needs to deliver Problem 1: Locating the child snapshot within the persisted rootWhen the timer fires, I need to find the child actor's snapshot inside the persisted root snapshot and transition it: async function onTimeout(actorId: string, timerId: string) {
const persistedSnapshot = await loadSnapshot();
const restoredRootSnapshot = parentMachine.restoreSnapshot(persistedSnapshot);
// How do I locate the actor identified by actorId?
}I can recursively walk Using the const persistedSnapshot = await loadSnapshot();
// Create an actor only to restore the actor hierarchy and gain access to
// its system.
const rootActor = createActor(parentMachine, {
snapshot: persistedSnapshot
});
const childRef = rootActor.system.get(registryKey)!;
const childSnapshot = childRef.getSnapshot();
// Transition using the pure transition function.
const [nextChildSnapshot, effects] = transition(
childMachine,
childSnapshot,
{ type: 'xstate.timer', id: timerId }
);Is this the right way to do it? Problem 2: Patching the child snapshot back into the rootAfter transitioning the child, I need to put the updated snapshot back into the root and persist the whole tree: const [nextChildSnapshot, effects] = transition(
childMachine,
childSnapshot,
{ type: `xstate.after.${timerId}` }
);
// How do I produce the next root snapshot?
const nextRootSnapshot = ???;
await executeEffects(effects, runtime);
await saveSnapshot(nextRootSnapshot);I could recursively find the child ref and replace its snapshot in userland, then persist the root again. But manually mutating the actor tree feels wrong. What is the correct way to merge a nested actor snapshot back into its root snapshot before persisting? |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
XState
6.0.0-alpha.21introduced a wonderful API that makes integrating XState into custom runtimes much nicer:The host owns the runtime by implementing
ActorSystemRuntimeinterface:This works beautifully for spawning actors, timers, and sending events from parent to child. Every lifecycle operation in the downward direction surfaces as an effect.
For example, when a parent stops, it emits
@xstate.stopfor each of its children:The gap
The upward direction is missing: when a child completes (reaches a final state) or errors, no effect is produced so with pure transitions the parent never finds out, and
onDone/onErrornever fire.Why
The done/error notification never goes through the effects system. It lives inside the live interpreter: when a child's snapshot becomes terminal,
Actor.update(increateActor.ts) calls the system relay directly:With pure transitions there is no
Actorinstance, so that code never runs - and nothing equivalent appears in the returned effects.What hosts have to do today
Detect the terminal status after transitioning a child and hand-roll the event delivery to the parent:
This is fragile: the event shape and type strings are internal conventions, and every custom runtime re-implements them by hand.
Here's a revised version:
Proposed solution
What if child-actor termination were represented as an effect instead?
The runtime would receive the completion or error event through the same
sendEventcallback it already implements:Now, I'm not sure whether
sendEventis the right place for this or whether a dedicated method would be a better fit.Either way, I think this aligns with the data-first direction effects are already heading, and child termination is just another piece of data that chould flow through the runtime contract rather than being baked into imperative interpreter code.
All reactions