Skip to content

Getting started ​

Install ​

sh
npm install @anishbenji/tscache   # or: bun add @anishbenji/tscache, pnpm add @anishbenji/tscache

The package is ESM-only and has no runtime dependencies. Its entries:

ImportFor
@anishbenji/tscachethe page: createClient, the types, the errors, encodeSnapshot and decodeSnapshot
@anishbenji/tscache/workerthe worker script; you serve it, you never import it into the page
@anishbenji/tscache/fetcheryour fetcher module: its types and AuthInvalidError, nothing else
@anishbenji/tscache/enginethe engine without a worker, for Node and tests
@anishbenji/tscache/gridgrid arithmetic for the page: snapRange, slotStart, nextSlotStart
@anishbenji/tscache/vitefetcherUrl(), the Vite plugin for the fetcher module (vite 8 is an optional peer)

1. Serve the worker ​

createClient needs the URL of the @anishbenji/tscache/worker script as your bundler serves it. With Vite, ?worker&url gives it:

ts
import { createClient } from "@anishbenji/tscache";
// Vite: `?worker&url` bundles the module worker and gives its served URL.
import workerUrl from "@anishbenji/tscache/worker?worker&url";
// @anishbenji/tscache/vite's plugin: the fetcher module's URL, its exports kept.
import fetcherModule from "./fetcher.ts?fetcher";

const client = await createClient({
  workerUrl,
  fetcher: { module: fetcherModule },
});
console.log(client.mode); // "shared", or "dedicated" where SharedWorker is missing

webpack and setups without a bundler serve a copy of the package's dist/ directory instead; see Workers and fallback. If the URL is wrong, both worker hostings fail and the client quietly falls back to an engine in the page, which no other tab shares: check client.mode once.

2. Write a fetcher ​

The fetcher is an ES module the worker loads with import(). Its default export has a fetch method that returns every point of the requested range:

ts
import {
  AuthInvalidError,
  type Fetcher,
  type FetchRequest,
  type FetchResponse,
} from "@anishbenji/tscache/fetcher";

/** What this app passes as `context` to createClient and updateAuth. */
export interface Context {
  token?: string;
  /**
   * The backend's origin. The browser omits it: its requests resolve
   * against the page's origin. A server has none, so it passes one.
   */
  origin?: string;
}

/**
 * The float fields of this app's caches (dtype `f64` or `f32` in their
 * CacheConfig); `volume` is a `u32`. The worker does not tell a fetcher the
 * dtypes, so the fetcher knows them, as it knows the backend's protocol.
 */
const FLOAT_FIELDS = new Set(["open", "high", "low", "close"]);

/** One page of the backend's answer. */
interface Page {
  timestamps: number[];
  /** JSON has no NaN, so a missing value arrives as null. */
  fields: Record<string, (number | null)[]>;
  meta: {
    version: string;
    /** The first timestamp that is not final yet. */
    finalizedUntil: number;
  };
  /** Where the next page starts; absent on the last one. */
  next?: number;
}

/**
 * The interval as this backend's query names it. A fixed interval is a
 * number of ms; a calendar cache's is an object, which `String()` would
 * turn into "[object Object]", so name its unit instead.
 */
function intervalParam(interval: FetchRequest["interval"]): string {
  return typeof interval === "number" ? String(interval) : interval.unit;
}

async function fetchPage(request: FetchRequest, start: number): Promise<Page> {
  const { token, origin } = (request.context ?? {}) as Context;
  // The cache id names the series: `<dataset>/<symbol>`.
  const query = new URLSearchParams({
    start: String(start),
    end: String(request.range.end),
    interval: intervalParam(request.interval),
    offset: String(request.alignmentOffset),
  });
  const path = `/api/series/${request.cacheId}?${query}`;
  const response = await fetch(
    origin === undefined ? path : new URL(path, origin),
    {
      headers: token === undefined ? {} : { authorization: `Bearer ${token}` },
    },
  );
  // The one error the worker treats specially: every tab hears authInvalid.
  if (response.status === 401) throw new AuthInvalidError("token refused");
  // Anything else thrown makes the range 'fetch-failed' for this get.
  if (!response.ok) throw new Error(`backend answered ${response.status}`);
  return (await response.json()) as Page;
}

const fetcher: Fetcher = {
  async fetch(request): Promise<FetchResponse> {
    // The answer is authoritative for the whole range: collect every page.
    const timestamps: number[] = [];
    // No prototype: a field may be named like an Object.prototype member
    // (`constructor`), which `??=` would otherwise find already set.
    const fields: Record<string, number[]> = Object.create(null);
    let page = await fetchPage(request, request.range.start);
    const { version } = page.meta;
    let finalizedUntil = page.meta.finalizedUntil;
    for (;;) {
      if (page.meta.version !== version) {
        throw new Error("version changed mid-fetch");
      }
      // A loop, not push(...values): spreading a long page overflows the stack.
      for (const t of page.timestamps) timestamps.push(t);
      for (const [name, values] of Object.entries(page.fields)) {
        fields[name] ??= [];
        const column = fields[name];
        // A put rejects null in every field (N68). In a float field a missing
        // value is NaN. An integer field has none, and rejects NaN and, by
        // decision 38, fractions too: a null there is the backend's error,
        // and failing the range ('fetch-failed') says so.
        const float = FLOAT_FIELDS.has(name);
        for (const [i, value] of values.entries()) {
          if (value !== null) column.push(value);
          else if (float) column.push(NaN);
          else throw new Error(`${name} has no value at ${page.timestamps[i]}`);
        }
      }
      // The earliest watermark: a later page must not vouch for an
      // earlier page's provisional points.
      finalizedUntil = Math.min(finalizedUntil, page.meta.finalizedUntil);
      if (page.next === undefined) break;
      page = await fetchPage(request, page.next);
    }
    return { timestamps, fields, meta: { version, finalizedUntil } };
  },
};

export default fetcher;

With Vite, add the plugin, which serves the module with its default export intact:

ts
// vite.config.ts
import { fetcherUrl } from "@anishbenji/tscache/vite";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [fetcherUrl()],
  // An ES worker keeps the persistence code a chunk of its own, downloaded
  // only by a worker that persists (Vite's default 'iife' inlines it).
  worker: { format: "es" },
});

For TypeScript, declare the ?fetcher import once:

ts
// What an app's bundler declares for these imports. Vite's client types
// declare `?worker&url`; `?fetcher` is @anishbenji/tscache/vite's (the worker setup
// guide).
declare module "*?worker&url" {
  const url: string;
  export default url;
}
declare module "*?fetcher" {
  const url: string;
  export default url;
}

The fetcher is optional. Without one, the cache holds only what you put, and get reports the rest as misses. Writing a fetcher has the full contract.

3. Open a cache ​

ts
const MINUTE = 60_000;
const candles = await client.cache({
  id: "candles/ACME",
  interval: MINUTE, // required: there is no default
  fields: { open: "f64", high: "f64", low: "f64", close: "f64", volume: "f64" },
});

interval is required: every timestamp of the cache lies on its grid. Every tab opens a cache with the same config; a different structure under the same id is refused with ConfigError.

4. Read ​

ts
// The bar forming now: reading to Date.now() would also ask for the next one.
const now = Math.floor(Date.now() / MINUTE) * MINUTE;
const result = await candles.get({ start: now - 6 * 60 * MINUTE, end: now });

// Present points only: equal-length columns, no holes.
const { timestamps, fields } = result;
console.log(timestamps.length, fields.close?.at(-1));

// What is known, and what is not.
for (const range of result.coverage) {
  console.log("authoritative", range.start, range.end);
}
for (const miss of result.misses) {
  console.log("not loaded", miss.range, miss.reason, miss.error?.message);
}

A range is inclusive at both ends, in milliseconds, and need not be on the grid: a read widens it to the grid points around it, so a chart's visible range goes straight in. The read awaits the fetches for what the cache lacks and resolves with every point it holds in the range, the parts it knows for certain (coverage), and the parts it does not (misses, each with a reason). It never rejects because data is unavailable: a failed fetch comes back as a miss.

Next ​