Skip to content

Snapshots ​

A snapshot is what a cache knows about a range: the present points inside it, the covered sub-ranges, the dataset version and the watermark in force, and the grid and schema they belong to. A server takes one with its read and puts it in the page; the browser applies it to its own cache, so its first read fetches only what the server did not know.

Taking one ​

get(range, { snapshot: true }) resolves with the result and its snapshot, both from the same read: snapshot.coverage equals the result's coverage, and its points are the result's points. Equal cache state gives equal snapshots. The snapshot's buffers are fresh and are moved to the page with the result. snapshot.range is the request snapped outward.

Carrying one in HTML: encodeSnapshot and decodeSnapshot ​

A snapshot holds binary buffers. encodeSnapshot(snapshot) returns it with each mask and field buffer as base64 text: a plain JSON value. decodeSnapshot(encoded) restores it. NaN, which JSON would turn into null, survives. Both use the runtime's base64 (Uint8Array.prototype.toBase64 and fromBase64 where they exist, btoa/atob otherwise), so they run in browsers and Node alike.

ts
import {
  type CacheConfig,
  createClient,
  encodeSnapshot,
  type Range,
} from "@anishbenji/tscache";
import type { Context } from "./fetcher";

export const candles: CacheConfig = {
  id: "crypto/BTC",
  interval: 60_000,
  fields: { open: "f64", high: "f64", low: "f64", close: "f64", volume: "u32" },
};

export interface ServerOptions {
  /** The fetcher module as a URL the server can import(). */
  fetcherModule: string;
  /** The backend's origin: a server has no page origin to resolve against. */
  origin: string;
}

/**
 * The page renderer of this server process. Create it once at startup: it
 * owns the process's one client, so a render reads what earlier renders
 * fetched. Every visitor reads the same cache: public data only.
 */
export async function createRenderer({ fetcherModule, origin }: ServerOptions) {
  const context: Context = { origin };
  const client = await createClient({
    mode: "in-process", // a server has no workers
    fetcher: { module: fetcherModule, context },
  });
  const cache = await client.cache(candles);
  return async (range: Range): Promise<string> => {
    // One read gives the page's columns and the cache's snapshot.
    const { snapshot, ...result } = await cache.get(range, { snapshot: true });
    if (snapshot === undefined) throw new Error("the read carries no snapshot");
    // Escape every "<" so no string can close the script element.
    const json = JSON.stringify(encodeSnapshot(snapshot)).replaceAll(
      "<",
      "\\u003c",
    );
    return `<p id="chart">${result.timestamps.length} candles</p>
<script id="tscache-snapshot" type="application/json">${json}</script>`;
  };
}

Escape every < before the JSON goes into the page

JSON.stringify leaves < as it is, and the HTML parser ends a <script> element at the first </script> it meets, inside a JSON string or not. A field name, a dataset version, or anything else in the element (the columns beside the snapshot) that contains </script> would end the element early: the rest of the JSON is parsed as HTML, the browser's JSON.parse of the element's text throws, and when the string comes from data, the text after it runs as markup and script in your page (cross-site scripting). Replacing every < with \u003c, as the snippet does, keeps the JSON valid and decoding to the same value, and leaves the parser nothing to end the element with. tscache does not do it for you: encodeSnapshot returns a JSON value, not HTML.

decodeSnapshot checks the shape only and throws TscacheError for anything that is not an encoded snapshot; whether the snapshot fits the cache is hydrate's to check.

Applying one: hydrate ​

ts
import {
  type ClientOptions,
  createClient,
  decodeSnapshot,
  type EncodedSnapshot,
  type GetResult,
  type Range,
  TscacheError,
} from "@anishbenji/tscache";
import { candles } from "./snapshots-server";

/**
 * Starts the page's cache from the server's snapshot (the JSON text of its
 * script element), then reads `range`, which fetches only what the
 * snapshot did not cover. `options` carry the worker URL and the fetcher:
 * the browser's client loads what the snapshot lacks.
 */
export async function startCache(
  options: ClientOptions,
  range: Range,
  text: string | null | undefined,
): Promise<GetResult> {
  const client = await createClient(options);
  // A worker lost meanwhile fails every pending call, hydrate included, as
  // does a page hidden for good: pagehide disposes the client.
  let lost = false;
  client.on("workerLost", () => {
    lost = true;
  });
  const cache = await client.cache(candles);
  if (text != null) {
    try {
      const seed = decodeSnapshot(JSON.parse(text) as EncodedSnapshot);
      const { applied, skipped } = await cache.hydrate(seed);
      console.log(applied, skipped); // skipped: "version-mismatch" when refused
    } catch (error) {
      // The client is gone: no read follows, so the loss is the answer.
      if (lost || disposed(error)) throw error;
      // Not seeded: hydration saves fetches and is never needed for correct
      // answers, so the read below fetches instead. A worker from before
      // hydrate (a stale cached script) refuses the op; any other failure
      // is worth a warning in development. It names the error and never
      // prints its message, which can quote the snapshot: the page's data.
      const old =
        error instanceof TscacheError && error.message === "unknown op hydrate";
      if (!old && development()) {
        const why = error instanceof Error ? error.name : typeof error;
        console.warn(`snapshot not applied (${why}); the cache fetches`);
      }
    }
  }
  return cache.get(range);
}

/** Whether `error` is a disposed client's answer to every call. */
function disposed(error: unknown): boolean {
  return error instanceof TscacheError && error.message === "client disposed";
}

// Bundlers replace the exact text `process.env.NODE_ENV` at build time, so
// it is read bare; a page that no bundler prepared has no `process`.
declare const process: { env: { NODE_ENV?: string } };

/** Whether this is a development build. */
function development(): boolean {
  try {
    return process.env.NODE_ENV !== "production";
  } catch {
    return false;
  }
}
ts
import workerUrl from "@anishbenji/tscache/worker?worker&url";
import fetcherModule from "./fetcher.ts?fetcher";
import { startCache } from "./snapshots-browser";

const MINUTE = 60_000;
const now = Math.floor(Date.now() / MINUTE) * MINUTE;
const result = await startCache(
  { workerUrl, fetcher: { module: fetcherModule } },
  { start: now - 6 * 60 * MINUTE, end: now }, // the range the server read
  document.getElementById("tscache-snapshot")?.textContent,
);

cache.hydrate(snapshot) runs as one call inside the worker, so no other tab's write lands in the middle. Its rules:

  • Checked first, in full. The snapshot must describe this cache: the same interval, offset and fields, and well-formed ranges and payloads. Anything else throws TscacheError before anything changes; a snapshot is made by the library, so a malformed one is corruption, never repaired.
  • Version. If both the snapshot and the cache have a version and they differ, nothing is applied and the result is { applied: [], skipped: 'version-mismatch' }. A cache without a version adopts the snapshot's without clearing.
  • Watermark. The snapshot's finalizedUntil advances the cache's watermark, never moves it back.
  • Only where nothing is known. Each covered range of the snapshot, minus what the cache already covers and minus its provisional region, is written as authoritative. Covered slots are never touched, so a newer fetch by another tab survives; the snapshot's own provisional tail is not applied, and the browser fetches it.
  • No events. hydrate never clears, so it emits no cacheCleared and no mergeWarning.

It resolves with applied, the ranges it wrote, ascending. The snapshot is cloned to the worker, not transferred, so it stays usable: the client that replaces a lost one can be seeded from the same object.

Hydration is an optimisation

A worker from before hydrate (a stale cached script) rejects the call with TscacheError "unknown op hydrate", and a get with snapshot: true returns no snapshot. Treat that as nothing applied: the cache fetches instead. Treat any other failure to apply a snapshot as not seeded too, and warn in development with the error's name only, as the snippet above does: the message can quote the snapshot (JSON.parse quotes the text it stopped at), which carries the page's data. hydrate's own errors do not print a refused value, except a format of 1 or 2; most name the field and the type it received. A few still print a timestamp or slot index that already passed validation, as context, which is why the name alone is the safe thing to log. A worker lost while hydrate is pending fails it too; that is no news about the snapshot, so the snippet gives up without a warning.

With an Engine, engine.snapshot(cacheId, range) takes a snapshot without a read, for persistence and tests (The engine). Server rendering puts it all together. The design is §2.8 of the architecture document.