# Run many machines under one parent

tea runs one machine per `run`. It has no supervisor and no registry of runs,
and Elm has none either. A tree of machines is built from Effect scopes, `run`
from `@demlik/tea/effect`, and three helpers from the same entry:
[`spawn`](../reference/effect.md#spawn) starts a child in a scope of its own,
[`stop`](../reference/effect.md#stop) stops one child, and
[`tell`](../reference/effect.md#tell) puts a notice on the parent's line
without waiting for it.

This page starts workers under a parent. Each worker runs in a child scope of
the parent's scope, the host keeps a table of live workers by id, and the
parent gets a `child_stopped` Msg when a worker stops. The table, the ids and
the Msg names are yours. The helpers run the steps that race.

It needs the Effect engine: see
[Run a machine on the Effect engine](./run-on-the-effect-engine.md).

## 1. Write the machines

Both machines are plain tea and import nothing from Effect. The parent uses
the transitions form, so a `closed` parent has no cell for `child_stopped`.
Save them as `parent-and-workers.ts`.

```ts
import { defineMachine } from "@demlik/tea";

/** A child: counts the jobs it has done. */
export interface WorkerState {
  readonly done: number;
}

export type WorkerMsg = { readonly _tag: "job" };

export const worker = defineMachine({
  types: { model: {} as WorkerState, msg: {} as WorkerMsg },
  init: (loaded) => [loaded ?? { done: 0 }, []],
  update: {
    job: (s) => [{ done: s.done + 1 }, []],
  },
});

/** The parent: lists the children that stopped, until it closes. */
export type ParentState =
  | { readonly _tag: "open"; readonly stopped: readonly string[] }
  | { readonly _tag: "closed"; readonly stopped: readonly string[] };

export type ParentMsg =
  | { readonly _tag: "child_stopped"; readonly id: string }
  | { readonly _tag: "close" };

export const parent = defineMachine({
  types: { model: {} as ParentState, msg: {} as ParentMsg },
  init: (loaded) => [loaded ?? { _tag: "open", stopped: [] }, []],
  update: {
    open: {
      child_stopped: (s, m) => [{ ...s, stopped: [...s.stopped, m.id] }, []],
      close: (s) => [{ _tag: "closed", stopped: s.stopped }, []],
    },
    // A closed parent takes no Msg, so it has no cell for `child_stopped`.
    closed: {},
  },
});
```

## 2. Start each worker with `spawn`, and stop it with `stop`

This is host code, and it is yours to change. Save it beside the machines as
`parent-and-workers-effect.ts`.

```ts
import {
  type EffectBootingRuntime,
  type EffectRun,
  run,
  spawn,
  stop,
  tell,
} from "@demlik/tea/effect";
import { Effect, type Scope } from "effect";
import {
  type ParentMsg,
  type ParentState,
  parent,
  type WorkerMsg,
  type WorkerState,
  worker,
} from "./parent-and-workers";

/** A running child: its handle, and the scope that stops it. */
export interface Child {
  readonly run: EffectBootingRuntime<WorkerState, WorkerMsg>;
  readonly scope: Scope.Closeable;
}

/** The host's own table of live children, by id. tea keeps none. */
export type Children = Map<string, Child>;

/**
 * Start a worker in a child scope of `parentScope` and enrol it in
 * `children`. `stopWorker` stops that worker. Closing the parent's scope
 * stops every worker spawned under it.
 */
export const spawnWorker = (
  parentScope: Scope.Scope,
  parentRun: EffectRun<ParentState, ParentMsg>,
  children: Children,
  id: string,
): Effect.Effect<Child> =>
  spawn(parentScope, {
    start: (scope) =>
      Effect.map(run(worker, {}), (run): Child => ({ run, scope })),
    enrol: (child) => Effect.sync(() => children.set(id, child)),
    remove: Effect.sync(() => children.delete(id)),
    notify: tell(parent, parentRun, { _tag: "child_stopped", id }),
  });

/** Stop one worker. An id not in the table is a no-op. */
export const stopWorker = (
  children: Children,
  id: string,
): Effect.Effect<void> =>
  Effect.suspend(() => {
    const child = children.get(id);
    return child === undefined ? Effect.void : stop(child.scope);
  });
```

`spawn` forks a scope from `parentScope` and takes the host's four steps:

- **`start`** starts the child and returns what you keep for it. It runs with
  the child's scope provided, so `run(worker, {})` belongs to that scope and
  stops when it closes. `start` is also handed the scope. Keep it: it is what
  you hand to `stop`.
- **`enrol`** writes the child to your table.
- **`remove`** takes it out again. It runs when the child's scope closes,
  after the worker has stopped.
- **`notify`** runs after `remove`. Here it is `tell(parent, parentRun, msg)`,
  which puts `msg` on the parent's line when the parent's State has a cell for
  it, and returns at once. `spawn` runs `notify` on a fiber nothing reads, so
  `notify` is typed to never fail. `tell` carries no failure in its type, so it
  goes in bare. `parentRun` is an `EffectRun`, the handle `ready` gives you. The
  plain `EffectRuntime` does not compile here, for the reason in
  [What the helpers guarantee](#what-the-helpers-guarantee).

`stop(child.scope)` stops that one worker: its run stops, `remove` takes its
entry out and `notify` tells the parent. The table lookup is yours, so
`stopWorker` does it and then calls `stop`. Closing the parent's scope closes
every child forked from it, so the whole tree stops with it.

A worker whose Sub fails with an error it did not map to a Msg closes its own
child scope the same way, so `remove` and `notify` run. So does a worker whose
reducer throws under the default `stop` strategy: its Subs close, its final
save runs, and the parent hears `child_stopped`, with no call from you. The
parent's scope and the other workers stay up. That takes an `onError` on the
worker's `run`: with none, the default sink rethrows the failure and ends the
process, along with every run in it. The same goes for the parent.

## 3. Use it

This goes in a third file beside the other two. It imports `Scope` as a value
and `Exit` with it, because it opens the parent's scope and closes it.

```ts
import { run } from "@demlik/tea/effect";
import { Effect, Exit, Scope } from "effect";
import { parent } from "./parent-and-workers";
import {
  type Children,
  spawnWorker,
  stopWorker,
} from "./parent-and-workers-effect";

const program = Effect.gen(function* () {
  const parentScope = yield* Scope.make();
  const parentRun = yield* (yield* run(parent, {}).pipe(
    Scope.provide(parentScope),
  )).ready;
  const children: Children = new Map();

  const a = yield* spawnWorker(parentScope, parentRun, children, "a");
  yield* spawnWorker(parentScope, parentRun, children, "b");
  yield* (yield* a.run.ready).dispatch({ _tag: "job" });

  // Stops worker "a". The parent soon reads { _tag: "open", stopped: ["a"] }.
  yield* stopWorker(children, "a");

  // Stops worker "b", then the parent.
  yield* Scope.close(parentScope, Exit.void);
});
```

The parent is not a worker. If the parent's own Sub fails, or its reducer
throws, only the parent's run stops. `parentScope` stays open, because you opened it, so the workers keep
running and `remove` and `notify` do not run. To stop the whole tree with the
parent, wait on `parentRun.done()` on a fiber of its own, and close `parentScope`
when it ends. Fork this right after the workers start:
`Effect.forkDetach(Effect.ensuring(Effect.ignore(parentRun.done()), Scope.close(parentScope, Exit.void)))`.

## 4. Do your own work between the fork and the run

A host often does more than start a run. This one gives every process its own
`Terminal` service, and its table says whether a process is `starting` or
`running`. That work goes in `start`, ahead of the run. It is a file of its
own beside `parent-and-workers.ts`.

```ts
import { Cmd, defineMachine } from "@demlik/tea";
import { type EffectRun, run, spawn, stop, tell } from "@demlik/tea/effect";
import { Context, Effect, Layer, type Scope } from "effect";
import { z } from "zod";
import { type ParentMsg, type ParentState, parent } from "./parent-and-workers";

/** Write one line to the process's terminal. */
export const writeLine = Cmd.define("write_line", {
  input: z.object({ text: z.string() }),
  ok: z.object({}),
  err: ["closed"],
});

/** A child: counts the lines it wrote. */
export interface ProcessState {
  readonly written: number;
}

export type ProcessMsg = { readonly _tag: "input"; readonly text: string };

export const proc = defineMachine({
  types: { model: {} as ProcessState, msg: {} as ProcessMsg },
  cmds: [writeLine],
  init: (loaded) => [loaded ?? { written: 0 }, []],
  update: {
    input: (s, m) => [s, [writeLine({ text: m.text })]],
    write_line_ok: (s) => [{ written: s.written + 1 }, []],
    write_line_err: (s) => [s, []],
  },
});

/** One process's terminal. Every process gets its own. */
export class Terminal extends Context.Service<
  Terminal,
  {
    readonly write: (text: string) => Effect.Effect<void, { _tag: "closed" }>;
  }
>()("Terminal") {}

/** Boot one process. Needs a Scope and that process's Terminal. */
export const runProcess = run(proc, {
  interpret: {
    write_line: (cmd) =>
      Effect.gen(function* () {
        const terminal = yield* Terminal;
        yield* terminal.write(cmd.text);
        return {};
      }),
  },
});

/**
 * A child in the host's table. It is `starting` from the moment its scope is
 * forked until its run is up, so a lookup can tell the two apart.
 */
export type Process =
  | { readonly lifecycle: "starting" }
  | {
      readonly lifecycle: "running";
      readonly run: Effect.Success<typeof runProcess>;
      readonly scope: Scope.Closeable;
    };

/** The host's own table of processes, by id. tea keeps none. */
export type Processes = Map<string, Process>;

/**
 * Start a process under the parent with its own `terminal`. The host's work
 * between the fork and the run is in `start`: it marks the process
 * `starting`, then builds the process's services in the child's scope. A
 * build that fails or is interrupted closes that scope, which removes the
 * entry and tells the parent.
 */
export const spawnProcess = <E>(
  parentScope: Scope.Scope,
  parentRun: EffectRun<ParentState, ParentMsg>,
  processes: Processes,
  id: string,
  terminal: Layer.Layer<Terminal, E>,
): Effect.Effect<Process, E> =>
  spawn(parentScope, {
    start: (scope) =>
      Effect.gen(function* () {
        processes.set(id, { lifecycle: "starting" });
        const services = yield* Layer.build(terminal);
        const run = yield* Effect.provide(runProcess, services);
        return { lifecycle: "running", run, scope } satisfies Process;
      }),
    enrol: (process) => Effect.sync(() => processes.set(id, process)),
    remove: Effect.sync(() => processes.delete(id)),
    notify: tell(parent, parentRun, { _tag: "child_stopped", id }),
  });

/** Stop one running process. Any other id is a no-op. */
export const stopProcess = (
  processes: Processes,
  id: string,
): Effect.Effect<void> =>
  Effect.suspend(() => {
    const process = processes.get(id);
    return process?.lifecycle === "running" ? stop(process.scope) : Effect.void;
  });
```

`Layer.build(terminal)` builds the process's services in the child's scope, so
they are released when the process stops. If the build fails, `spawnProcess`
fails with the same error. If it is interrupted, the spawn ends there. Either
way `spawn` closes the child's scope, so `remove` deletes the `starting` entry
and `notify` tells the parent.

## What the helpers guarantee

You do not guard any of these in host code.

- **The table never holds a child whose scope has closed.** `spawn` runs the
  fork, the removal finalizer, `start` and `enrol` as one uninterruptible
  step. An interrupt waits for the step to finish, unless your own `start`
  marks a part of itself interruptible. A child whose scope closed before
  `enrol` is removed again. Tuval wrote these as separate steps and looked up
  dead children
  ([phoenix #7898](https://github.com/kamp-us/phoenix/issues/7898)).
- **Stopping a child never waits for the parent.** `notify` runs on a fiber of
  its own that the closing scope does not wait for. So a parent's Cmd handler
  can call `stop`, even though the parent's `dispatch` waits for that handler.
- **Stopping a child twice is safe.** The second `stop` succeeds and sends no
  second notice.
- **`tell` promises queued, not handled.** It puts the Msg on the receiver's
  line and answers at once, before the receiver's step has run. A result comes
  back later as its own Msg. So a child can tell its parent from a Cmd handler,
  the parent can answer from its own, and neither stops. The Promise engine has
  the same `tell`, in `@demlik/tea/promise`.
- **`tell` says where the Msg stands, in three words.** `"queued"` means it is
  on the line. `"stopped"` means the receiver is stopping or has stopped, so it
  is not. `"no_cell"` means the receiver's current State has no cell for it, so
  it is not. Tuval sent a notice the parent no longer took and logged an error
  per spawn ([phoenix #8927](https://github.com/kamp-us/phoenix/issues/8927)).
- **`tell` takes only the handle `ready` gives.** That is an `EffectRun`, or a
  spread of one (`Run` on the Promise engine). It carries the run's line, and the
  type asks for it. An `EffectRuntime` built by hand does not compile as `tell`'s
  argument, so a `notify` cannot lose its notice to one. The handle straight from
  `run` does not compile either, with a store or without one. Wait for `ready`.
- **Two `tell`s from one sender fold in the order they were sent.**
- **A Msg whose cell is gone by its turn is dropped without a word.** It does
  not end the process, with or without an `onError`.
- **A failed save of the receiver reaches the receiver's `onError`.** It does
  not come back to the sender, and `spawn` does not report it.

Four things stay yours:

- **A cast past `tell`'s type can lose the notice.** A hand-built object cast
  past it has no line. On it, `tell` throws on the Promise engine and dies with a
  defect on the Effect engine. This is the one way `tell` fails. In `notify`, that
  defect ends the fiber unseen, so the parent is never told.
- **`"no_cell"` reads the State as it is now.** Msgs already on the line have
  not folded yet. A Msg that only a queued one makes acceptable answers
  `"no_cell"`, so wait for the first one's result before sending the second.
- **`idle()` and `dispatch` speak for one run.** A machine waiting on a `tell`
  from another run looks quiet to its own `idle()`. Wait for its State, or use
  `done()` with a `terminal`.
- **Two hand-written waiting `dispatch` calls into each other can still stop
  both machines.** A step ends only when its Cmd handlers return, and `dispatch`
  waits for the receiver's step. A handler in each machine waiting on the other
  is a ring, and tea has no lock-up detector. Use `tell` there.

Stop a child with `stop`, or by closing its scope. `child.run.stop()` is not
one of them: it stops the run and leaves the scope open, so the entry stays in
your table and the parent is not told.

`remove` also runs for a child that never reached `enrol`, so write it to be
safe on an id the table does not hold. `Map.delete` is.

The page's examples are `examples/parent-and-workers.ts`,
`examples/parent-and-workers-effect.ts` and `examples/process-tree-effect.ts`.
