# Programs

> Read when an app is written as Effect programs. Run an effect per change, stream changes, hold a value observed for a scope, feed a value from a stream, run a feed while its data is read, and hold a section's writes in a stage until it succeeds.

The Effect pages are for applications that already use Effect: see
[Schema-checked boxes](./boxes.md). The functions on this page are for apps
written as Effect programs, and `@frondruntime/pinna-effect` exports them next
to the rest. Models and components need none of them. `watchScoped` and
`observeScoped` end in `Scoped`, Effect's suffix for a call that lives for the
caller's scope, because the plain `watch` and `observe` keep their names and
return a stop function instead.

## Example

No program requires a service for the realm. `watchScoped` and `fromStream`
take it first, as `watch` does, and `changes`, `observeScoped`, and
`whileObserved` take it from the observable, so a program that refuses every
requirement but `Scope` runs each of them.

```ts
import { createRealm } from "@frondruntime/pinna-effect";

// Every program below takes the realm, or an observable that carries it,
// so none requires a service for it; a test makes a realm of its own.
const realm = createRealm();
```

`watchScoped` runs an effect for each change of what the select reads, in the
caller's scope. A new value interrupts the running effect: the latest value
wins. `search` stands for the application's own effect.

```ts
import { schemaBox, update, watchScoped } from "@frondruntime/pinna-effect";
import { Effect, Schema } from "effect";

const $query = schemaBox(realm, Schema.String, "");
const $results = schemaBox(realm, Schema.Array(Schema.String), []);

const searchAsTyped = watchScoped(
  realm,
  (read) => read($query),
  (query) =>
    Effect.gen(function* () {
      // A newer query interrupts this effect, here or in the search.
      yield* Effect.sleep("200 millis");
      const results = yield* search(query);
      update(realm, (_read, write) => write($results, results));
    }),
);
```

`changes` is a stream of the current value, then each change.

```ts
import { changes } from "@frondruntime/pinna-effect";
import { Effect, Stream } from "effect";

// The query now, then each change; a slow consumer skips to the newest.
const logQueries = changes($query).pipe(
  Stream.runForEach((query) => Effect.log(`query: ${query}`)),
);
```

`fromStream` is a read-only value fed by a stream. The stream runs only while
the value is observed. When the last observer leaves, the value resets to
`initial` synchronously. Each run starts from `initial` until its first
element arrives. `fetchRate` stands for the application's own effect.

```ts
import { computed, fromStream, schemaBox } from "@frondruntime/pinna-effect";
import { Effect, Schedule, Schema, Stream } from "effect";

const $price = schemaBox(realm, Schema.Number, 10);

const priceInEuros = Effect.gen(function* () {
  // No rate until the stream emits, then its latest rate. The poll runs
  // only while $rate is observed. Losing the last observer resets $rate
  // to undefined, so a stale rate never shows as current.
  const $rate = yield* fromStream<number | undefined>(
    realm,
    Stream.fromEffectSchedule(fetchRate, Schedule.spaced("1 minute")),
    undefined,
  );
  return computed(realm, (read) => {
    const rate = read($rate);
    return rate === undefined ? undefined : read($price) * rate;
  });
});
```

`whileObserved` runs a program while an observable is observed: from the
start when the first observer arrives, interrupted when the last one leaves.
It is how a feed writes the rows of a collection only while a list shows
them: a list reads `keys`, and a reader of one present row does not. `fromStream` is the same lifetime around a single value. A row checked
against a schema lands in a `schemaCollection`
([Collection fields](./collections.md)). `fetchTrades` and `tradeUpdates`
stand for the application's own snapshot and updates.

```ts
import { Schema } from "effect";

class Trade extends Schema.Class<Trade>("Trade")({
  id: Schema.String,
  notional: Schema.Number.check(Schema.isGreaterThan(0)),
}) {}
```

```ts
import { box, schemaCollection, update, whileObserved } from "@frondruntime/pinna-effect";
import { Effect, Stream } from "effect";

const $trades = schemaCollection(realm, Trade, { keyOf: (trade) => trade.id });
// Only the app knows when its snapshot is complete, so the flag is its own.
const $loaded = box(realm, false);

// A list observes the keys; a reader of one present row does not, so this
// feed runs while a list shows the trades.
const tradeFeed = whileObserved(
  $trades.keys,
  Effect.gen(function* () {
    const trades = yield* fetchTrades;
    update(realm, (_read, write) => {
      write.replaceAll($trades, trades);
      write($loaded, true);
    });
    // The run ends when the last reader leaves, so it must not end before:
    // it runs the updates for as long as it is observed.
    yield* tradeUpdates.pipe(
      Stream.runForEach((trade) =>
        Effect.sync(() => update(realm, (_read, write) => write.upsert($trades, trade))),
      ),
    );
  }).pipe(
    // Not loaded once nobody reads it: the next reader waits for a new snapshot.
    Effect.ensuring(Effect.sync(() => update(realm, (_read, write) => write($loaded, false)))),
  ),
);
```

`observeScoped` holds a value observed until the scope closes, so the stream behind
it keeps running with nothing rendered.

```ts
import { observeScoped } from "@frondruntime/pinna-effect";
import { Effect } from "effect";

const keepRateFresh = Effect.gen(function* () {
  const $euros = yield* priceInEuros;
  // Observed until the scope closes, rendered or not:
  // the poll keeps running, and $euros stays cached.
  yield* observeScoped($euros);
  return $euros;
});
```

Each of them stops when its scope closes.

```ts
import { Effect } from "effect";

const main = Effect.gen(function* () {
  yield* searchAsTyped;
  yield* Effect.forkScoped(logQueries);
  yield* keepRateFresh;
  yield* tradeFeed;
});

// Every watch, stream, and hold above stops when the scope
// closes: here, when the fiber is interrupted.
const start = () => Effect.runFork(main.pipe(Effect.andThen(Effect.never), Effect.scoped));
```

## Rules

- Pass the realm, as `watch` takes it. A test makes a realm of its own.
  `RealmService` is for a `SchemaModel` decoded inside an Effect program
  ([Classes](./classes.md)).
- A watch's effect has no error channel. A defect is a bug: it is logged at
  the error level, and the watch keeps running. A stream behind `fromStream`
  logs a defect too.
- While observed, a `fromStream` value is the last element of the current
  run, or `initial` before the first; while unobserved, it is `initial`. A
  stream that completes or dies leaves the value as it is until the last
  observer leaves. A failure the screen must show is an element the stream
  gives, such as a status beside the rate: see
  [Failures as values](#failures-as-values).
- A watch's select is tracked and must not write. Its effect writes through
  `update`.
- `watchScoped` runs for changes, not for the current value. `changes` starts with
  the current value.
- `changes`, `observeScoped`, and `whileObserved` take the realm from the
  observable. A host whose programs require nothing but `Scope` watches a
  box with `changes` while its work awaits.
- A `whileObserved` program runs in a scope of its own, closed when the run
  ends, so a fiber it forks into that scope stops with it. A program that
  returns ends its run while the value is still observed, and the next run
  starts only after the last observer leaves and another arrives: a feed
  ends on the stream it runs.
- `whileObserved` and `fromStream` keep the services of the program that
  called them, not of the code that observes later. Provide a service before
  the call.
- A program that writes more than one value per element runs on
  `whileObserved` and writes them in one update. `fromStream` publishes each
  element in an update of its own, so a box written from inside its stream
  lands one update earlier, and a reader of both sees them disagree.
- Whether a feed has loaded is the application's own box. Pinna cannot tell
  when a snapshot is complete. The program writes the flag in the same
  update as the rows, so no reader sees it loaded with the rows missing.
- `watchScoped` and `fromStream` compare with `Object.is` unless given
  `{ equals }`, as the core's `watch` and `box` do: a value from a stream or
  a select has no schema to compare by, unlike a `schemaBox`. `changes`
  takes no options and compares with `Object.is`.
- Stop a program by closing its scope, not by keeping stop functions.

## Answers

| Call | Answers |
| --- | --- |
| `watchScoped(realm, (read) => ..., (value, previous) => effect, { equals?, name? })` | An effect that starts the watch in the caller's scope. A result equal under `equals`, `Object.is` by default, is no change, so it neither runs nor interrupts the effect. `name` names the watch in its errors. |
| `changes($x)` | A stream of `$x`'s current value, then each change; a slow consumer skips to the newest. Takes a box or a computed value, not an atom. |
| `observeScoped($x)` | An effect that holds `$x`, a box, a computed value, or an atom, observed until the scope closes. |
| `whileObserved($x, program)` | An effect that runs `program` while `$x`, a box, a computed value, or an atom, is observed, each run in a scope of its own. A defect is logged at the error level, and the next observation starts the program again. Closing the caller's scope interrupts a run and waits for it; later observation does not start it again. |
| `fromStream(realm, stream, initial, { equals?, name? })` | A read-only value: `initial`, then the stream's latest element; needs the stream's services. The stream runs with the services of the program that made the value, and restarts each time the value is observed again. The value resets to `initial` when the last observer leaves or the scope closes; closing the scope stops the stream for good. An element equal under `equals`, `Object.is` by default, notifies nobody; `name` names the value for `inspect`. |
| `withStage(realm, (stage) => section, { name?, conflicts? })` | The section's value, with its stage applied; a section failure, defect, or interruption drops the stage and the outcome stands. A conflict fails with `StageConflict`; a recipe that throws on replay is a defect. An interruption once landing began leaves the stage applied; the exit still contains `Interrupt`. |
| `withStage(stage, (child) => section, { name? })` | A savepoint over `stage`, with the same success and failure behavior. The child inherits its root's conflict mode, takes no `conflicts` option, and never fails with `StageConflict`: its root checks what the child read. |
| `StageConflict` | The tagged error `withStage` fails with when a stage opened with `{ conflicts: "fail" }` finds that what it read changed: `stage`, `changed`, and `observables`, as on `StageConflictError`. |

## Lifetimes

Three owners run an effect, and the owner decides what stops it.

- Observation owns the stream of a `fromStream` value and a `whileObserved`
  program: each runs from the first observer to the last, and starts again with the next. This fits
  data that matters only while something shows it, such as a rate or a
  search result: the last observer leaving stops the work, and the value
  resets to `initial`, so a stale rate never shows as current.
- A fiber owns a feed whose data is kept whether shown or not, such as the
  quotes of a board that several screens and watches read from one
  collection. The feed runs until the fiber is interrupted, with nothing
  observing it ([Live data](../guides/live-data.md#with-effect)).
- A scope owns a command, such as an order sent or a file saved. It runs
  to its end whatever the screen does, and only closing the scope
  interrupts it. This fits work a person started and expects finished.

A `fromStream` value keeps the context of the program that made it, and its
stream runs with that context on every observation. A service the stream
needs is provided where the value is made, not where it is observed. The
stream's type lists the services it needs but not the clock, so a stream
that polls or sleeps keeps the clock of the program that made the value: a
test on `TestClock` provides it before the value is made
([Testing](#testing)).

```ts
import { fromStream } from "@frondruntime/pinna-effect";
import { Context, Effect, Schedule, Stream } from "effect";

class Rates extends Context.Service<Rates, { readonly latest: Effect.Effect<number> }>()("Rates") {}

// The stream needs Rates, so making the value needs it: fromStream keeps the
// context of the program that makes the value, and the stream runs with it
// on every observation, whatever program observes the value later.
const makeRate = fromStream<number | undefined, Rates>(
  realm,
  Stream.fromEffectSchedule(
    Effect.gen(function* () {
      const rates = yield* Rates;
      return yield* rates.latest;
    }),
    Schedule.spaced("1 minute"),
  ),
  undefined,
);

const rate = makeRate.pipe(Effect.provideService(Rates, { latest: fetchRate }));
```

A command that an event handler starts runs in a scope made once for the
application. `Effect.forkIn` runs it in that scope, and
`Effect.runForkWith(context)` gives it the application's services, the
clock among them, so a test's `TestClock` reaches the command too.

```ts
import { box, update } from "@frondruntime/pinna-effect";
import { Effect } from "effect";

type OrderStatus = "idle" | "sending" | "sent";
const $orderStatus = box<OrderStatus>(realm, "idle");

const sendOrder = (amount: number) =>
  Effect.gen(function* () {
    update(realm, (_read, write) => write($orderStatus, "sending"));
    yield* submit(amount);
    update(realm, (_read, write) => write($orderStatus, "sent"));
  });

// Made once, in the application's scope. An event handler calls `send`; the
// order runs in that scope, so unmounting the component that sent it, or the
// last observer of $orderStatus leaving, interrupts nothing. Closing the
// application's scope interrupts it. The order runs with the services the
// application was given, its clock among them.
const orders = Effect.gen(function* () {
  const scope = yield* Effect.scope;
  const context = yield* Effect.context<never>();
  const send = (amount: number): void => {
    Effect.runForkWith(context)(Effect.forkIn(sendOrder(amount), scope));
  };
  return { send };
});
```

`Effect.forkScoped` schedules its fiber and returns before the fiber runs,
so the next line cannot count on what the fiber writes.
`{ startImmediately: true }` runs the fiber up to its first wait at once.

```ts
import { untracked } from "@frondruntime/pinna-effect";
import { Effect } from "effect";

const sendAndRead = Effect.gen(function* () {
  // The fiber runs up to its first wait before the next line, so the read
  // sees "sending". Without startImmediately, it starts later, and the read
  // sees "idle".
  yield* Effect.forkScoped(sendOrder(10), { startImmediately: true });
  return untracked(realm, (read) => read($orderStatus));
});
```

## Failures as values

`fromStream` takes a stream whose error type is `never`, because a value
has no channel for a failure. A typed failure the screen shows is mapped
into the value's own type: the good elements and the failure become members
of one union, and `Stream.catch` turns the failure into the last element.

```ts
import { fromStream } from "@frondruntime/pinna-effect";
import { Data, Stream } from "effect";

// The transport's typed failure.
class RateUnavailable extends Data.TaggedError("RateUnavailable")<{ readonly reason: string }> {}

// What the screen shows: a rate, or why there is none.
type RateState =
  | { readonly _tag: "Loading" }
  | { readonly _tag: "Rate"; readonly rate: number }
  | { readonly _tag: "Unavailable"; readonly reason: string };

const showRate = (rates: Stream.Stream<number, RateUnavailable>) =>
  fromStream<RateState>(
    realm,
    rates.pipe(
      Stream.map((rate): RateState => ({ _tag: "Rate", rate })),
      // The failure becomes the last element: the stream ends on it, and the
      // value shows it until the last observer leaves.
      Stream.catch((error) =>
        Stream.succeed<RateState>({ _tag: "Unavailable", reason: error.reason }),
      ),
    ),
    { _tag: "Loading" },
  );
```

The stream ends on the failure, and the value shows it until the last
observer leaves. The next observer starts the stream again, from `initial`.

## Testing

A program that polls or sleeps is tested on `TestClock`, from
`effect/testing`, so the test moves time instead of waiting for it. The
test realm is as on [Testing](../guides/testing.md).

- Provide `TestClock.layer()` around the program that makes a `fromStream`
  value, not only around the one that observes it. The value keeps the
  clock of the program that made it, and a value made on the live clock
  polls on the live clock whatever the observer provides.
- Hold the value observed with `observeScoped`. Its stream runs only while
  something observes the value, so an unobserved poll never runs and the
  value stays `initial`.

```ts
import { expect, test } from "bun:test";
import { testRealm } from "@frondruntime/pinna/testing";
import { fromStream, observeScoped, RealmService, untracked } from "@frondruntime/pinna-effect";
import { Effect, Schedule, Stream } from "effect";
import { TestClock } from "effect/testing";

test("a poll advances with the test clock", async () => {
  using realm = testRealm();
  let polls = 0;
  const poll = Effect.sync(() => ++polls);

  const latest = await Effect.gen(function* () {
    // Made under TestClock: fromStream keeps the clock of the program that
    // makes the value, and the poll waits on it.
    const $polls = yield* fromStream(
      realm,
      Stream.fromEffectSchedule(poll, Schedule.spaced("1 minute")),
      0,
    );
    // The poll runs only while something observes the value.
    yield* observeScoped($polls);
    yield* TestClock.adjust("2 minutes");
    return untracked(realm, (read) => read($polls));
  }).pipe(
    Effect.scoped,
    Effect.provideService(RealmService, realm),
    Effect.provide(TestClock.layer()),
    Effect.runPromise,
  );

  expect(latest).toBe(3);
});
```

`TestClock.adjust` is not a completion signal. It runs the sleeps that fall
due and waits for the fibers it woke to suspend; work that no sleep holds,
such as a load that yields between rows, can still be running when it
returns, and `TestClock.adjust(0)` wakes nothing at all. A test waits on a
value the program publishes when its work is done: a `Deferred`, or a box
read through `changes`.

```ts
import { expect, test } from "bun:test";
import { testRealm } from "@frondruntime/pinna/testing";
import { box, changes, RealmService, untracked, update } from "@frondruntime/pinna-effect";
import { Effect, Stream } from "effect";
import { TestClock } from "effect/testing";

test("a test waits on what the program publishes, not on the clock", async () => {
  using realm = testRealm();
  const $loadedRows = box(realm, 0);
  const $loaded = box(realm, false);
  // Yields between rows; no sleep holds it, so the clock has nothing to wait for.
  const load = Effect.gen(function* () {
    for (let row = 1; row <= 100; row++) {
      yield* Effect.yieldNow;
      update(realm, (_read, write) => write($loadedRows, row));
    }
    update(realm, (_read, write) => write($loaded, true));
  });

  const loaded = await Effect.gen(function* () {
    yield* Effect.forkScoped(load);
    yield* changes($loaded).pipe(
      Stream.filter((done) => done),
      Stream.runHead,
    );
    return untracked(realm, (read) => read($loadedRows));
  }).pipe(
    Effect.scoped,
    Effect.provideService(RealmService, realm),
    Effect.provide(TestClock.layer()),
    Effect.runPromise,
  );

  expect(loaded).toBe(100);
});
```

A helper that runs a program and declares its realm with `using` is
`async` and awaits the run before it returns. Returning the promise without
`await` disposes the realm while the program's scope is still open, and the
dispose throws `The test realm is not at rest: watch still running.`, one
entry per watch the program holds. The dispose stops each watch first, so no
watch reruns in the next test, but a fiber the program forked runs on until
its scope closes; the fix is `return await`.

```ts
import { expect, test } from "bun:test";
import { testRealm } from "@frondruntime/pinna/testing";
import { RealmService, schemaBox, update, watchScoped } from "@frondruntime/pinna-effect";
import { Deferred, Effect, Schema } from "effect";

// `async` and `return await`: the realm is disposed after the program's scope
// closes. A helper that returns the promise without awaiting it disposes the
// realm while the program's watch still runs.
const searchOnce = async (query: string): Promise<string> => {
  using realm = testRealm();
  const $query = schemaBox(realm, Schema.String, "");
  return await Effect.gen(function* () {
    const searched = yield* Deferred.make<string>();
    yield* watchScoped(
      realm,
      (read) => read($query),
      (value) => Deferred.succeed(searched, value),
    );
    update(realm, (_read, write) => write($query, query));
    return yield* Deferred.await(searched);
  }).pipe(Effect.scoped, Effect.provideService(RealmService, realm), Effect.runPromise);
};

test("a helper awaits its program before its realm is disposed", async () => {
  expect(await searchOnce("pinna")).toBe("pinna");
});
```

| Call | Answers |
| --- | --- |
| `Effect.provide(TestClock.layer())` | A program whose sleeps and schedules wait on the test clock. |
| `TestClock.adjust(duration)` | Moves the test clock and runs the sleeps that fall due; not a signal that other work finished. |

## Stages

`withStage` holds a section's writes in a stage
([Updates](../state/updates.md#stages)) and lands them when the section
succeeds. A section failure, defect, or interruption drops
them, so nothing the section staged reaches the realm. An interruption
once landing began leaves the stage applied; the exit still contains `Interrupt`.

```ts
import { box, stageUpdate, withStage } from "@frondruntime/pinna-effect";
import { Effect } from "effect";

const $balance = box(realm, 100);
const $status = box<"idle" | "sent">(realm, "idle");

const transfer = (amount: number) =>
  withStage(realm, (stage) =>
    Effect.gen(function* () {
      stageUpdate(stage, (read, write) => {
        write($balance, read($balance) - amount);
        write($status, "sent");
      });
      // Nothing shows until send succeeds; a failure or an interruption drops it.
      yield* send(amount);
    }),
  );
```

Over a stage, `withStage` is a savepoint. A section that fails and is caught
leaves the outer stage as it was, and each attempt of an `Effect.retry`
opens a fresh child.

```ts
import { box, stageUpdate, withStage } from "@frondruntime/pinna-effect";
import { Effect } from "effect";

const $notes = box<ReadonlyArray<string>>(realm, []);

const transferWithNote = (amount: number, note: string) =>
  withStage(realm, (stage) =>
    Effect.gen(function* () {
      stageUpdate(stage, (read, write) => {
        write($balance, read($balance) - amount);
      });
      // A child stage: when the section fails, its writes never reach the outer
      // stage, and each retry starts from a fresh child.
      yield* withStage(stage, (section) =>
        Effect.gen(function* () {
          const text = yield* describeTransfer(note);
          stageUpdate(section, (_read, write) => {
            write.modify($notes, (notes) => {
              notes.push(text);
            });
          });
        }),
      ).pipe(
        Effect.retry({ times: 2 }),
        Effect.catch(() => Effect.void),
      );
      yield* send(amount);
    }),
  );
```

With `{ conflicts: "fail" }`, a stage whose reads changed before it landed
fails with `StageConflict`, and `Effect.retry` runs the section again over
the new values.

```ts
import { box, StageConflict, stageUpdate, withStage } from "@frondruntime/pinna-effect";
import { Effect } from "effect";

const $price = box(realm, 10);
const $total = box(realm, 0);

const checkout = withStage(
  realm,
  (stage) =>
    Effect.sync(() => {
      stageUpdate(stage, (read, write) => {
        write($total, read($price) * 2);
      });
    }),
  { conflicts: "fail" },
).pipe(
  // The price changed after the stage read it: run the section again over the new one.
  Effect.retry({ while: (error) => error instanceof StageConflict, times: 3 }),
);
```

- `withStage` applies the stage after the section succeeds, synchronously,
  so nothing runs between the section's last write and the landing.
- The release drops the stage whether or not it applied: `dropStage` does
  nothing to a closed stage. An `applyStage` precondition failure leaves
  the stage open and becomes a defect in `withStage`; the release then
  drops it and its open children. A conflict or replay throw drops it
  before the release.
- Retrying reruns the section, requests included. Retry only a section that
  is safe to repeat; `withStage` never retries on its own.
- A host that lands a stage inside its own update, or applies only on a
  condition, calls `openStage`, `applyStage`, and `dropStage` itself, with
  `Effect.acquireUseRelease`.

## See also

- [Reacting](../state/reacting.md): `watch` and `autorun` without Effect.
- [Classes](./classes.md): `decode`, JSON in and a checked model out.
- [Live data](../guides/live-data.md): a WebSocket feed and a refetch as Effect programs.
- [Testing](../guides/testing.md): a test realm, and a program run in it.
