Code tour
This page reads the source of packages/tscache/src/ in the order a request travels: from the package entries, through the client in the page and the RPC layer, into the worker, where the orchestrator plans fetches in front of the engine, down to the segments and the coverage index, out to IndexedDB, and finally to the Vite plugin that serves the fetcher module at build time.
Each stop lists the symbols to open, as path#symbol (A.b is the member b of A), says what to notice in them, and names a scenario of the demo hub (bun run demo) where the code is at work. bun run docs:check fails when an anchor on this page stops resolving.
1. The entries
Read:
packages/tscache/src/entries/index.ts#createClientpackages/tscache/src/entries/worker.ts#createServerpackages/tscache/src/entries/engine.ts#Enginepackages/tscache/src/entries/fetcher.ts#AuthInvalidErrorpackages/tscache/src/entries/vite.ts#fetcherUrl
What to notice:
- Four of the five entries only re-export.
entries/worker.tsis the one that runs code when it loads: it builds the worker's server and attaches it (stop 4). .re-exportscreateClient, the errors,encodeSnapshotanddecodeSnapshot,DTYPESand types; theCacheHandleandTscacheClientare exported as types only../engineexports theEngineclass itself, for server code and tests../fetcherre-exports fromerrors.tsalone, plus type-only exports of the fetcher types.- Package map shows what each entry's imports reach.
In the demo hub: every example page imports the worker entry as a URL (@anishbenji/tscache/worker?worker&url) and passes it to createClient as workerUrl; for instance Two tabs, one SharedWorker (examples/react-lwcharts/src/client.ts).
2. The client
Read:
packages/tscache/src/client/client.ts#createClientpackages/tscache/src/client/client.ts#CHAINpackages/tscache/src/client/client.ts#connectpackages/tscache/src/client/client.ts#Clientpackages/tscache/src/client/client.ts#Client.#losepackages/tscache/src/client/hosting.ts#handshakepackages/tscache/src/client/hosting.ts#openSharedpackages/tscache/src/client/hosting.ts#openDedicatedpackages/tscache/src/client/hosting.ts#openInProcesspackages/tscache/src/client/cache.ts#CacheHandlepackages/tscache/src/client/events.ts#ClientEmitter
What to notice:
createClientvalidates its options before it creates anything:workerUrlis required unless the chain starts at'in-process', andhandshakeTimeoutMs(default 5000) must be a finite positive number.connectwalksCHAINfromoptions.mode. Only aHostingErrorsteps down to the next hosting; any other error, aProtocolMismatchErrorincluded, rejectscreateClient. Each step is kept and emitted asmodeFallbackon the next macrotask, once the caller has had a chance to subscribe.handshakearms its timer only untilhelloarrives; loading the fetcher module, which happens beforeinit-ok, has no timeout. A workererrorevent before then aborts the handshake.openSharedcreates the SharedWorker withtype: 'module',extendedLifetime: trueand the generation key as itsname, and onhelloqueues on the worker's lifetime lock. A grant beforeinit-okfails the hosting; a grant afterwards aborts the connected port client, whichClient.#loseturns into oneworkerLostevent.openDedicatedlearns of its worker's failure from the worker'serrorevent instead.openInProcessloadsclient/in-process.tswithimport(), so a page served by a worker never downloads the engine; a chunk that fails to load is aHostingError.CacheHandlesends one request per method with its cache id filled in (ononly subscribes, and sends nothing).puttransfers the batch's buffers, so the caller's arrays are detached afterwards;hydratesends its snapshot without a transfer list, so the snapshot stays usable.Clientdisposes itself on the page'spagehide, unless the page enters the back/forward cache (persisted), because the worker would otherwise never learn that the tab went.ClientEmitter.receivemaps wire events ontoClientEventsand ignores names it does not know.
In the demo hub: Two tabs, one SharedWorker: crash the tab that opened first (it hosts the SharedWorker): the other tabs get workerLost and build a new client. The server-rendered entries (Server-rendered candles, Server-rendered sensor) create their server-side client with mode: 'in-process'.
3. The RPC layer
Read:
packages/tscache/src/rpc/protocol.ts#Hellopackages/tscache/src/rpc/protocol.ts#Evtpackages/tscache/src/rpc/protocol.ts#toWireErrorpackages/tscache/src/rpc/protocol.ts#fromWireErrorpackages/tscache/src/rpc/protocol.ts#transferablesOfpackages/tscache/src/rpc/port-client.ts#PortClient.connectpackages/tscache/src/rpc/port-client.ts#PortClient.requestpackages/tscache/src/rpc/server.ts#RpcServer.attachpackages/tscache/src/rpc/server.ts#RpcServer.#initpackages/tscache/src/rpc/server.ts#RpcServer.#handlerspackages/tscache/src/rpc/server.ts#RpcServer.#requestpackages/tscache/src/rpc/server.ts#Persistencepackages/tscache/src/rpc/lifetime.ts#holdLifetimeLockpackages/tscache/src/rpc/lifetime.ts#watchLifetimeLock
What to notice:
- The server speaks first.
RpcServer.attachgives each port a client id (c1,c2, …) and postshellowith the protocol, the library version and, in a SharedWorker, the lifetime lock's name. The client answersinit, which carries the fetcher config. RpcServer.#initrefuses another protocol withinit-err, then loads the fetcher module before it answersinit-ok, so a module that fails to load rejectscreateClientat startup.- Every request is
{ t: 'req', id, op, params }, withidcounted per port client. The server names a requestclientId:id, the request id that request-scoped events carry. RpcServer.#handlerssendsget,invalidateandupdateAuthto the orchestrator andput,clear,setFinalizedUntilandhydrateto the engine. When the hosting has a persistence, every op that names a cache runs throughPersistence.durably,clearAllgoes toPersistence.clearAll, andcacheof a cache withpersist: trueanswers only oncePersistence.openhas settled.RpcServer.#requesttransfers agetresult's buffers (transferablesOf) instead of copying them, and answers adisposebefore it drops the port.- Errors cross the port as plain
WireErrorobjects.toWireErrornames a library error by its class, found withinstanceof, because a minifier may rename the constructor (other errors keep theirname);fromWireErrorrebuilds the class and turns an unknown name into aTscacheError. - Events fan out to every ready port. A port the server drops on its own initiative gets a
byefirst, because a browserMessagePortfires no close event; when the last connection goes, the server flushes persistence. holdLifetimeLocktakes an exclusive Web Lock that is never released while the worker runs, andwatchLifetimeLockqueues on it in shared mode: the grant means the holder is gone.
In the demo hub: Two tabs, one SharedWorker, or any reference client: every tab is one port of the same server, so a second tab draws from what the first one fetched.
4. The worker host
Read:
packages/tscache/src/entries/worker.ts#createServerpackages/tscache/src/entries/worker.ts#dedicatedWorkerScopepackages/tscache/src/entries/worker.ts#sharedWorkerScopepackages/tscache/src/entries/worker.ts#lazyPersistpackages/tscache/src/client/in-process.ts#connectInProcesspackages/tscache/src/persist/clear-only.ts#lazyIdbStore
What to notice:
- The entry tells the two worker kinds apart by their globals: both have
importScripts, and only a SharedWorker's global hasonconnect. - In a dedicated worker, the global scope itself is the port: one server is attached to it at load.
- In a SharedWorker, the
connectlistener goes on at load, so no connection is missed, but ports wait until the worker holds its lifetime lock; everyhellocan then name the lock. One server serves every port. createServerbuilds oneEngineand oneRpcServeraround it, with the persistence the entry asks for: the SharedWorker passes an IndexedDB opener and gets aHostedPersistence, the dedicated worker passesclearOnlyand gets aClearOnlyPersistence, and wherelazyIdbStorefinds no IndexedDB there is no opener and no persistence.connectInProcessbuilds the same pair, anEngineand anRpcServer, in the page, and connects to it over aMessageChannel: the in-process hosting runs the same protocol as the workers.
In the demo hub: Two tabs, one SharedWorker: every tab you open reads mode shared, and a new tab draws three days at once and fetches only the forming bar.
5. The orchestrator
Read:
packages/tscache/src/orchestrator/orchestrator.ts#Orchestrator.getpackages/tscache/src/orchestrator/orchestrator.ts#Orchestrator.#roundspackages/tscache/src/orchestrator/orchestrator.ts#Orchestrator.#roundpackages/tscache/src/orchestrator/orchestrator.ts#planRoundpackages/tscache/src/orchestrator/orchestrator.ts#coalescepackages/tscache/src/orchestrator/orchestrator.ts#Orchestrator.#runpackages/tscache/src/orchestrator/orchestrator.ts#Orchestrator.#applypackages/tscache/src/orchestrator/orchestrator.ts#Orchestrator.#refusedpackages/tscache/src/orchestrator/orchestrator.ts#Orchestrator.invalidatepackages/tscache/src/orchestrator/orchestrator.ts#Orchestrator.loadpackages/tscache/src/orchestrator/orchestrator.ts#Orchestrator.updateAuthpackages/tscache/src/orchestrator/orchestrator.ts#annotatepackages/tscache/src/orchestrator/auth.ts#AuthStatepackages/tscache/src/orchestrator/auth.ts#sameMaterial
What to notice:
- Without a fetcher, or with
cacheOnly: true,Orchestrator.getis oneEngine.get. - Otherwise a round,
Orchestrator.#round, runs in one synchronous step from reading the coverage to listing its new fetches, so two rounds never interleave, whichever tabs they serve. It reads the coverage one slot beyond the request at each end, so a miss at the edge can extend into it. planRoundtakes the request's slots that are neither covered nor blocked, joins the fetches in flight that meet them, and fetches only the rest.coalescemerges adjacent misses and extends a miss by one slot into coverage next to it.- A fetch in flight can be joined only while its cache generation (cleared count) and auth generation are current and no
invalidatehas fenced it. Orchestrator.#runpasses the fetcher copies of the range and a clone of the auth context. Once the fetcher settles, the outcome is decided in one step: a response that started before a clear of the cache is dropped, any other is applied byOrchestrator.#applyas a put with the fetched range as its authority, and the fetch leaves the in-flight list in that same step.Orchestrator.#roundsruns a second round only when the cache was cleared while the first waited, minus the ranges whose fetch failed or came back auth-pending; then it reads the engine once.annotaterelabels the misses those fetches leave as'fetch-failed'or'auth-pending'.Orchestrator.#refusedrecognises an expired credential withisAuthInvalidError, and only a failure under the current auth generation flipsAuthState, which broadcastsauthInvalidonce per flip. While auth is invalid, or whileupdateAuthis swapping credentials, a round fetches and joins nothing and its misses come back'auth-pending'at once.Orchestrator.updateAuthapplies updates one at a time: the fetcher'supdateAuthhook hears a clone of the new context, then the context and the auth generation switch together.Orchestrator.loadimports the fetcher module once per server, so once per SharedWorker, once an import has succeeded; a failed import leaves the slot free for the next connection to retry. A connection naming another module gets aConfigError; one bringing a context that is not the identical value goes throughupdateAuth, except a context thatsameMaterialfinds equal to the context the last refusal named (AuthState.wasRefused, checked when its turn comes and again after the hook), which changes nothing, whatever the auth state.
In the demo hub: Candles with weekend gaps: load an earlier fortnight; the page asks for the whole range and only what the cache does not cover is fetched: the older fortnight and the provisional slot at the right edge. Two tabs, one SharedWorker: expire the access token; one tab refreshes it, the others carry on, and the backend counts one refresh.
6. The engine
Read:
packages/tscache/src/engine/engine.ts#Engine.cachepackages/tscache/src/engine/engine.ts#STRUCTURALpackages/tscache/src/engine/engine.ts#Engine.clearAllpackages/tscache/src/engine/validate.ts#resolveCacheConfigpackages/tscache/src/engine/cache.ts#CacheState.putpackages/tscache/src/engine/cache.ts#CacheState.#putValidpackages/tscache/src/engine/cache.ts#CacheState.#applyVersionpackages/tscache/src/engine/cache.ts#CacheState.#setWatermarkpackages/tscache/src/engine/cache.ts#CacheState.hydratepackages/tscache/src/engine/batch.ts#validateBatchpackages/tscache/src/engine/read.ts#read
What to notice:
Engine.cacheis get-or-create. A second config for the same id must agree on every field inSTRUCTURAL, or it throwsConfigError; its version andfinalizedUntilare ignored.- The engine is synchronous and has no timers: every method runs to completion inside the call, and
Engine.clearAllempties every cache but keeps the caches and their configs. CacheState.putvalidates the whole batch before it changes anything (validateBatch: alignment, strictly ascending timestamps, field lengths, the put's range), copying the values into fresh arrays of the schema's dtypes.CacheState.#putValidthen runs in a fixed order: a differing version clears the cache (CacheState.#applyVersion); the points are written; the watermark advances; the put's claim, minus the provisional slots, is recorded as coverage; and only then is the version clear reported.CacheState.#setWatermarkwithdraws coverage from the new watermark slot on whenever the provisional region grows, so those points are fetched again.CacheState.hydratewrites a snapshot only into the parts of its coverage this cache neither covers nor holds as provisional, and refuses a snapshot of another dataset version.readreturns every present point in the request with the covered sub-ranges and the uncovered ones as'uncached'misses; this is where slots become milliseconds again.- Data model draws the state these calls change.
In the demo hub: Live server metrics and sparse events: the log shows one ten-minute fetch, then short fetches of the provisional tail only; Restate history makes the backend answer with a new dataset version, and the cache clears itself and fetches the window again.
7. Segments and coverage
Read:
packages/tscache/src/grid.ts#snapOutpackages/tscache/src/grid.ts#snapInpackages/tscache/src/engine/merge.ts#SegmentStore.putpackages/tscache/src/engine/merge.ts#SegmentStore.#togetherpackages/tscache/src/engine/merge.ts#SegmentStore.#carvepackages/tscache/src/segment/dense.ts#DenseSegmentpackages/tscache/src/segment/dense.ts#DenseSegment.mergeFrompackages/tscache/src/segment/types.ts#Segmentpackages/tscache/src/coverage.ts#CoverageIndex.addpackages/tscache/src/coverage.ts#CoverageIndex.subtractpackages/tscache/src/coverage.ts#CoverageIndex.gaps
What to notice:
grid.tsis the only module that converts between milliseconds and slots; everything below it does range arithmetic on integer slots. A read or an invalidation snaps outward (snapOut), a put's authority inward (snapIn).SegmentStore.putfirst removes the stored points inside the put's authority (SegmentStore.#carve), then writes the batch one write run at a time, in ascending slot order.SegmentStore.#togethercuts the batch into write runs (N70): consecutive batch points on the same page with at mostgapSplitKslots between them, counted on the batch alone. The layout rule is the file comment at the top ofmerge.ts: two present points share a segment when they lie on the same page and at mostgapSplitKslots between them hold no point.- A
DenseSegmentstores no timestamps: a slot's time follows from its position. It keeps one typed array per field and one presence bit per slot, so a point has all of its fields or none. DenseSegment.mergeFromwith an authority leaves exactly the given points inside it; without one it only adds or overwrites.CoverageIndex.addmerges overlapping and adjacent ranges;CoverageIndex.subtractmay split one range in two;CoverageIndex.gapsgives the uncovered sub-ranges that become a read's misses.
In the demo hub: Greenhouse sensor with dropouts: the three charts break at exactly the same places, because presence is per point. Live server metrics and sparse events, events page: zooming inside the loaded week asks the backend for nothing, because empty slots are covered, not missing.
8. Persistence
Read:
packages/tscache/src/persist/hosted.ts#HostedPersistencepackages/tscache/src/persist/clear-only.ts#ClearOnlyPersistencepackages/tscache/src/persist/persister.ts#Persisterpackages/tscache/src/persist/persister.ts#Persister.openpackages/tscache/src/persist/persister.ts#Persister.#planpackages/tscache/src/persist/persister.ts#Persister.#rejectedpackages/tscache/src/persist/persister.ts#durablypackages/tscache/src/persist/records.ts#PageRecordpackages/tscache/src/persist/idb-store.ts#openIdbStorepackages/tscache/src/engine/cache.ts#installRestore
What to notice:
persist/imports the engine; the engine imports nothing frompersist/. The persister reaches a cache's state through internal functions that no package entry exports, and installsrestore's implementation withinstallRestorewhen it is constructed.HostedPersistenceloadspersist/lazy.ts, the persister and the IndexedDB adapter, withimport()at the first persisted cache or the firstclearAll. Meanwhile the opens, the ops on a cache whose open waits, and, once one op waits, every later op andclearAllwait and reach the persister in arrival order; ops on other caches run at once. A chunk that fails to load, or does not load in time, turns persistence off for the worker's life.Persister.openloads a cache's records under one deadline (timeoutMs, default 5000 ms). Writes are behind, except removals, which request a flush at once: a flush is duedebounceMs(1000) after the latest change and no later thanmaxDelayMs(5000) after the first, and is planned from memory alone (Persister.#plan) without reading the disk.durablyholds an op's answer when the op, or another op meanwhile, recorded a removal: the op answers once the removal is durable or, after the cache's persistence has stopped, once the persister releases it (architecture §4.10.1; What can outlive a removal says what the answer guarantees after a stop).- A
QuotaExceededErrorstops the cache's persistence at once rather than retrying (Persister.#rejected); the stop reaches every tab aspersistStopped. openIdbStoreopens one database per origin,tscacheat version 1, with acachesand apagesobject store; aPageRecordholds a snapshot of one page's covered ranges.ClearOnlyPersistence, in the dedicated-worker and in-process hostings where IndexedDB exists, persists nothing; itsclearAllempties the database too.
In the demo hub: no scenario persists a cache. Every example app and reference client builds its worker with worker: { format: 'es' } (for instance examples/vanilla-uplot/vite.config.ts), so this chunk stays a file of its own, which a worker loads only at its first persisted cache or its first clearAll. Persistence shows how to turn it on.
9. The Vite plugin
Read:
packages/tscache/src/vite/fetcher-url.ts#fetcherUrlpackages/tscache/src/vite/fetcher-url.ts#IIFE_WARNINGpackages/tscache/src/vite/urls.ts#devUrlpackages/tscache/src/vite/urls.ts#serverFileUrl
What to notice:
- The worker loads the fetcher with
import()and needs its default export. Vite would bundle a?worker&urlimport without its exports, soimport url from "./fetcher.ts?fetcher"resolves instead to a module whose default export is the fetcher's URL. - In a build, the plugin's
loadhook emits the fetcher as a chunk of its own with its signature preserved (preserveSignature: 'strict'). In dev it serves the file from source: the browser gets an@fsURL under the base (devUrl), server code the file's absolute path. In a server build the URL is a file URL built at run time (serverFileUrl). generateBundlefails the build when the fetcher's chunk, or any chunk it reaches, contains Vite's module-preload helper, which needsdocumentandwindow, which a worker does not have.buildStartwarns once when a browser build makes workers as IIFE, which cannot split off the worker's persistence chunk; the plugin never changes the format.- The plugin imports nothing from Vite, not even its types: it declares the shapes of the context it uses.
In the demo hub: every example app and reference client lists fetcherUrl() in its vite.config.ts and imports its fetcher with ?fetcher; for instance Two tabs, one SharedWorker (examples/react-lwcharts/src/client.ts).