Skip to content

Solid ​

The Solid snippet targets Solid 2.0 (2.0.3) with @solidjs/web. Solid 2 removed createResource, so a series is an async memo.

The adapter ​

  • createConnection(open, seeds?) connects once and disposes the client when the calling owner is disposed. Call it in the app's root component and provide the result with <ConnectionContext value={connection}>.
  • createSeries(connection, config, range, { initial }?) returns an accessor for the cache's answer for range(). Put a chart under <Errored>, and under <Loading> unless it has initial.
ts
// tscache in Solid 2: the app's connection in a context, and a series as an
// async memo over the connection's state and the range on screen. The memo
// is Solid's own latest-wins machinery: an answer for a range that a newer
// range has overtaken never lands, and while the next answer loads, the
// previous one stays on screen with isPending() true, so a chart never
// flashes a fallback. A change to the cache over the range on screen, from
// any tab, runs the memo again, at most once per frame (shared/changes.ts);
// a read from the cache alone then replaces the answer without pending.
// One connection (shared/connection.ts) serves every series of the app.

import type {
  CacheConfig,
  GetResult,
  Range,
  TscacheClient,
} from "@anishbenji/tscache";
import {
  type Accessor,
  createContext,
  createSignal,
  onCleanup,
} from "solid-js";
import { ViewReads } from "../shared/changes";
import { type Connection, connect, type Seed } from "../shared/connection";

/** The cache's answer for a range. */
export interface Answer {
  range: Range;
  result: GetResult;
}

/**
 * The app's connection, from {@link createConnection}. Provide it with
 * `<ConnectionContext value={connection}>`; a component reads it with
 * `useContext(ConnectionContext)`.
 */
export const ConnectionContext = createContext<Connection>();

/**
 * Connects for the calling owner's lifetime: call it once, in the app's
 * root component, and provide the connection with {@link ConnectionContext}.
 * Disposing the root (the function `render` or `hydrate` returns) disposes
 * the client; a page that simply closes needs no teardown, since a client
 * disposes itself on `pagehide`.
 */
export function createConnection(
  open: () => Promise<TscacheClient>,
  seeds?: readonly Seed[],
): Connection {
  const connection = connect(open, seeds);
  onCleanup(() => void connection.dispose());
  return connection;
}

export interface SeriesOptions {
  /**
   * The answer to show until the first read lands, such as the server's
   * read when hydrating. The series then never suspends to a `<Loading>`.
   */
  initial?: Answer;
}

/**
 * The cache's answer for `range()`, read through `connection` (in a
 * component, `useContext(ConnectionContext)`). Until the first answer it
 * suspends to the nearest `<Loading>` (unless `initial` is given); a read
 * that fails on a live client, and a connection that failed, throw to the
 * nearest `<Errored>`.
 *
 * A read that a lost worker rejected is not an error: the connection's
 * state moves on, the memo runs again, and the connection's next client
 * reads the range again. A change to the cache over `range()` reads it
 * again: from the cache alone, or with a fetch after a change that wrote
 * nothing (architecture §2.7). Only a read that may fetch is pending
 * (`isPending`): a read from the cache alone, after a live bar say, leaves
 * the answer on screen current until its own replaces it.
 */
export function createSeries(
  connection: Connection,
  config: CacheConfig,
  range: Accessor<Range>,
  { initial }: SeriesOptions = {},
): Accessor<Answer> {
  const [state, setState] = createSignal(connection.state);
  onCleanup(connection.subscribe(() => setState(connection.state)));
  const [changed, setChanged] = createSignal(0);
  // Holds a change during a fetching read, keeps failure labels, and
  // releases after the answer landed (shared/changes.ts).
  const views = new ViewReads({
    shown: range,
    interval: config.interval,
    alignmentOffset: config.alignmentOffset ?? 0,
    reread: () => setChanged((n) => n + 1),
  });
  /** Counts the memo's runs: only the latest run's cache-only answer lands. */
  let run = 0;
  /** A cache-only read's failure on a live client, for the next run to throw. */
  let failed: { error: unknown } | undefined;
  onCleanup(() => {
    run++;
    views.dispose();
  });

  // A memo that can also be written (a derived signal): a cache-only
  // answer is written over the last one, so it never makes the series
  // pending, and the next run that fetches replaces it.
  const [answer, setAnswer] = createSignal<Answer>(
    (previous: Answer | undefined) => {
      const current = state();
      const asked = range();
      changed();
      const mine = ++run;
      if (failed !== undefined) {
        const { error } = failed;
        failed = undefined;
        throw error;
      }
      if (current.status === "failed") throw current.error;
      // Pending until the client connects, which runs the memo again. A
      // fresh promise each time: one shared promise would keep the
      // callbacks of every run that ever waited on it.
      if (current.status === "connecting") return new Promise<never>(() => {});
      const read = views.read(
        connection.cache(current.client, config),
        asked,
        current,
      );
      const landing = read.answer.then((result) => ({ range: asked, result }));
      if (read.cacheOnly && previous !== undefined) {
        landing.then(
          (next) => {
            if (run === mine) setAnswer(() => next);
          },
          (error: unknown) => {
            // As below: only a failure on a live client counts.
            if (run !== mine || connection.state !== current) return;
            failed = { error };
            setChanged((n) => n + 1);
          },
        );
        return previous;
      }
      return landing.catch((error: unknown) => {
        // Only a failure on a live client counts. After a loss the memo
        // has run again on the new state, so this read stays pending
        // and Solid drops it as overtaken, whatever the order in which
        // the rejection and the state change arrive.
        if (connection.state === current) throw error;
        return new Promise<never>(() => {});
      });
    },
    initial === undefined ? undefined : { loadingValue: initial },
  );
  return answer;
}

The series is one async memo over the range and the connection's state. Solid's async memo does latest-wins: a new range drops the run in flight, and after the first answer the previous one stays on screen with isPending(answer) true. A memo, unlike a store, neither proxies nor copies the typed arrays. The memo is a derived signal (createSignal(fn), a memo that can also be written): when the cache changes over the range, a read from the cache alone is written over the answer on screen, so isPending(answer) stays false, and only a read that may fetch is pending. A lost worker moves the connection to connecting, which runs the memo again, and the replacement client reads.

Pages ​

tsx
// The server-rendered page, as both halves render it (ssr-server.tsx,
// ssr-browser.tsx). Until hydration ends, both render the server's read, so
// the browser's hydration render writes exactly the server's markup; then
// the live chart, which the browser's half passes as children, takes over.
// The live chart is created only after hydration, so nothing in it can make
// the hydrating render differ from the server's.

import type { GetResult } from "@anishbenji/tscache";
import type { JSX } from "@solidjs/web";
import { createSignal, onSettled, Show } from "solid-js";
import { describe } from "../shared/candles";
import type { ServerRead } from "../shared/hydration";

/** The chart as the server read it. */
export function ServerChart(props: { result: GetResult }) {
  return <p>{describe(props.result)}</p>;
}

/** The server's read, then, once hydration has ended, `children`. */
export function Page(props: { read: ServerRead; children?: JSX.Element }) {
  const [hydrated, setHydrated] = createSignal(false);
  onSettled(() => {
    setHydrated(true);
  });
  return (
    <Show
      when={hydrated()}
      fallback={<ServerChart result={props.read.result} />}
    >
      {props.children}
    </Show>
  );
}
tsx
// A page with one chart, client-only. The app's root component connects
// once and provides the connection; the chart reads its range through it.
// Disposing the app disposes the client.

import { type ClientOptions, createClient } from "@anishbenji/tscache";
import { render } from "@solidjs/web";
import { Errored, isPending, Loading, useContext } from "solid-js";
import { candles, describe, lastDays } from "../shared/candles";
import { ConnectionContext, createConnection, createSeries } from "./series";

function Chart() {
  // A chart passes its visible range as a signal, so scrolling reads the
  // new range; the cache fetches only what it does not hold.
  const range = lastDays(90, Date.now());
  const answer = createSeries(
    useContext(ConnectionContext),
    candles,
    () => range,
  );
  // A chart library would take answer().result.timestamps and .fields here.
  return (
    <p aria-busy={isPending(answer) ? "true" : undefined}>
      {describe(answer().result)}
    </p>
  );
}

function App(props: { options: ClientOptions }) {
  const connection = createConnection(() => createClient(props.options));
  return (
    <ConnectionContext value={connection}>
      <Errored
        fallback={(error) => (
          <p role="alert">The chart could not load: {String(error())}</p>
        )}
      >
        <Loading fallback={<p>Loading the last 90 days…</p>}>
          <Chart />
        </Loading>
      </Errored>
    </ConnectionContext>
  );
}

/**
 * A page with one chart, showing the last 90 days. `options` carries the
 * worker and fetcher URLs as your bundler serves them
 * (docs/guides/worker-setup.md). Returns the page's teardown.
 */
export function startPage(
  options: ClientOptions,
  element: HTMLElement,
): () => void {
  return render(() => <App options={options} />, element);
}

Server rendering ​

The server reads, renders the page with renderToString and writes the read into the page. The browser hydrates the same page showing the server's read, then mounts the live chart, seeded with the read and given it as initial, so the chart shows the server's answer at once and fetches at most the uncovered tail.

tsx
// A server-rendered page in Solid, the server's half. The server reads with
// its own client, renders the page from that read, and writes the read into
// the page as data the browser starts its cache from (ssr-browser.tsx).
// Without the browser's half, this is a page rendered on the server alone.

import { generateHydrationScript, renderToString } from "@solidjs/web";
import { candles, lastDays } from "../shared/candles";
import { dehydrate, jsonScript, SERVER_READ } from "../shared/hydration";
import { type ServerOptions, serverReader } from "../shared/server";
import { Page } from "./page";

/**
 * The page renderer for this server process; create it once at startup,
 * since it owns the process's client (docs/guides/worker-setup.md, "Server
 * rendering"). It renders the page's body: Solid's hydration script, the
 * app in `#app`, and the read.
 */
export function pageRenderer(
  options: ServerOptions,
): (now: number) => Promise<string> {
  const reader = serverReader(options);
  const hydration = generateHydrationScript();
  return async (now) => {
    const read = await reader(candles, lastDays(90, now));
    // renderToString is synchronous, so the read comes first.
    const app = renderToString(() => <Page read={read} />);
    return `${hydration}<div id="app">${app}</div>${jsonScript(SERVER_READ, dehydrate(read))}`;
  };
}
tsx
// A server-rendered page in Solid, the browser's half. It hydrates the
// server's markup from the server's read, then mounts the live chart, which
// connects with that read as every client's seed and shows it until its
// own answer lands, so the page never shows a fallback. The browser fetches
// only what the read did not cover (the provisional last day, say).

import { type ClientOptions, createClient } from "@anishbenji/tscache";
import { hydrate } from "@solidjs/web";
import { Errored, isPending, useContext } from "solid-js";
import { candles, describe } from "../shared/candles";
import {
  type Dehydrated,
  readJson,
  rehydrate,
  SERVER_READ,
  type ServerRead,
} from "../shared/hydration";
import { Page, ServerChart } from "./page";
import { ConnectionContext, createConnection, createSeries } from "./series";

function Chart(props: { read: ServerRead }) {
  // The server's range: its covered parts come from the seed, so the first
  // answer costs at most the uncovered tail.
  const answer = createSeries(
    useContext(ConnectionContext),
    candles,
    () => props.read.range,
    { initial: props.read },
  );
  // A chart library would take answer().result.timestamps and .fields here.
  return (
    <p aria-busy={isPending(answer) ? "true" : undefined}>
      {describe(answer().result)}
    </p>
  );
}

function Live(props: { options: ClientOptions; read: ServerRead }) {
  const connection = createConnection(
    () => createClient(props.options),
    [{ config: candles, read: props.read }],
  );
  return (
    <ConnectionContext value={connection}>
      <Errored
        fallback={(error) => (
          <>
            <p role="alert">
              The chart could not update: {String(error())}. It shows what the
              server read.
            </p>
            <ServerChart result={props.read.result} />
          </>
        )}
      >
        <Chart read={props.read} />
      </Errored>
    </ConnectionContext>
  );
}

/** Takes over the server's page. Returns its teardown. */
export function hydratePage(options: ClientOptions): () => void {
  const root = document.getElementById("app");
  if (root === null) throw new Error("the page has no #app");
  const read = rehydrate(candles, readJson<Dehydrated>(SERVER_READ));
  return hydrate(
    () => (
      <Page read={read}>
        <Live options={options} read={read} />
      </Page>
    ),
    root,
  );
}

The snippet's README lists its limits.

Complete apps ​