# Run a machine on the Effect engine

To run a `@demlik/tea` machine with Effect handlers, Layers and interruption,
import `run` from `@demlik/tea/effect`. The machine file is the one the Promise
engine runs, unchanged: see
[Run a machine on the Promise engine](./run-on-the-promise-engine.md).

This page runs one machine. To run several under a parent, use `spawn`, `tell`
and `stop` from the same entry: see
[Run many machines under one parent](./run-many-machines.md).

The agent layer runs on the Promise engine, not this one. `defineAgent` from
`@demlik/tea/agent` drives its machine with the Promise engine's `run`, so
`agent.run` returns a Promise and a `tool()` handler is an `async` function, not
an `Effect`. Whether the agent layer gets an Effect form is an open question,
tracked in
[kamp-us/demlik#322](https://github.com/kamp-us/demlik/issues/322).

`@demlik/tea/effect` is `stable` and targets Effect v4 (still a release
candidate). `effect` is an optional peer dependency, so install it yourself:

```sh
pnpm add effect
```

## 1. Write the machine once

This is the same file the Promise how-to uses. It imports only `@demlik/tea`.

```ts
import { Cmd, defineMachine } from "@demlik/tea";
import { z } from "zod";

/** Look a user up by id. The handler returns an outcome; the engine mints the Msg. */
export const fetchUser = Cmd.define("fetch_user", {
  input: z.object({ id: z.string() }),
  ok: z.object({ name: z.string() }),
  err: ["not_found"],
});

export interface ProfileState {
  readonly status: "idle" | "loading" | "loaded" | "missing";
  readonly name: string | null;
}

export type ProfileMsg =
  | { readonly _tag: "look_up"; readonly id: string }
  | { readonly _tag: "clear" };

export const profile = defineMachine({
  types: { model: {} as ProfileState, msg: {} as ProfileMsg },
  cmds: [fetchUser],
  init: (loaded) => [loaded ?? { status: "idle", name: null }, []],
  update: {
    look_up: (s, m) => [
      { ...s, status: "loading", name: null },
      [fetchUser({ id: m.id })],
    ],
    fetch_user_ok: (s, m) => [
      { ...s, status: "loaded", name: m.value.name },
      [],
    ],
    fetch_user_err: (s) => [{ ...s, status: "missing", name: null }, []],
    clear: (s) => [{ ...s, status: "idle", name: null }, []],
  },
  // A miss clears itself after two seconds. Both engines ship `timer`.
  subs: [
    {
      _tag: "timer",
      deps: (s) =>
        s.status === "missing" ? { ms: 2_000, msg: { _tag: "clear" } } : null,
    },
  ],
});
```

To write the schemas in Effect Schema instead of zod, import `Cmd` from
`@demlik/tea/effect`. Its `Cmd.make` takes plain Effect schemas:

```ts
import { Cmd } from "@demlik/tea/effect";
import { Schema } from "effect";

/** `fetchUser` again, with its schemas written in Effect Schema. */
export const fetchUser = Cmd.make("fetch_user", {
  input: Schema.Struct({ id: Schema.String }),
  ok: Schema.Struct({ name: Schema.String }),
  err: ["not_found"],
});
```

It returns a Cmd like the zod one, so the rest of the machine file stays as it
is and still runs on both engines. The file now imports `effect`.

A schema here checks a value and never translates it. One that changes a
value's type, such as `Schema.FiniteFromString` or a brand, is a compile error.
To keep its checks, pass `Schema.toType(schema)`.

## 2. Hand `run` Effect handlers

```ts
import { run } from "@demlik/tea/effect";
import { Context, Effect } from "effect";
import { profile } from "./profile-lookup";

/** Where names come from, as an Effect service. Provide it with a Layer. */
export class Directory extends Context.Service<
  Directory,
  { readonly nameOf: (id: string) => Effect.Effect<string | undefined> }
>()("Directory") {}

/** Boot the profile machine on the Effect engine. Needs a Scope and a Directory. */
export const runProfile = run(profile, {
  interpret: {
    fetch_user: (cmd) =>
      Effect.gen(function* () {
        const directory = yield* Directory;
        const name = yield* directory.nameOf(cmd.id);
        if (name === undefined) {
          return yield* Effect.fail({ _tag: "not_found" as const });
        }
        return { name };
      }),
  },
});

/** Look one user up and read the state it settles in. Closing the scope stops the run. */
export const lookUp = (id: string) =>
  Effect.gen(function* () {
    const handle = yield* runProfile;
    const runtime = yield* handle.ready;
    yield* runtime.dispatch({ _tag: "look_up", id });
    return runtime.getState();
  }).pipe(Effect.scoped);
```

Then provide the service and run it:

```ts
import { Effect, Layer } from "effect";
import { Directory, lookUp } from "./profile-lookup-effect";

export const DirectoryLive = Layer.succeed(Directory, {
  nameOf: (id) => Effect.succeed(id === "u1" ? "Ada" : undefined),
});

export const state = await Effect.runPromise(
  lookUp("u1").pipe(Effect.provide(DirectoryLive)),
);
// { status: "loaded", name: "Ada" }
```

What changes from the Promise engine:

- **A handler returns an `Effect`.** Its success becomes `fetch_user_ok` and a
  failure with a declared tag becomes `fetch_user_err`. A defect, or a failure
  with a tag the Cmd does not declare, goes to `onError` and dispatches no Msg.
  A hand-written Cmd's handler succeeds with one Msg, a list of Msgs, or
  nothing, as on the Promise engine; a list is dispatched in order.
- **Services come from your Layers.** `runProfile` needs `Directory` because
  its handler reads it, and the type says so. It does not compile as runnable
  until you provide it.
- **`run` needs a `Scope`.** Closing the scope stops the run and its Subs.
  Every handler still in flight is interrupted, its finalizers run, and no Msg
  is dispatched after stop. Calling `stop()` on the handle does the same.
- **The handle's verbs are Effects.** The members have the Promise engine's
  names. Where the Promise engine returns a Promise (`ready`, `dispatch`,
  `dispatchOnce`, `idle`, `done`, `stop`), this one returns an Effect, so you
  `yield*` it. `getState`, `result` and the listeners (`subscribe`, `observe`,
  `onBoot`, `on`) are the same functions on both engines. `useRuntime` from
  `@demlik/tea/react` accepts the booted run from either engine and returns
  `[state, send]`; `send(msg)` returns `undefined` and runs no Effect in the
  component. The run's sink hears step failures; pass `{ onError }` to the hook
  for sends to a stopped run.

The other options (`store`, `onError`, `clock`, `events`, `supervision`,
`terminal`, `telemetry`, `disposeTimeoutMs`) mean what they mean on the Promise
engine. A fenced store stays fenced, and must be given an `onError`:
[step 4 of the durability how-to](./make-durable.md#4-refuse-a-second-writer-if-two-processes-can-reach-the-storage)
says why.

## 3. Swap a runner in a test

A Sub runner returns a `Stream` of Msgs. A `subscribe` entry with a built-in's
name replaces it, so a test can fire the `timer` Msg at once:

```ts
import { run } from "@demlik/tea/effect";
import { Effect, Stream } from "effect";
import { profile } from "./profile-lookup";

/** The profile machine with every lookup a miss, and a `timer` that fires at once. */
export const runProfileInTest = run(profile, {
  interpret: {
    fetch_user: () => Effect.fail({ _tag: "not_found" as const }),
  },
  subscribe: { timer: (sub) => Stream.make(sub.deps.msg) },
});
```

The built-in `timer` is `Effect.sleep` for `deps.ms`, then `deps.msg`.

## 4. Turn a Sub's errors into Msgs

An Elm `Sub msg` has no error type, and neither does a tea Sub. A runner maps
the errors it expects into Msgs itself, and the machine decides what they mean:

```ts
import { Data, Stream } from "effect";

class SocketClosed extends Data.TaggedError("SocketClosed")<{
  readonly code: number;
}> {}

run(chat, {
  subscribe: {
    // `roomFeed` is a Stream<ChatMsg, SocketClosed>.
    room: (sub) =>
      roomFeed(sub.deps.roomId).pipe(
        Stream.catchTag("SocketClosed", (e) =>
          Stream.make({ _tag: "disconnected", code: e.code } as const),
        ),
      ),
  },
});
```

The machine handles `disconnected` like any other Msg. To reconnect, its
`update` changes the State so the Sub's `deps` change, and the engine starts
the Sub again.

A failure the Sub does not catch stops that run. `onError` sees it under
`phase: "sub"`, and `done()` fails with `SubFailed`, whose `cause` is what the
Sub failed with. `result()` stays `undefined`. The Scope you ran it in stays
open, so whatever else lives there keeps going, and your program does not end by
itself. To end it, wait on `done()`. What the run's handlers and runners acquired
through `Scope.Scope` is released with the run, because that service is the run's
own child Scope there. The Msgs the Sub sent before it failed fold first, so if
one of them reaches a terminal State, `done()` and `result()` both answer with
that State. There is no hook on the machine or on `run` for it: a failure you
expect belongs in the Sub.

With no `onError`, the default sink rethrows the failure and ends the process,
along with every other run in it, whatever the Scope does. A host running several
machines in one process passes a sink.

The Promise engine follows the same rule. Its runner dispatches the Msgs for
the errors it expects (the `onError` option of `fromWebSocket` does this), and a
runner that throws while it starts stops the run, reaches `onError` under
`"sub"` and rejects `done()` with `SubFailedError`.

## 5. Catch a run's failures by tag

A dispatch fails with one of three typed errors, and `Effect.catchTags` sorts
them:

- **`Stopped`**: the run is stopping or has stopped, so the Msg was never
  folded. `when` says which.
- **`StoreFailed`**: the store failed. `operation` is `"save"` when a
  transition's save threw (a fenced store's conflict included), and `"load"`
  when `ready` could not restore the saved state. `cause` is the underlying
  error.
- **A hand-written cell's own failure**: the error type of the `interpret`
  cell of a Cmd that is not `Cmd.define`d. A `Cmd.define`d Cmd's failure
  becomes its `_err` Msg instead.

```ts
const sent = runtime.dispatch({ _tag: "look_up", id }).pipe(
  Effect.as("sent"),
  Effect.catchTags({
    Stopped: () => Effect.succeed("stopped"),
    StoreFailed: (e) => Effect.succeed(`store ${e.operation} failed`),
  }),
);
```

Anything else is a bug in the program, like a reducer that throws or a Msg
with no cell. It ends the Effect as a defect.

`done()` follows the same split. A failed terminal save fails it with
`StoreFailed`, and a Sub failure fails it with `SubFailed`. A reducer throw under
the default `stop` strategy refuses every later Msg, and `done()` ends as a defect
holding what was thrown, for waiting and later callers. `Effect.catchTags` does not
see a defect, so read it with `Effect.catchDefect` or from the fiber's `Exit`. The
Promise engine's `done()` rejects with what was thrown.

A reducer throw under `stop` also stops the run by itself, the same way a Sub
failure does. Once the Msgs already in line have folded, the Subs close, the final
save runs, and the run's own Scope closes. The Scope you ran it in stays open. You
do not need to call `stop()` after a failed `done()`, and calling it, or closing
your Scope, does nothing more.

## 6. Drive it from a React component

`useMachine` from `@demlik/tea/react` runs this engine too. Hand it
`runIn(runtime)` from `@demlik/tea/effect`, with your `ManagedRuntime`, as its `run`,
and the `interpret` cells above go beside it unchanged. See
[step 8 of Drive a machine from React](./drive-from-react.md#8-run-the-hook-on-the-effect-engine).
