Writing a fetcher
The fetcher is the one piece of your code that runs inside tscache's worker. The worker loads it once, with import(), and calls its default export's fetch for every range a get needs.
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;The module
- An ES module, served from your origin, with its default export intact. With Vite, use
?fetcher;?worker&urldrops the exports. A relative URL resolves against tscache's own file, not the page; that file sits beside the worker script unless you wrap the worker or re-chunk tscache's code. Pass an absolute URL or path. - Self-contained. It closes over nothing on the page. What it needs (a token, an API origin) arrives as
context, a structured-cloneable value fromcreateClientorupdateAuth; each fetch gets a copy of the latest. - Imports from
@anishbenji/tscache/fetcher, which holds the types andAuthInvalidErrorand nothing else. - Loaded at startup. A module that fails to import, or whose default export has no
fetch, makescreateClientreject with aTscacheErrornaming it, so a broken fetcher does not look like a flaky backend. - Loads or fails. Nothing bounds the load in 0.2.0: an
import()that never settles (a module server that accepts the request and never answers, a top-levelawaitthat never resolves) leavescreateClientpending. The handshake timeout ends at the worker's hello, before the load starts. - Never closes its worker (
self.close()): a dedicated worker that does fires noerror, and the calls of its tab hang. - Bounds each request, for example with
AbortSignal.timeout()on itsfetch, and throws when the bound passes. The worker never cancels a fetch, and one fetch serves everygetthat needs one of its slots, from every tab, so a request that never settles holds them all. The thrown error is an ordinary failure: a'fetch-failed'miss, and the nextgettries again.
What a response must contain
A response is authoritative for the whole requested range. Every point the backend has in [range.start, range.end] must be in it; slots without a point become confirmed gaps, and points the cache held there that the response lacks are removed. So:
- Paginated APIs: loop until you have every page before returning. A partial response records the missing points as gaps that are never fetched again.
- Late or revised data: report
meta.finalizedUntil, the first timestamp that is not final yet. Points at or after it are stored but stay provisional and are fetched again; the response is authoritative only below it. Across pages, report the earliest page's watermark. - Versioned datasets: report
meta.version. A change clears every tab's cache and applies this response. Do not assemble one response from two versions. - Timestamps on the cache's grid (
request.interval,request.alignmentOffset), ascending, unique, with every field present. A response that fails validation makes the range'fetch-failed'. - The interval is a number or a calendar interval.
request.intervalis the cache's interval as its config resolved it: milliseconds, or for a calendar cache (Calendar intervals) an object such as{ unit: "day", zone: "America/New_York", at: "09:30" }, withrequest.alignmentOffset0. Narrow it before doing arithmetic or building a query:String(request.interval)of a calendar interval is"[object Object]", and TypeScript does not flag it. The fetcher above names the unit (intervalParam). Stamp each bar at its slot's start, the instant the zone's clock readsat. - Missing values as
NaNin float fields, and every value one its field can hold (Batches). JSON has noNaNand writes it asnull, and a put rejectsnullin every field. The fetcher above maps it toNaNin its float fields only (else if (float) column.push(NaN), withFLOAT_FIELDSnaming them, since the worker does not pass the dtypes). An integer field cannot mark a missing value (Integer fields) and rejectsNaN, fractions and values outside its dtype's range, so anullthere fails the whole response: the fetcher above throws, naming the field and timestamp, and the range is'fetch-failed'. Round in the fetcher if the backend sends fractions for an integer field.
The range is already coalesced: adjacent misses are merged, and a miss next to known data is extended by one slot into it (one interval on a fixed grid, one day or month on a calendar grid). Its ends are slot starts.
Errors
| You throw | The get sees | Then |
|---|---|---|
AuthInvalidError | the range as 'auth-pending' | every tab hears authInvalid; no fetch runs until the next updateAuth, or a joining tab with other material (Credentials) |
| anything else | the range as 'fetch-failed', with the error's name and message | nothing is cached; the next get tries again |
Retries, backoff and timeouts are yours: tscache retries nothing on behalf of a get that already returned.
Deduplication
One fetch serves every tab: a second get, from any tab, that needs the same coalesced range of the same cache awaits the fetch in flight. Overlapping but different ranges are fetched separately.
Binary pages
JSON is the easy format, and for small pages it is fast enough. For a chart's pages it is often the largest cost in a fetch after the network: every number is parsed from text, and every column is then copied into a typed array. A binary page of typed columns needs neither. Measured in Chromium 153 on an Apple Silicon Mac, for one 5,000-bar OHLCV page:
| Decoding | Body | Time |
|---|---|---|
Row JSON ([{ t, o, h, l, c, v }]), JSON.parse | 382 KB | 533 µs |
Columnar JSON through Response.json(), then Float64Array.from per column | 252 KB | 443 µs |
The same with JSON.parse on text already read | 252 KB | 321 µs |
Binary columns through Response.arrayBuffer(), viewed in place | 220 KB | 93 µs |
| Binary columns already in memory: views only / copied into new arrays | 220 KB | 0.13 µs / 10.4 µs |
The decode runs in the worker, so it delays every fetch's data, in every tab the worker serves. The fetcher contract already accepts typed arrays (FetchResponse takes Float64Array timestamps and any numeric typed array per field), so binary pages need nothing from tscache: only a format your backend and your fetcher agree on.
The format
The examples define one, in examples/mock-backend/src/columns.ts: a short JSON header, then the timestamps and one column per field, each in its field's dtype. Every number is little-endian, the byte order of every platform a browser runs on.
| Bytes | Holds |
|---|---|
| 4 | the magic TSC and the format version, 1 (54 53 43 01) |
| 4 | H, the header's length, as a u32 |
H | the header, UTF-8 JSON: a ColumnsHeader |
| to a multiple of 8 | zero padding |
count × 8 | the timestamps, as f64 |
| per field, in the header's order | zero padding to a multiple of 8, then count values of the field's dtype |
import type { Dtype } from "@anishbenji/tscache";
/** The media type of a columns body, for Accept and Content-Type. */
export const COLUMNS_TYPE = "application/vnd.tscache.columns";
/** One field column: its name and how its values are stored. */
export interface ColumnSpec {
name: string;
dtype: Dtype;
}
/** The JSON header that precedes the columns. */
export interface ColumnsHeader {
/** Points in the page: the length of every column. */
count: number;
/** The field columns, in the order they follow the timestamps. */
fields: ColumnSpec[];
/**
* The answer's other members, as its JSON form carries them (the mock
* backend's `meta` and `next`). Unchecked: the reader knows its backend.
*/
[member: string]: unknown;
}
/** A typed array of numbers: what each dtype's column decodes to. */
export type NumericColumn =
| Float64Array
| Float32Array
| Int32Array
| Uint32Array
| Int16Array
| Uint16Array
| Int8Array
| Uint8Array;Why the padding. A typed array can only view bytes at an offset that is a multiple of its element size: new Float64Array(buffer, 12, n) throws. Starting every column on an 8-byte boundary lets each one be viewed where it lies in the body. A count of 0 is a valid, empty page.
Why a JSON header. It is a few hundred bytes, parsed once per page, and it carries what the JSON form carries besides the columns (here the page's meta and its next cursor) without a second format.
Integer fields cannot hold NaN. A float column carries NaN as is; the encoder refuses a value an integer dtype cannot hold rather than store it as 0.
Asking for it
The mock backend serves both formats from one URL, and both answers carry Vary: Accept so that a cache between them keeps the two apart. A request gets a columns body only when its Accept names application/vnd.tscache.columns, with a quality above 0 and no lower than JSON's; a wildcard alone, or no Accept, gets JSON, so a client that has not heard of the format is unaffected. Media types are compared without their parameters and without regard to case, on both sides:
/**
* The media type of a Content-Type, or of one range of an Accept: what
* precedes its parameters, trimmed and lowercased, as media types are
* compared.
*/
function mediaTypeOf(value: string): string {
return (value.split(";")[0] ?? "").trim().toLowerCase();
}
/**
* A range's quality: its `q` parameter, 1 without one, or undefined when
* the value is not a quality (0 to 1, at most three decimals).
*/
function qualityOf(range: string): number | undefined {
for (const parameter of range.split(";").slice(1)) {
const [name = "", value = ""] = parameter.split("=").map((s) => s.trim());
if (name.toLowerCase() !== "q") continue;
return /^(0(\.\d{0,3})?|1(\.0{0,3})?)$/.test(value)
? Number(value)
: undefined;
}
return 1;
}
/** Ranges that match JSON, from the most specific. */
const JSON_RANGES = ["application/json", "application/*", "*/*"];
/**
* Whether to answer a request with a columns body, from its Accept header.
* Only a range that names COLUMNS_TYPE selects it, never a wildcard, so a
* client that has not heard of the format keeps getting JSON. Its quality
* must be above 0 and at least JSON's: the quality of the most specific
* range that matches `application/json`, or 0 when none does.
*/
export function acceptsColumns(accept: string | null): boolean {
let columns = 0;
/** The most specific JSON range seen, as an index into JSON_RANGES. */
let jsonRank = JSON_RANGES.length;
let json = 0;
for (const range of (accept ?? "").split(",")) {
const type = mediaTypeOf(range);
const quality = qualityOf(range);
if (quality === undefined) continue;
if (type === COLUMNS_TYPE) columns = Math.max(columns, quality);
const rank = JSON_RANGES.indexOf(type);
if (rank < 0 || rank > jsonRank) continue;
json = rank < jsonRank ? quality : Math.max(json, quality);
jsonRank = rank;
}
return columns > 0 && columns >= json;
}This fetcher is the one at the top of this page, asking for columns:
import {
AuthInvalidError,
type Fetcher,
type FetchRequest,
type FetchResponse,
} from "@anishbenji/tscache/fetcher";
import {
COLUMNS_TYPE,
decodeColumns,
fromColumns,
fromJson,
isColumnsType,
joinPages,
type NormalPage,
} from "@examples/mock-backend/columns";
import type { Context } from "./fetcher";
/** What a page carries besides its columns, in either format. */
interface PageMembers {
meta: { version: string; finalizedUntil: number };
/** Where the next page starts; absent on the last one. */
next?: number;
}
/** A page: its columns normalized, whatever its format, and its members. */
interface Page extends PageMembers {
columns: NormalPage;
}
/**
* 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;
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 headers: Record<string, string> = {
accept: `${COLUMNS_TYPE}, application/json;q=0.5`,
};
if (token !== undefined) headers.authorization = `Bearer ${token}`;
const response = await fetch(
origin === undefined ? path : new URL(path, origin),
{ headers },
);
if (response.status === 401) throw new AuthInvalidError("token refused");
if (!response.ok) throw new Error(`backend answered ${response.status}`);
let columns: NormalPage;
let members: PageMembers;
if (isColumnsType(response.headers.get("content-type"))) {
// One ArrayBuffer, every column a view into it. A truncated or malformed
// body throws ColumnsError, which makes the range 'fetch-failed'.
const decoded = decodeColumns(await response.arrayBuffer());
columns = fromColumns(decoded);
members = decoded.header as unknown as PageMembers;
} else {
// JSON, from a backend that does not serve columns (or not yet).
members = (await response.json()) as PageMembers;
columns = fromJson(members);
}
const { meta, next } = members;
return next === undefined ? { columns, meta } : { columns, meta, next };
}
const fetcher: Fetcher = {
async fetch(request): Promise<FetchResponse> {
// Authoritative for the whole range: collect every page first.
const pages: Page[] = [];
let start: number | undefined = request.range.start;
while (start !== undefined) {
const page = await fetchPage(request, start);
pages.push(page);
start = page.next;
}
const { version } = (pages[0] as Page).meta;
if (pages.some((page) => page.meta.version !== version)) {
throw new Error("version changed mid-fetch");
}
// By the rule table in columns.ts: one dtype stays that dtype; mixed
// formats or dtypes widen to Float64Array, never narrow; pages whose
// field names differ throw ColumnsError.
const { timestamps, fields } = joinPages(pages.map((p) => p.columns));
return {
timestamps,
fields,
meta: {
version,
// The earliest watermark, as in fetcher.ts.
finalizedUntil: Math.min(...pages.map((p) => p.meta.finalizedUntil)),
},
};
},
};
export default fetcher;A range that fits one page is returned as views over the body, with no copy at all; a longer one is joined into one array per column, which tscache copies into its segments either way.
Joining pages
The pages of one range need not agree on their format: a backend in the middle of an upgrade can answer one page as columns and the next as JSON, and two columns pages can carry a field in different dtypes. The fetcher therefore joins in two steps. It normalizes each page as it arrives (fromColumns, fromJson), so that every column is either a typed array of a known dtype or a list of JSON numbers, then joins the normalized pages (joinPages) by one rule:
| The pages hold | Joined as |
|---|---|
| one dtype throughout (columns bodies) | that dtype |
| JSON numbers throughout | number[] |
| anything else: columns and JSON, or columns of different dtypes | Float64Array, when every dtype involved is exact in float64; otherwise a ColumnsError |
Nothing is narrowed or rounded. Joining into the first page's array instead would convert silently: a u16 300 written into a u8 array reads as 44. Every dtype of this format is exact in float64, and JSON numbers are float64 already, so a mixed column always widens; a 64-bit integer dtype, if one were added, would be refused rather than rounded. A JSON column holding anything but numbers is refused when the page is normalized, since JSON writes NaN as null, which the put would reject. Pages whose field names differ, in number, name or order, are refused; the names are compared one by one, never through a string built from them.
// A range fetched in pages is joined in two steps, whatever format each
// page came in: every page is first normalized (fromColumns, fromJson),
// then the normalized pages are joined (joinPages), one rule for all.
//
// How one column joins across pages:
//
// | The pages hold | Joined as |
// |-----------------------------------------|----------------------------|
// | one dtype throughout (columns bodies) | that dtype |
// | JSON numbers throughout | number[] |
// | anything else: columns and JSON, or | Float64Array, when every |
// | columns bodies of different dtypes | dtype involved is exact in |
// | | float64; else ColumnsError |
//
// Nothing is narrowed or rounded: a u16 300 never lands in a u8 array (it
// would read 44). Every dtype of this format is exact in float64
// (EXACT_IN_FLOAT64), and JSON numbers are float64 already, so mixed
// columns always widen; a dtype added later that is not exact (a 64-bit
// integer) must be marked false there, and is then refused. Names and their
// order are compared one by one, never through a string built from them.
/** One column of a page, as its format delivered it. */
export type PageColumn =
| { kind: "typed"; dtype: Dtype; values: NumericColumn }
| { kind: "json"; values: number[] };
/** A page's columns in one form, whatever its format: the join's input. */
export interface NormalPage {
timestamps: PageColumn;
/** Field names, in the page's order. */
names: string[];
/** The fields' columns, in the order of `names`. */
fields: PageColumn[];
}
/** Whether each dtype's every value is a float64 exactly. */
const EXACT_IN_FLOAT64: Readonly<Record<Dtype, boolean>> = {
f64: true,
f32: true,
i32: true,
u32: true,
i16: true,
u16: true,
i8: true,
u8: true,
};
/** A decoded columns body, normalized. */
export function fromColumns(page: DecodedColumns): NormalPage {
return {
timestamps: { kind: "typed", dtype: "f64", values: page.timestamps },
names: page.header.fields.map(({ name }) => name),
fields: page.header.fields.map(({ name, dtype }) => ({
kind: "typed",
dtype,
values: page.fields[name] as NumericColumn,
})),
};
}
function jsonColumn(value: unknown, what: string): PageColumn {
if (!Array.isArray(value) || !value.every((v) => typeof v === "number")) {
// JSON writes NaN as null, which a typed array would store as 0.
throw new ColumnsError(`${what} is not a list of numbers`);
}
return { kind: "json", values: value };
}
/**
* A parsed JSON page (`{ timestamps, fields }`), normalized. Throws
* ColumnsError for a column that is not a list of numbers, or whose length
* differs from the timestamps'.
*/
export function fromJson(page: unknown): NormalPage {
const { timestamps, fields } = (page ?? {}) as Record<string, unknown>;
if (typeof fields !== "object" || fields === null || Array.isArray(fields)) {
throw new ColumnsError("the JSON page has no fields object");
}
const names = Object.keys(fields);
const times = jsonColumn(timestamps, "the JSON page's timestamps");
const count = times.values.length;
return {
timestamps: times,
names,
fields: names.map((name) => {
const column = jsonColumn(
(fields as Record<string, unknown>)[name],
`field "${name}"`,
);
// Checked per page, as decodeColumns does: once pages are joined, a
// long page and a short one can cancel out in the total.
if (column.values.length !== count) {
throw new ColumnsError(
`field "${name}" has ${column.values.length} values for ${count} timestamps`,
);
}
return column;
}),
};
}
/** The columns of a range fetched in one or more pages. */
export interface JoinedPages {
timestamps: Float64Array | number[];
fields: Record<string, NumericColumn | number[]>;
}
function sameNames(a: readonly string[], b: readonly string[]): boolean {
return a.length === b.length && a.every((name, i) => name === b[i]);
}
/** One column from a column of each page, by the rule table above. */
function joinColumn(parts: readonly PageColumn[]): NumericColumn | number[] {
const [first] = parts;
if (first === undefined) throw new ColumnsError("no pages to join");
if (parts.length === 1) return first.values;
if (parts.every((part) => part.kind === "json")) {
const joined: number[] = [];
// A loop, not push(...values): spreading a long page overflows the stack.
for (const part of parts)
for (const value of part.values) joined.push(value);
return joined;
}
const dtypes = new Set(
parts.map((part) => (part.kind === "typed" ? part.dtype : undefined)),
);
const [only] = dtypes;
let Column: ColumnConstructor;
if (dtypes.size === 1 && only !== undefined) {
Column = COLUMN_TYPES[only];
} else {
for (const dtype of dtypes) {
if (dtype !== undefined && !EXACT_IN_FLOAT64[dtype]) {
throw new ColumnsError(`a ${dtype} column cannot widen to f64 exactly`);
}
}
Column = Float64Array;
}
const joined = new Column(
parts.reduce((n, part) => n + part.values.length, 0),
);
let at = 0;
for (const { values } of parts) {
joined.set(values, at);
at += values.length;
}
return joined;
}
/**
* The normalized pages joined, in page order, by the rule table above: one
* page's columns as they are, else one new column per field. Throws
* ColumnsError when the pages' field names differ, in number, name or
* order, or when a column cannot be joined without loss.
*/
export function joinPages(pages: readonly NormalPage[]): JoinedPages {
const [first] = pages;
if (first === undefined) throw new ColumnsError("no pages to join");
if (pages.some((page) => !sameNames(page.names, first.names))) {
throw new ColumnsError("the pages' columns differ in name or order");
}
// No prototype, as in decodeColumns.
const fields: Record<string, NumericColumn | number[]> = Object.create(null);
first.names.forEach((name, i) => {
fields[name] = joinColumn(
pages.map((page) => page.fields[i] as PageColumn),
);
});
const timestamps = joinColumn(pages.map((page) => page.timestamps)) as
| Float64Array
| number[];
return { timestamps, fields };
}The decoder
decodeColumns checks the body against its header before viewing it: a body that is truncated, longer than its columns, or not in this format throws a ColumnsError, which the fetcher lets through, so the range is 'fetch-failed' and the next get tries again. A fetcher that also reads JSON should pick the decoder with isColumnsType(response.headers.get("content-type")), which allows for parameters such as ; charset=binary, rather than comparing the header's text.
/** A decoded page: its header, and its columns as views over the body. */
export interface DecodedColumns {
header: ColumnsHeader;
timestamps: Float64Array;
/** Field name → column, in the header's order. */
fields: Record<string, NumericColumn>;
}
function isColumnSpec(value: unknown): value is ColumnSpec {
if (typeof value !== "object" || value === null) return false;
const { name, dtype } = value as Record<string, unknown>;
return (
typeof name === "string" &&
name.length > 0 &&
typeof dtype === "string" &&
Object.hasOwn(COLUMN_TYPES, dtype)
);
}
function parseHeader(bytes: Uint8Array): ColumnsHeader {
let header: unknown;
try {
header = JSON.parse(
new TextDecoder("utf-8", { fatal: true }).decode(bytes),
);
} catch {
throw new ColumnsError("the columns header is not JSON");
}
if (typeof header !== "object" || header === null) {
throw new ColumnsError("the columns header is not an object");
}
const { count, fields } = header as Record<string, unknown>;
if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0) {
throw new ColumnsError(`the columns header has count ${String(count)}`);
}
if (!Array.isArray(fields) || !fields.every(isColumnSpec)) {
throw new ColumnsError("the columns header's fields are not column specs");
}
if (new Set(fields.map((field) => field.name)).size !== fields.length) {
throw new ColumnsError("the columns header names a field twice");
}
return header as ColumnsHeader;
}
/**
* The body's bytes as a plain Uint8Array starting on an 8-byte boundary of
* its buffer: the caller's memory when it already does, else an explicit
* copy. Never `slice()`: on a subclass such as Node's Buffer it returns a
* view of the same memory, at the same unaligned offset.
*/
function alignedBytes(body: ArrayBuffer | Uint8Array): Uint8Array {
const view = ArrayBuffer.isView(body)
? new Uint8Array(body.buffer, body.byteOffset, body.byteLength)
: new Uint8Array(body);
if (view.byteOffset % 8 === 0) return view;
const copy = new Uint8Array(view.byteLength);
copy.set(view);
return copy;
}
/**
* The columns of a body, as typed-array views over it. Pass what
* `response.arrayBuffer()` returns: nothing is copied. A view that does not
* start on an 8-byte boundary of its buffer (a Node Buffer from a pool, say)
* is copied once, since its columns could not be viewed in place. Throws
* ColumnsError for a body that is not one, truncated, or longer than its
* columns.
*/
export function decodeColumns(body: ArrayBuffer | Uint8Array): DecodedColumns {
requireLittleEndian();
const bytes = alignedBytes(body);
const { buffer, byteOffset, byteLength } = bytes;
if (byteLength < PREAMBLE || MAGIC.some((byte, i) => bytes[i] !== byte)) {
throw new ColumnsError("not a columns body");
}
const headerLength = new DataView(buffer, byteOffset).getUint32(4, true);
if (PREAMBLE + headerLength > byteLength) {
throw new ColumnsError("the columns body ends inside its header");
}
const header = parseHeader(bytes.subarray(PREAMBLE, PREAMBLE + headerLength));
const { count } = header;
/** The next column of `Column`, viewed in place. */
let at = align8(PREAMBLE + headerLength);
const column = (Column: ColumnConstructor): NumericColumn => {
const start = align8(at);
at = start + count * Column.BYTES_PER_ELEMENT;
if (at > byteLength) {
throw new ColumnsError("the columns body ends inside a column");
}
return new Column(buffer as ArrayBuffer, byteOffset + start, count);
};
const timestamps = column(Float64Array) as Float64Array;
// No prototype, so a field named `constructor` or `__proto__` is a key
// like any other rather than an inherited member.
const fields: Record<string, NumericColumn> = Object.create(null);
for (const { name, dtype } of header.fields) {
fields[name] = column(COLUMN_TYPES[dtype]);
}
if (at !== byteLength) {
throw new ColumnsError(
`the columns body has ${byteLength - at} bytes after its last column`,
);
}
return { header, timestamps, fields };
}
/**
* Whether a response's Content-Type is COLUMNS_TYPE, whatever its
* parameters (`; charset=binary`) or case.
*/
export function isColumnsType(contentType: string | null): boolean {
return contentType !== null && mediaTypeOf(contentType) === COLUMNS_TYPE;
}The same file holds encodeColumns, which the mock backend uses to write pages. Copy the file into your app and adapt it: the decoder is part of your code, not of tscache.
Arrow IPC
If your backend already speaks Apache Arrow (DuckDB, Polars, ClickHouse and Arrow Flight servers all can), its IPC stream format is a binary columnar page with a schema of its own, and there is no need for another format. Decode it in the fetcher with the apache-arrow package (tableFromIPC on the response's bytes, then each column's typed array). Points to watch:
- Bundle size. The Arrow library goes into the worker bundle, where the decoder above is a page of code.
- Types. tscache takes timestamps as a
Float64Arrayor anumber[], and Arrow's 64-bit integer columns decode toBigInt64Array: send timestamps as float64, or convert an int64 or timestamp column to aFloat64Array(one copy). - Nulls. tscache fields have no nulls, and a put rejects one. A null in a float column must become
NaN, and an integer column cannot hold one; check each column's null count.
A real one
The examples' fetcher, examples/mock-backend/src/fetcher.ts, pages through the mock backend, asks for columns bodies and reads JSON if the backend answers JSON, retries a fetch whose pages straddle a version change, and reads its backend origin from context on the server:
// The fetcher module the examples load into tscache's worker
// (docs/architecture.md §2.5). A cache id names the series as
// `<dataset>/<symbol>`, optionally followed by more segments that only keep
// ids apart (`candles/ACME/30m`). The backend answers in pages; a fetcher
// must return the whole requested range, so it loops over them. It asks for
// pages as columns bodies (src/columns.ts), which decode without parsing a
// number, and reads JSON from a backend that answers JSON anyway, page by
// page: each page is normalized as it arrives, and the pages are joined by
// the one rule table in src/columns.ts, whatever mix of formats they came in.
// The demo pages' insights (src/insights.ts) wrap it: each fetch is timed
// and its body bytes counted.
import {
AuthInvalidError,
type Fetcher,
type FetchRequest,
type FetchResponse,
} from "@anishbenji/tscache/fetcher";
import {
COLUMNS_TYPE,
decodeColumns,
fromColumns,
fromJson,
isColumnsType,
joinPages,
type NormalPage,
} from "./columns";
import { type MeteredFetch, withInsights } from "./insights";
import { type FetchNotice, postFetchNotice } from "./notices";
/** The fetcher context the examples pass to createClient and updateAuth. */
export interface ExampleContext {
/** Access token; omit when the backend runs without auth. */
token?: string;
/**
* The backend's origin. Omit in the browser, where the worker's own
* origin serves the backend. A server has no such origin, so the SSR
* examples pass the address they listen on.
*/
origin?: string;
/**
* How to ask for pages: as columns bodies (the default) or as JSON, for
* comparing the two.
*/
format?: "columns" | "json";
}
/** What the backend's pages carry besides their columns. */
interface PageMembers {
meta: { version: string; finalizedUntil: number };
next?: number;
}
/** One page: its columns normalized, whatever its format, and its members. */
interface Page extends PageMembers {
columns: NormalPage;
/** The size of its body. */
bytes: number;
}
function stringIn(context: unknown, key: keyof ExampleContext) {
if (typeof context !== "object" || context === null) return undefined;
const value: unknown = (context as Record<string, unknown>)[key];
return typeof value === "string" ? value : undefined;
}
function seriesPath(cacheId: string): string {
const [dataset, symbol] = cacheId.split("/");
if (!dataset || !symbol) {
throw new Error(`cache id "${cacheId}" is not <dataset>/<symbol>`);
}
return `/api/series/${encodeURIComponent(dataset)}/${encodeURIComponent(symbol)}`;
}
async function fetchPage(
path: string,
request: FetchRequest,
start: number,
): Promise<Page> {
const query = new URLSearchParams({
start: String(start),
end: String(request.range.end),
interval: String(request.interval),
offset: String(request.alignmentOffset),
});
const url = `${path}?${query}`;
const origin = stringIn(request.context, "origin");
const token = stringIn(request.context, "token");
const headers: Record<string, string> = {};
if (token !== undefined) headers.authorization = `Bearer ${token}`;
if (stringIn(request.context, "format") !== "json") {
headers.accept = `${COLUMNS_TYPE}, application/json;q=0.5`;
}
// The backend's pages are no-store, and so is the request: it skips the
// browser's HTTP cache, whose lock would otherwise hold identical
// requests made at once (several tabs opening one chart) behind the first.
const response = await fetch(
origin === undefined ? url : new URL(url, origin),
{ headers, cache: "no-store" },
);
if (response.status === 401) {
throw new AuthInvalidError("the backend refused the access token");
}
if (!response.ok) throw new Error(`the backend answered ${response.status}`);
const raw = await response.arrayBuffer();
const bytes = raw.byteLength;
if (!isColumnsType(response.headers.get("content-type"))) {
const body = JSON.parse(new TextDecoder().decode(raw)) as PageMembers;
return { columns: fromJson(body), meta: body.meta, bytes, ...nextOf(body) };
}
// Views over the body: no value is parsed or copied.
const decoded = decodeColumns(raw);
const members = decoded.header as unknown as PageMembers;
return {
columns: fromColumns(decoded),
meta: members.meta,
bytes,
...nextOf(members),
};
}
function nextOf({ next }: PageMembers): { next?: number } {
return next === undefined ? {} : { next };
}
/**
* Every page of the range, or undefined when the dataset version changed
* between two of them: a range is never assembled from two versions.
*/
async function collect(
path: string,
request: FetchRequest,
counted: (bytes: number) => void,
): Promise<FetchResponse | undefined> {
let page = await fetchPage(path, request, request.range.start);
const { version } = page.meta;
const pages: Page[] = [];
// The earliest watermark of all pages: a later page was answered later,
// and its watermark would claim an earlier page's provisional points.
let finalizedUntil = page.meta.finalizedUntil;
for (;;) {
counted(page.bytes);
if (page.meta.version !== version) return undefined;
pages.push(page);
finalizedUntil = Math.min(finalizedUntil, page.meta.finalizedUntil);
if (page.next === undefined) break;
page = await fetchPage(path, request, page.next);
}
// One rule for every mix of formats, and names compared one by one
// (src/columns.ts, "join").
const { timestamps, fields } = joinPages(pages.map((p) => p.columns));
return {
timestamps,
fields,
meta: { version, finalizedUntil },
};
}
async function fetchRange(
request: FetchRequest,
counted: (bytes: number) => void,
): Promise<FetchResponse> {
const path = seriesPath(request.cacheId);
for (let attempt = 0; attempt < 3; attempt++) {
const response = await collect(path, request, counted);
if (response !== undefined) return response;
}
throw new Error("the dataset version kept changing during the fetch");
}
/**
* Fetches the whole range, page by page, and announces the fetch on the
* examples' notice channel. Exported for the benchmark page's preview; its
* modes without tscache call the default export in the page, so every mode
* fetches and decodes with the same code.
*/
export const fetchSeries: MeteredFetch = async (request, meter) => {
let pages = 0;
const notice = (outcome: FetchNotice["outcome"]): FetchNotice => ({
cacheId: request.cacheId,
range: request.range,
pages,
outcome,
});
try {
const response = await fetchRange(request, (bytes) => {
pages++;
meter.page(bytes);
});
postFetchNotice(notice("ok"));
return response;
} catch (error) {
const auth = error instanceof AuthInvalidError;
postFetchNotice(notice(auth ? "auth-invalid" : "failed"));
throw error;
}
};
const fetcher: Fetcher = withInsights(fetchSeries);
export default fetcher;Without a bundler, write the fetcher as a plain ES module and import AuthInvalidError from your served copy of dist/fetcher.js.