Skip to content

Job Queue

A simulated job queue where the jobs share one BehavioralFsm definition. The app persists each job’s snapshot (state plus any pending deferred input) to localStorage on each event that mutates the serialized data: transitioned, deferred (a queued pause does not transition), and handled tick inputs (progress changes inside processing). A page refresh restores the jobs via rehydrate(). The restore is silent: _onEnter doesn’t fire, and the app re-establishes timers for in-flight jobs itself.

  • dehydrate()/rehydrate(snapshot) for the full persist/restore cycle: snapshot everything machina tracks for a job (state plus any pending deferred input) and restore it later without firing _onEnter, _onExit, or events. The WeakMap entry is written as if the client had always been there.
  • Deferred inputs survive the round trip: click Pause on start on a still-queued job to defer a pre-emptive pause until it enters processing, then refresh the page and start the job. It still pauses, because the snapshot form preserves the deferral. See Persisting clients for the general pattern.
  • Two-step restore, rehydrate then resume: rehydrate() places a job in processing, and the app dispatches resume to restart the tick timer. Side-effect recovery after a cold restore follows this two-step pattern.
  • createBehavioralFsm with per-client state: one FSM definition serves all jobs. Each job is a plain object, and state resides in the FSM’s internal WeakMap rather than on the client.
  • localStorage persistence on each data-mutating event: subscribers to transitioned, deferred, and handled tick inputs serialize each job’s snapshot and store it beside the client object, which matches the rehydrate() API design.
                start                          tick (all steps done)
  queued ──────────────► processing ──────────────────────────► completed
                           │    ▲
                     pause │    │ resume
                           ▼    │
                          paused
                           │
                     tick (random failure)
                           ▼
                          failed
                           │
                     retry │ (resets currentStep)
                           ▼
                        processing
State What happens
queued Registered but not running. start transitions to processing. pause (the Pause on start button) defers itself until processing is reached, a pre-emptive pause and the deferred input that demonstrates the snapshot round trip.
processing Tick timer advances currentStep. Random failure chance on each tick. pause stops the timer. resume restarts it silently.
paused Timer stopped. resume transitions back to processing, firing _onEnter to restart the timer.
failed Something went wrong during a tick. retry resets currentStep to 0 and transitions to processing for a fresh run.
completed Terminal. Job reached totalSteps. No inputs handled.

On page load, main.ts reads localStorage and restores each job in two steps:

// STEP 1: Silent placement — no _onEnter, no events, no timer.
// Requeues any pending deferred input from the snapshot too.
fsm.rehydrate(job, snapshot);

// STEP 2: Re-establish side effects for in-flight jobs
if (snapshot.state === "processing") {
    fsm.handle(job, "resume");
}

The resume handler on processing restarts the tick timer without transitioning. The job stays in processing and continues from its current step. The dual meaning of resume is intentional:

  • From paused: resume transitions to processing, which fires _onEnter and starts the timer normally.
  • While in processing: resume restarts the timer in place without a transition, and the post-rehydrate restore takes this path.

The app persists the job’s dehydrate() snapshot beside the client fields, as a sibling in the serialized shape:

interface PersistedJob {
    snapshot: ClientSnapshot; // from fsm.dehydrate(job)
    id: number;
    name: string;
    currentStep: number;
    totalSteps: number;
    createdAt: string;
    // timer is excluded — setTimeout handles are not serializable
}

This matches the rehydrate() API: fsm.rehydrate(client, snapshot) takes the snapshot as a separate argument because BehavioralFsm stores state and deferred inputs in a WeakMap rather than on the client object. The snapshot form, in place of a bare state string, lets a queued job’s pre-emptive pause (deferred until processing, see fsm.ts) survive the round trip. A bare state string restores the state path and drops the deferral.

On deserialization, timer is set to null. The resume input re-establishes it for processing jobs.

rehydrate() throws synchronously for unknown state names, including ones referenced inside a corrupted snapshot. main.ts wraps the restore loop in try/catch: when a schema change makes old data incompatible, the app clears localStorage and starts fresh:

try {
    for (const persisted of shape.jobs) {
        const job = reconstructClient(persisted);
        fsm.rehydrate(job, persisted.snapshot);
        // ...
    }
} catch {
    // rehydrate() threw — state names changed since last save
    localStorage.removeItem(STORAGE_KEY);
}

examples/job-queue/