# Live data

> Read when state comes from a socket or a server. Open a socket while a value is observed and reconnect after a drop, write each message in one update, refetch without losing row identity, and run the same feed as an Effect stream.

## Example

A quote feed keeps one row per symbol, written from a WebSocket. The server
sends a snapshot of every quote when the socket opens, then one change per
message. The parser checks each message by hand, builds new objects with
the fields a quote has, and returns `undefined` for anything else.

```ts
interface Quote {
  readonly symbol: string;
  readonly bid: number;
  readonly ask: number;
}

type QuoteMessage =
  | { readonly type: "snapshot"; readonly quotes: ReadonlyArray<Quote> }
  | { readonly type: "upsert"; readonly quote: Quote }
  | { readonly type: "delete"; readonly symbol: string };

const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
  typeof value === "object" && value !== null;

const isPrice = (value: unknown): value is number =>
  typeof value === "number" && Number.isFinite(value);

// A new object with a quote's fields alone, or undefined.
const toQuote = (value: unknown): Quote | undefined => {
  if (!isRecord(value)) {
    return undefined;
  }
  const { symbol, bid, ask } = value;
  return typeof symbol === "string" && isPrice(bid) && isPrice(ask)
    ? { symbol, bid, ask }
    : undefined;
};

// The message in `data`, or undefined. A snapshot that repeats a symbol is
// no message: `write.replaceAll` would throw on it.
const parseMessage = (data: unknown): QuoteMessage | undefined => {
  let value: unknown;
  try {
    value = JSON.parse(String(data));
  } catch {
    return undefined;
  }
  if (!isRecord(value)) {
    return undefined;
  }
  const { type, quotes, quote, symbol } = value;
  if (type === "snapshot" && Array.isArray(quotes)) {
    const parsed: Array<Quote> = [];
    const seen = new Set<string>();
    for (const item of quotes) {
      const next = toQuote(item);
      if (next === undefined || seen.has(next.symbol)) {
        return undefined;
      }
      seen.add(next.symbol);
      parsed.push(next);
    }
    return { type, quotes: parsed };
  }
  if (type === "upsert") {
    const next = toQuote(quote);
    return next === undefined ? undefined : { type, quote: next };
  }
  if (type === "delete" && typeof symbol === "string") {
    return { type, symbol };
  }
  return undefined;
};
```

The socket is open while something observes the feed. A private atom stands
for the socket, and `$status`, `$symbols`, and each `quote(symbol)` read it,
so the first observer of any of them runs `connect`, and the last one
leaving runs its cleanup, which closes the socket and cancels a pending
reconnect. A hook on `keys` would miss a reader of one row: `row(key)` never
reads `keys`.

```ts
import {
  atom,
  box,
  collection,
  computed,
  computedFunction,
  Model,
  onObserved,
  type Realm,
  update,
} from "@frondruntime/pinna";

type Status = "connecting" | "open" | "closed";

const quotesUrl = "wss://example.com/quotes";

class QuoteFeed extends Model {
  // Stands for the socket: observing any public field below opens it.
  private readonly $socket = atom(this.realm);
  private readonly $state = box<Status>(this.realm, "closed");
  private readonly $rows = collection(this.realm, {
    keyOf: (quote: Quote) => quote.symbol,
    // A snapshot builds new objects; a quote with the same prices is kept.
    equals: (previous, next) => previous.bid === next.bid && previous.ask === next.ask,
  });

  readonly $status = computed(this.realm, (read) => {
    read(this.$socket);
    return read(this.$state);
  });

  readonly $symbols = computed(this.realm, (read) => {
    read(this.$socket);
    return read(this.$rows.keys);
  });

  readonly quote = computedFunction(this.realm, (read, symbol: string) => {
    read(this.$socket);
    return read.row(this.$rows, symbol);
  });

  constructor(realm: Realm) {
    super(realm);
    onObserved(this.$socket, () => this.connect());
  }

  // Opens the socket, and reopens it after each drop: 0.5 s after the
  // first, doubling up to 30 s, back to 0.5 s once a message arrives.
  // Returns what closes it. The state lives in this call, so a socket from
  // an earlier observation never schedules a reconnect.
  private connect(): () => void {
    let socket: WebSocket | undefined;
    let timer: ReturnType<typeof setTimeout> | undefined;
    let attempt = 0;
    const open = () => {
      this.setStatus("connecting");
      const next = new WebSocket(quotesUrl);
      next.onopen = () => {
        this.setStatus("open");
      };
      next.onmessage = (event: MessageEvent) => {
        attempt = 0;
        this.receive(event.data);
      };
      next.onclose = () => {
        this.setStatus("closed");
        timer = setTimeout(open, Math.min(30_000, 500 * 2 ** attempt));
        attempt++;
      };
      socket = next;
    };
    open();
    return () => {
      clearTimeout(timer);
      if (socket !== undefined) {
        socket.onclose = null;
        socket.close();
      }
    };
  }

  private setStatus(status: Status): void {
    update(this.realm, (_read, write) => write(this.$state, status));
  }

  private receive(data: unknown): void {
    const message = parseMessage(data);
    if (message === undefined) {
      // The host's error sink, which a realm made without onError uses too.
      reportError(new TypeError("quotes: dropped a message that is not one"));
      return;
    }
    // One update per message: a reader sees all of it or none of it.
    update(this.realm, (_read, write) => {
      switch (message.type) {
        case "snapshot":
          // A quote equal to the one held keeps its row and notifies nobody.
          return write.replaceAll(this.$rows, message.quotes);
        case "upsert":
          return write.upsert(this.$rows, message.quote, { at: "end" });
        case "delete":
          return write.remove(this.$rows, message.symbol);
      }
    });
  }
}
```

A watch, an autorun, `observe`, or a mounted `useValue(feed.$symbols)` opens
the socket.

```ts
import { createRealm, watch } from "@frondruntime/pinna";

const realm = createRealm();
const feed = new QuoteFeed(realm);

// The first observer opens the socket; stopping the last one closes it.
const stop = watch(
  realm,
  (read) => read(feed.$status),
  (status) => {
    console.log(`quotes: ${status}`);
  },
);
```

A request is the same shape without a socket. An `AbortController` cancels
the request a newer one replaces, and `reconcile` keeps each unchanged row's
instance, so a refetch that changed nothing notifies nobody. The parser
reuses `isRecord` and `isPrice` from the first sample and throws on a body
that does not fit, and the status ends in `"failed"`.

```ts
import { box, Model, reconcile, update } from "@frondruntime/pinna";

interface Position {
  readonly id: string;
  readonly symbol: string;
  readonly quantity: number;
}

type Load =
  | { readonly state: "loading" }
  | { readonly state: "loaded" }
  | { readonly state: "failed"; readonly error: unknown };

const positionsUrl = "https://example.com/positions";

const toPosition = (value: unknown): Position => {
  if (isRecord(value)) {
    const { id, symbol, quantity } = value;
    if (typeof id === "string" && typeof symbol === "string" && isPrice(quantity)) {
      return { id, symbol, quantity };
    }
  }
  throw new TypeError("positions: a row is not a position");
};

class Positions extends Model {
  readonly $rows = box<ReadonlyArray<Position>>(this.realm, []);
  readonly $load = box<Load>(this.realm, { state: "loading" });
  private controller: AbortController | undefined;

  // Loads the account's positions. A newer call aborts this one, and an
  // aborted call writes nothing, so the last call wins. The rows stay on
  // screen while the next ones load.
  async refresh(account: string): Promise<void> {
    this.controller?.abort();
    const controller = new AbortController();
    this.controller = controller;
    update(this.realm, (_read, write) => write(this.$load, { state: "loading" }));
    try {
      const response = await fetch(`${positionsUrl}/${encodeURIComponent(account)}`, {
        signal: controller.signal,
      });
      if (!response.ok) {
        throw new Error(`positions: the server answered ${response.status}`);
      }
      const body: unknown = await response.json();
      if (!Array.isArray(body)) {
        throw new TypeError("positions: the body is not a list");
      }
      const next = body.map(toPosition);
      if (controller.signal.aborted) {
        return;
      }
      update(this.realm, (read, write) => {
        // Unchanged positions keep their instance; nothing changed keeps the array.
        write(
          this.$rows,
          reconcile(read(this.$rows), next, {
            keyOf: (position) => position.id,
            equals: (previous, current) =>
              previous.symbol === current.symbol && previous.quantity === current.quantity,
          }),
        );
        write(this.$load, { state: "loaded" });
      });
    } catch (error) {
      // An aborted fetch rejects too; the newer call owns the status.
      if (controller.signal.aborted) {
        return;
      }
      update(this.realm, (_read, write) => write(this.$load, { state: "failed", error }));
    }
  }
}
```

## Rules

- Write each message in one update. A reader then sees a snapshot whole or
  not at all; a write per row would show every row in between.
- Write a snapshot through `write.replaceAll` on a collection with `equals`.
  An unchanged row keeps its instance, so a reconnect that sends the same
  quotes reruns no reader. `write.replaceAll` throws on a repeated key and
  writes nothing, so reject one at the boundary.
- Await a request, then write its result in an update of its own: an update
  is synchronous ([Updates](../state/updates.md)).
- Check that a request was not aborted before writing its result or its
  failure. An aborted `fetch` rejects, and without the check the older
  request's failure overwrites the newer one's `"loading"`.
- The hook writes `"connecting"`, in an update. The cleanup writes nothing,
  so rows and status stay as last written while nothing observes the feed,
  and the next snapshot replaces the rows.
- Keep a connection's state inside the call that opens it, and detach the
  socket's `onclose` before closing it, so a socket from an earlier
  observation schedules no reconnect.
- A message the parser drops goes to the host's `reportError`, where a realm
  made without `onError` also reports. A realm made with `onError` does not
  see it.

`onObserved` and atoms are on [Lifecycles](../state/lifecycles.md), the
writes to a collection on [Collections](../state/collections.md), and
`reconcile` on [Updates](../state/updates.md).

## With Effect

The same feed as an Effect program. `Schema.fromJsonString` parses and
checks a message in one step, and fails with a `SchemaError` for anything
that does not fit.

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

const Quote = Schema.Struct({
  symbol: Schema.String,
  bid: Schema.Finite,
  ask: Schema.Finite,
});
type Quote = typeof Quote.Type;

const QuoteMessage = Schema.Union([
  Schema.Struct({ type: Schema.Literal("snapshot"), quotes: Schema.Array(Quote) }),
  Schema.Struct({ type: Schema.Literal("upsert"), quote: Quote }),
  Schema.Struct({ type: Schema.Literal("delete"), symbol: Schema.String }),
]);
type QuoteMessage = typeof QuoteMessage.Type;

// Parses the JSON and checks it in one step; fails with a SchemaError.
const decodeMessage = Schema.decodeUnknownEffect(Schema.fromJsonString(QuoteMessage));
```

The watchlist is a `BoxField`, checked on every write: people type it, and
it is saved with the board. The quotes are a plain collection and the status
a plain box, written only from messages the decode checked, so nothing checks
them twice ([Plain or schema boxes](../start/index.md#plain-or-schema-boxes)).
Loosening a field's schema to make the feed fast would leave every other
writer of that field unchecked; the hot rows go in a plain collection
instead.

```ts
import { BoxField, box, collection, SchemaModel, update } from "@frondruntime/pinna-effect";
import { Schema } from "effect";

type Status = "connecting" | "open" | "closed";

class QuoteBoard extends SchemaModel<QuoteBoard>("QuoteBoard")({
  // Typed by people and saved with the board: every write is checked.
  $watchlist: BoxField(Schema.Array(Schema.String)),
}) {
  // Written by the feed alone, from messages the decode checked: checked nowhere else.
  readonly $quotes = collection(this.realm, {
    keyOf: (quote: Quote) => quote.symbol,
    equals: Schema.toEquivalence(Quote),
  });
  readonly $status = box<Status>(this.realm, "closed");

  setStatus(status: Status): void {
    update(this.realm, (_read, write) => write(this.$status, status));
  }

  add(symbol: string): void {
    update(this.realm, (read, write) => write(this.$watchlist, [...read(this.$watchlist), symbol]));
  }

  // One update per message: a reader sees all of it or none of it.
  receive(message: QuoteMessage): void {
    update(this.realm, (_read, write) => {
      switch (message.type) {
        case "snapshot":
          return write.replaceAll(this.$quotes, message.quotes);
        case "upsert":
          return write.upsert(this.$quotes, message.quote, { at: "end" });
        case "delete":
          return write.remove(this.$quotes, message.symbol);
      }
    });
  }
}
```

`Stream.callback` turns the socket's callbacks into a stream. The socket
opens in `Effect.acquireRelease`, so closing the stream's scope closes it,
and a drop fails the stream with `SocketClosed`.

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

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

// Each message the socket receives. The stream fails with SocketClosed when
// the socket closes, and closing the stream's scope closes the socket.
const socket = (url: string, onOpen: () => void): Stream.Stream<string, SocketClosed> =>
  Stream.callback<string, SocketClosed>((queue) =>
    Effect.acquireRelease(
      Effect.sync(() => {
        const next = new WebSocket(url);
        next.onopen = onOpen;
        next.onmessage = (event: MessageEvent) => {
          Queue.offerUnsafe(queue, String(event.data));
        };
        next.onclose = (event: CloseEvent) => {
          Queue.failCauseUnsafe(queue, Cause.fail(new SocketClosed({ code: event.code })));
        };
        return next;
      }),
      (next) =>
        Effect.sync(() => {
          next.onclose = null;
          next.close();
        }),
    ),
  );
```

`changes` streams the watchlist, and `Stream.switchMap` closes the socket
of the previous list and opens one for the new list. `Stream.retry` reopens
the socket after a drop, and its schedule resets once a message passes
through. Each message is decoded, then written in one update; a message
that fails either step is logged and dropped.

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

const quotesUrl = "wss://example.com/quotes";

// 0.5 s after a drop, doubling up to 30 s; a message that arrives resets it.
const reconnect = Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("30 seconds")]);

// Follows the board's watchlist: a new list closes the socket and opens one for it.
const follow = Effect.fn("follow")(function* (board: QuoteBoard) {
  yield* changes(board.$watchlist).pipe(
    Stream.switchMap((symbols) => {
      const url = `${quotesUrl}?symbols=${symbols.map(encodeURIComponent).join(",")}`;
      return socket(url, () => board.setStatus("open")).pipe(
        Stream.onStart(Effect.sync(() => board.setStatus("connecting"))),
        Stream.tapError(() => Effect.sync(() => board.setStatus("closed"))),
        Stream.retry(reconnect),
      );
    }),
    Stream.runForEach((data) =>
      decodeMessage(data).pipe(
        // A write that throws, such as a snapshot that repeats a symbol, is undone.
        Effect.flatMap((message) => Effect.try(() => board.receive(message))),
        Effect.catch((error) => Effect.logWarning("quotes: dropped a message", error)),
      ),
    ),
  );
});
```

A layer provides the realm. The fiber owns the feed: the socket is open
while the fiber runs, whether or not anything observes the board, and
interrupting the fiber closes it. A value that should run only while a
screen shows it is owned by observation instead, through `fromStream`
([Programs](../effect/programs.md#lifetimes)).

```ts
import { createRealm, decode, RealmService } from "@frondruntime/pinna-effect";
import { Effect, Fiber, Layer } from "effect";

const realm = createRealm();
const RealmLive = Layer.succeed(RealmService, realm);

// Throws the SchemaError when the saved board does not fit.
const board = decode(realm, QuoteBoard)({ watchlist: ["ACME", "GLOBEX"] });

// The socket is open while the fiber runs.
const fiber = Effect.runFork(follow(board).pipe(Effect.provide(RealmLive)));

// Interrupting the fiber closes the socket.
const close = () => Effect.runFork(Fiber.interrupt(fiber));
```

- Wrap the write in `Effect.try`. A throw inside `Effect.sync` is a defect,
  and a defect in `Stream.runForEach` ends the program, socket and all.
  `Effect.try` makes it an error the program logs; the update has already
  undone the write.
- Write each status in the stage that knows it: `Stream.onStart` for
  `"connecting"`, the socket's `onopen` for `"open"`, and `Stream.tapError`,
  before `Stream.retry`, for `"closed"`. Without `Stream.tapError`, the
  status stays `"open"` through every reconnect wait.

## See also

- [Lifecycles](../state/lifecycles.md): `onObserved`, atoms, and `observe`.
- [Collections](../state/collections.md): `keys`, `row(key)`, and `equals`.
- [Updates](../state/updates.md): what an update undoes when it throws.
- [Programs](../effect/programs.md): `changes`, `watchScoped`, `fromStream`, and who owns a feed.
- [Classes](../effect/classes.md): `SchemaModel`, `BoxField`, and `decode`.
- [Hooks](../react/hooks.md): `useValue` and a list that rerenders one row.
