Skip to content

About

Schema-first state machines for Effect. Define once, derive everywhere, break nothing.

Resources

Stars

86 stars

Watchers

1 watching

Forks

Repository files navigation

effect-machine

Type-safe state machines for Effect.

Effect Machine gives one actor a schema-first state model, a typed event mailbox, scoped Effect work, typed input and output, supervision, persistence hooks, inspection, and framework-neutral Atom integration.

Use it when a feature has several valid states, invalid transitions, state-owned async work, timeouts, cancellation, actor coordination, or UI views that need precise subscriptions.

Install

bun add effect-machine effect

effect is a required peer dependency.

Imports

import { Event, Machine, State } from "effect-machine";
import * as ActorAtom from "effect-machine/atom";
import { EntityMachine, toEntity } from "effect-machine/cluster";

Use effect-machine for local machines and actors. Use effect-machine/atom for React, Solid, or another Effect Atom binding. Use effect-machine/cluster for distributed entity machines.

First machine

States and events are Effect schemas.

import { Effect, Schema } from "effect";
import { Event, Machine, State } from "effect-machine";

const DownloadState = State({
  Idle: {},
  Downloading: { url: Schema.String },
  Done: { url: Schema.String, bytes: Schema.Finite },
  Failed: { url: Schema.String, message: Schema.String },
});

const DownloadEvent = Event({
  Start: { url: Schema.String },
  Completed: { bytes: Schema.Finite },
  Failed: { message: Schema.String },
});

const downloadMachine = Machine.make({
  state: DownloadState,
  event: DownloadEvent,
  initial: DownloadState.Idle,
})
  .on(DownloadState.Idle, DownloadEvent.Start, ({ event }) =>
    DownloadState.Downloading({ url: event.url }),
  )
  .on(DownloadState.Downloading, DownloadEvent.Completed, ({ state, event }) =>
    DownloadState.Done.with(state, { bytes: event.bytes }),
  )
  .on(DownloadState.Downloading, DownloadEvent.Failed, ({ state, event }) =>
    DownloadState.Failed.with(state, { message: event.message }),
  )
  .final(DownloadState.Done, ({ state }) => state.bytes)
  .final(DownloadState.Failed, () => 0);

const program = Effect.scoped(
  Machine.scoped(
    Effect.gen(function* () {
      const actor = yield* Machine.spawn(downloadMachine);
      yield* actor.start;
      yield* actor.send(DownloadEvent.Start({ url: "/report.pdf" }));
      yield* actor.send(DownloadEvent.Completed({ bytes: 1024 }));
      return yield* actor.awaitOutput;
    }),
  ),
);

An empty variant is a value such as DownloadState.Idle. A non-empty variant is a constructor such as DownloadState.Downloading({ url }).

State.with(source, fields) copies matching fields into the target variant. It prevents manual context spreading across different states.

Effect is the composition layer

Effect Machine does not add an action queue or a second context system.

Work API
Unconditional state change .on, .reenter, or .immediate
Conditional state change .when, .reenterWhen, or .immediateWhen
Work that produces a completion event .task
State-owned stream or resource .spawn
Actor-owned stream or resource .background
Autonomous machine sequence Machine.run with Effect.flatMap
Interactive multi-phase flow Parent machine with child actors
Lazy child requested by consumers ActorHost in a parent state scope

Effect requirements remain in R. A machine cannot start until the application provides every required service. Effectful transition handlers must have never in their error channel. Convert expected failures to states or events.

Machine-lifetime backgrounds can read self.state and self.latestTransition. These are the actor-owned subscription refs. They stay stable across supervision generations. Use SubscriptionRef.get or SubscriptionRef.changes for Effect workflows. Use self.client for synchronous host callbacks that need send, getSnapshot, or subscribe.

Read the Effect model and async work ownership.

Guards and stable state

Register ordered candidates for one state and event. The first passing guard wins. An unguarded candidate is the fallback.

machine
  .when(
    State.Checking,
    Event.Continue,
    function hasStock({ state }) {
      return state.stock > 0;
    },
    () => State.Accepted,
  )
  .on(State.Checking, Event.Continue, () => State.Rejected)
  .immediate(State.Accepted, ({ state }) => State.Ready.with(state));

The predicate can return a Boolean or Effect<boolean, never, R>. Its requirements flow into the machine type. actor.can(event) evaluates the same predicate with the actor's captured context. ActorAtom.can(actor, event) exposes the result to React and Solid. After the actor is final, stopped or defected, every can form answers false and runs no predicate. The inspector uses the predicate function name.

Immediate transitions run until the state is stable. Subscribers see only the stable state. The runtime stops an accidental eventless loop after 100 edges.

Effect services and tasks

class Api extends Context.Service<
  Api,
  { readonly load: (id: string) => Effect.Effect<Data, ApiError> }
>()("app/Api") {}

machine.task(State.Loading