Skip to content

The engine ​

@anishbenji/tscache/engine exports Engine, the engine every hosting runs, without a worker, a port or a fetcher. Its methods are synchronous and take the cache id first. Use it in Node, in tests, or to build persistence; in a page, use createClient, which runs this engine in a worker for you.

ts
import { Engine, PutError } from "@anishbenji/tscache/engine";

const engine = new Engine();
const DAY = 86_400_000;
engine.cache({ id: "daily", interval: DAY, fields: { close: "f64" } });

engine.on("cacheCleared", ({ cacheId, reason }) => {
  console.log(cacheId, reason);
});

const monday = Date.UTC(2026, 9, 26);
// Synchronous: no worker, no port, no fetcher.
engine.put(
  "daily",
  { timestamps: [monday, monday + DAY], fields: { close: [101, 102] } },
  { range: { start: monday, end: monday + 6 * DAY } }, // the weekend is a confirmed gap
);
const week = engine.get("daily", { start: monday, end: monday + 6 * DAY });
console.log(week.timestamps.length, week.coverage, week.misses); // 2, one range, []

// A snapshot without a read, for persistence or a test.
const snapshot = engine.snapshot("daily", {
  start: monday,
  end: monday + 6 * DAY,
});
const other = new Engine();
other.cache({ id: "daily", interval: DAY, fields: { close: "f64" } });
console.log(other.hydrate("daily", snapshot).applied);

try {
  engine.put("daily", { timestamps: [monday + 1], fields: { close: [1] } });
} catch (error) {
  if (error instanceof PutError) console.log(error.code); // "misaligned"
}
MethodDoes
cache(config)get-or-create; returns the resolved config the cache was created with
has(id)whether the cache exists; never throws
configOf(id)the resolved config
get(id, range, { snapshot? })the current state only; there is no fetcher, so misses are 'uncached'
put(id, batch, options?)as CacheHandle.put, returning { warnings }; arrays are copied, not transferred
coverage(id, range)the covered sub-ranges, without reading points
invalidate(id, range), clear(id), clearAll(), setFinalizedUntil(id, t)as on the handle
snapshot(id, range)a snapshot of the range, without a read
hydrate(id, snapshot)as CacheHandle.hydrate
on(event, fn), off(event, fn)the one engine event, cacheCleared

Every method that takes an id throws UnknownCacheError for an id without a cache, except has. The entry also exports the errors, encodeSnapshot, decodeSnapshot, DTYPES and the types, so Node code needs nothing else. It has no DOM, worker or timer code.