Skip to content

How it works ​

This section describes tscache from its source code. Each diagram lists the files and symbols it is drawn from, as path#symbol, so you can check it against the code. Paths are relative to the repository root.

  • Overview (this page): the pieces of the system and where each one runs.
  • Package map: the five package entries, and a module graph generated from the package's imports.
  • Data model: the grid, slots, segments, coverage, versions and watermarks inside one cache.
  • Code tour: the source read in the order a request travels, from the entries to the Vite plugin, with the demo-hub scenario that shows each part at work.

The flows, each a sequence diagram with a walkthrough and the code behind it:

  • Startup and fallback: the hosting chain and the handshake.
  • A read, end to end: get() from a tab to the worker and back, with in-flight subtraction and coalescing.
  • Sharing across tabs: the first tab starts the SharedWorker, later tabs join, a tab closes, the worker dies.
  • Fences and invalidation: the clear generation and the invalidate fence.
  • Auth refresh: a refused token, the authInvalid broadcast, updateAuth, and the next read.
  • Persistence: restore at cache(), write-back, and a quota stop.
  • Live feeds: the reference clients' elected feed tab, which puts bars into the shared cache.

The system ​

tscache system overviewEach tab's page holds a client and a PortClient, connected over a MessagePort to one RpcServer in a SharedWorker (or a dedicated worker, or in-process). The server dispatches to the orchestrator and the engine; the orchestrator fetches through the fetcher module, which calls the backend; in the SharedWorker, persistence writes the engine's caches to IndexedDB.Pageone per tab; each tab has its own clientYour applicationyour code callscache.get(range), put, …Client · CacheHandlecreateClient() runs thehosting chain; cache(config)returns a CacheHandlePortClientrequest ids, handshake,errors and eventshosting chain, first that starts wins:shareddedicatedin-processSharedWorkeror a dedicated Worker, or in-process in the pageMessagePortRpcServerhello → init handshake with each port; dispatches eachrequest; sends events to every ready portOrchestratormisses → coalesced fetches, minus the fetchesin flight; the auth stateEngineone CacheState per cache id: segments, coverage,dataset version, finalized watermarkDenseSegment[]CoverageIndexPersistenceSharedWorker: HostedPersistence loads the Persister withimport(); other hostings: clearAll empties the databaseget, invalidateput, clear,hydrate, …read; apply responses as putsobserve changes, restoreYour backendHTTP, WebSocket, …your fetcher calls itFetcher moduleyour code, loadedonce with import();its fetch() answersIndexedDBdatabase tscache:caches and pagescalls or messagesloaded with import() when first neededthe page's end of the port

Every tab runs its own client. The client reaches one engine through a MessagePort: in a SharedWorker, which every tab that loads the same worker script shares, or in a dedicated worker or the page itself when a SharedWorker cannot start. Next to the engine, the orchestrator turns a read's misses into calls to your fetcher module, which is the only part of tscache that talks to your backend. In the SharedWorker, the persistence layer keeps the caches that ask for it in IndexedDB.

PieceRuns inWhat it does
Clienteach pagecreateClient tries the hostings in turn and wraps the connected port; client.cache(config) returns a CacheHandle, whose data methods are each one request
PortClienteach pagethe page's end of the port: completes the handshake, matches each response to its request by id, rebuilds errors and passes events on
RpcServerthe hostingone per engine, any number of ports: greets each port with a hello naming its client id, expects an init back, dispatches requests, and sends events to every ready port
Orchestratorthe hostingserves get and invalidate: plans the fetches a read needs, minus those already in flight, calls the fetcher, applies each response as a put, then reads once
Enginethe hostingthe caches, by id; each CacheState holds its segments, coverage index, dataset version and watermark
Persistencethe hostingin the SharedWorker, loads the persister on demand and keeps caches with persist: true in IndexedDB; in the other hostings, only empties the database at clearAll
Fetcher modulethe hostingyour module: its default export's fetch answers the orchestrator's requests; loaded once, with import(), during the handshake

Drawn from:

The three hostings ​

createClient tries the hostings in a fixed order, shared, then dedicated, then in-process, starting from options.mode (default shared). A hosting that cannot start throws a HostingError: the client steps down to the next one and reports the step as a modeFallback event. Any other error, such as a protocol mismatch, rejects createClient. client.mode tells which hosting won.

HostingWhere the engine runsPersistence
shareda SharedWorker, created with type: 'module', extendedLifetime: true and its generation key as name; one engine serves every tab that connectscaches with persist: true are kept in IndexedDB
dedicateda dedicated Worker per client; the worker's global scope is the portnone; where IndexedDB exists, clearAll empties the database
in-processthe page itself, over a MessageChannel; its code is a chunk the page loads with import() only when the chain reaches itnone; where IndexedDB exists, clearAll empties the database

All three run the same server: each builds an RpcServer around a new Engine, and the server builds its own Orchestrator. The fetcher module is therefore loaded wherever the engine runs, in the page for the in-process hosting.

Where the browser has Web Locks (secure contexts only), the SharedWorker holds a lock for as long as it runs and names it in its hello (hello.lock). A shared-mode client queues on that lock; it is granted the lock only once the worker is gone. A dedicated worker's client learns of its worker's failure from the worker's error event instead. Either way the client then rejects everything pending and emits workerLost; only the detection differs.

The client queues on the lock as soon as hello names it, before the handshake ends. A grant that arrives before init-ok, for example because the worker died while it loaded the fetcher module, fails the shared hosting with a HostingError, and the client steps down the chain instead of emitting workerLost. The handshake timeout (handshakeTimeoutMs) bounds only the wait for hello.

Without Web Locks, the SharedWorker names no lock and the client watches none. A worker that dies with the tab hosting it (a renderer crash) is then noticed only if the browser fires a close event on the port; where it does not, pending requests stay pending and no workerLost is emitted.

Drawn from:

One read, briefly ​

A read, end to end follows these steps in a sequence diagram.

  1. cache.get(range) sends a get request through the PortClient.
  2. The RpcServer hands it to Orchestrator.get, with a request id of the form clientId:seq.
  3. Without a fetcher, or with cacheOnly: true, the orchestrator answers with one Engine.get. Otherwise it finds the read's misses, subtracts the fetches already in flight for that cache (it waits for those instead), merges adjacent misses, extends each by one slot into the coverage next to it, and calls the fetcher once per merged range. While auth is invalid, or while the fetcher's updateAuth hook is swapping credentials, it fetches and joins nothing: those ranges come back as 'auth-pending' at once.
  4. Each response is applied as a put over the range it was asked for. That makes the part of the range below the cache's watermark, and below the response's own meta.finalizedUntil when it reports one, authoritative (see the watermark). A response that lands after the cache was cleared is dropped instead. The orchestrator waits for the fetches until they settle or auth goes invalid, whichever comes first; fetches still running when auth goes invalid finish in the background.
  5. If the cache was cleared while the read waited, the orchestrator runs one more round: it asks again for what is still missing, minus the ranges whose fetch failed or came back auth-pending. There is no third round.
  6. It then reads the engine once, and labels the misses left by a failed fetch, or by auth going invalid, as 'fetch-failed' or 'auth-pending'.
  7. The result travels back to the page with its typed arrays transferred, not copied.

Drawn from: