/** * Copyright (c) 2025 Elara AI Pty Ltd * Dual-licensed under AGPL-3.0 and commercial license. See LICENSE for details. */ import { type DatasetStatusInfo, type RequestOptions } from "@elaraai/e3-api-client"; import type { TreePath, DatasetStatus as PlatformDatasetStatus } from "@elaraai/e3-types"; /** * Timer abstraction the cache uses for periodic polling. Exists so * tests can drive the poll loop deterministically with a fake clock * instead of `setInterval` real-time. */ export interface Clock { /** Schedule `fn` to run every `ms` milliseconds. Returns a handle * whose `clear()` cancels future invocations. */ setInterval(fn: () => void, ms: number): { clear(): void; }; /** The time now, in milliseconds, by which the cache ages its last full * status answer; `Date.now()` when absent. */ now?(): number; } /** Default {@link Clock} backed by `globalThis.setInterval`. */ export declare const realClock: Clock; /** * Whether the page is hidden — its tab in the background, or its window * minimized — and when that changes: what the cache stops its polls on. * Exists so tests can hide and show a page deterministically; the default * reads the document. */ export interface Visibility { /** Whether the page is hidden */ readonly hidden: boolean; /** Calls `fn` whenever `hidden` changes. Returns what stops the calls. */ onChange(fn: () => void): () => void; } /** Default {@link Visibility}: the document's, and never hidden where there * is no document. */ export declare const documentVisibility: Visibility; /** The interval a workspace is polled at unless configured or asked * otherwise: every second while what the poll shows changes. */ export declare const DEFAULT_POLL_INTERVAL_MS = 1000; /** The longest a workspace's poll backs off to while nothing it shows * changes, unless configured or asked otherwise: 5 s. A watcher that asked * for a longer interval keeps it. */ export declare const DEFAULT_POLL_BACKOFF_MS = 5000; /** * How long a poll keeps asking conditionally — sending the tag of its last * full answer — before it asks for the status in full again: half a minute. * The tag names what the workspace stores, not the runner's view of an * execution recorded running, so a runner that died shows as stale within * this long. */ export declare const STATUS_UNCHANGED_MAX_MS = 30000; /** * Adapter the cache uses for every server round-trip. Exists so tests * (and any non-e3 host) can inject a synthetic implementation; the * default wraps the `@elaraai/e3-api-client` module-level functions. * * The cache passes its own `apiUrl` / `repo` / request options to the * adapter only via the {@link createDefaultDatasetApi} factory — the * adapter itself doesn't see those values, so tests don't need to * scaffold dummy URLs. */ export interface DatasetApi { /** Fetch a dataset's content. `hash` is the server's content hash * when it exposes one (`null` otherwise) — the cache records it so * the next status poll doesn't refetch content it already has. */ get(workspace: string, path: TreePath): Promise<{ data: Uint8Array; hash: string | null; }>; set(workspace: string, path: TreePath, value: Uint8Array): Promise; launchDataflow(workspace: string): Promise; listRoot(workspace: string): Promise; listAt(workspace: string, path: TreePath): Promise; /** * A workspace's status, for the datasets `paths` names: the answer holds * those of them the workspace has, each with its hash and status. Every * dataset when omitted. The cache's poll names what it watches. * * Asked conditionally, with the `etag` the last answer carried, it is * `null` when the status that answer gave is current. An answer carries * its tag when the server names one; the cache asks unconditionally * after an answer without one. */ workspaceStatus(workspace: string, paths?: readonly TreePath[], etag?: string): Promise<{ datasets: DatasetStatusInfo[]; etag?: string | null; } | null>; } /** * Build the default {@link DatasetApi} that talks to a real e3 server * via `@elaraai/e3-api-client`. Tests typically construct a * hand-rolled adapter instead. * * @param apiUrl - Base URL of the e3 API server * @param repo - Repository name * @param getOptions - Reads the current request options — the token, and the * `fetch` requests go through — so a rotated one is used at once * @returns The adapter */ export declare function createDefaultDatasetApi(apiUrl: string, repo: string, getOptions: () => RequestOptions): DatasetApi; /** * Configuration for the {@link ReactiveDatasetCache}. * * Strictly cache-internal — credentials and server identity (apiUrl, * repo, token) live in the {@link E3Config} context exposed by * ``. The cache talks to the server only via the injected * {@link DatasetApi} adapter, so it has no opinion on transport. * * @property workspace - The workspace this cache instance renders * against. Used by `Data.bind` to scope cache keys; consumed by * bind-runtime and the renderers via `getConfig().workspace`. */ export interface ReactiveDatasetCacheConfig { workspace?: string; /** * The interval a workspace is polled at while what the poll shows * changes, in milliseconds, unless a watch asks for a shorter one. * * @defaultValue 1000 */ pollIntervalMs?: number; /** * The longest a workspace's poll backs off to while nothing it shows * changes, in milliseconds, unless a watch asks for a shorter one. * * @defaultValue 5000 */ pollBackoffMs?: number; } /** * Interface for the ReactiveDatasetCache. */ export interface ReactiveDatasetCacheInterface { /** Read a cached dataset value synchronously */ read(workspace: string, path: TreePath): Uint8Array | undefined; /** Check if a dataset is cached */ has(workspace: string, path: TreePath): boolean; /** * Get the platform status of a dataset — `unset` | `stale` | `up-to-date`. * Returns `unset` if we don't know yet (status hasn't been polled). * `write()` flips the local entry to `stale` immediately (optimistic). * The next poll updates from the server's authoritative status. */ getStatus(workspace: string, path: TreePath): PlatformDatasetStatus; /** Write a dataset value (async - mutates remotely) */ write(workspace: string, path: TreePath, value: Uint8Array): Promise; /** * Write a dataset value AND launch a dataflow execution to propagate the * change to downstream tasks. Use when a single user action both mutates * input data and should trigger downstream recomputation (e.g. a Slider's * `onChangeEnd`). Use plain `write` for high-frequency optimistic updates * that you don't want to drive the dataflow on every tick. */ writeAndStart(workspace: string, path: TreePath, value: Uint8Array): Promise; /** * Launch a workspace dataflow run WITHOUT writing anything first, so * downstream tasks recompute against the current dataset state. This is the * standalone half of {@link writeAndStart} — use it after an out-of-band * mutation (e.g. a record commit) or to drive an explicit "Run" affordance. * Fire-and-await: resolves once the server accepts the request, not when * the dataflow finishes. */ launchDataflow(workspace: string): Promise; /** Preload a dataset into cache */ preload(workspace: string, path: TreePath): Promise; /** List fields at a path */ list(workspace: string, path: TreePath): Promise; /** * Poll a dataset, for one watcher. Each call is paired with one * {@link clearRefetchInterval}: a path two views watch stays polled until * both have cleared it. * * @remarks * The workspace's poll runs at the shortest interval its watchers asked * for while what it shows changes, backing off to the shortest backoff * they asked for once nothing has; a new watch, like the viewer's other * acts, brings it back to its interval. While the page is hidden nothing * is polled: shown again, the workspace is polled at once. * * @param workspace - The workspace * @param path - The dataset's path * @param intervalMs - The poll's interval while what it shows changes; * the cache's {@link ReactiveDatasetCacheConfig.pollIntervalMs} when * omitted * @param backoffMs - The longest the poll backs off to; the cache's * {@link ReactiveDatasetCacheConfig.pollBackoffMs} when omitted */ setRefetchInterval(workspace: string, path: TreePath, intervalMs?: number, backoffMs?: number): void; /** * Stop polling a dataset for one watcher registered with * {@link setRefetchInterval}. The path stops being polled once its last * watcher clears it, and the workspace's shared poller once its last path * goes — without this, a long-lived session accumulates watched paths (and * network traffic) forever. */ clearRefetchInterval(workspace: string, path: TreePath): void; /** * Follow a dataset's content hash without fetching its content — what a * paged source follows its dataset by. * * @remarks * The path joins its workspace's status poll, started at `intervalMs` when * nothing else polls the workspace. `onHash` is called with the hash a * poll reports whenever it differs from the one this watch holds — the * last it was told, or the one its watcher last said it holds * ({@link hashHeld}) — (`null` while the dataset has no value), the first * poll after the watch starts included. The dataset's content is never * fetched. * * @param workspace - The workspace * @param path - The dataset's path * @param onHash - Called with each new hash * @param intervalMs - The poll's interval, when this watch starts it or * asks for a shorter one: the poll backs off from it while nothing * changes, as every poll does; the cache's * {@link ReactiveDatasetCacheConfig.pollIntervalMs} when omitted * @param backoffMs - The longest the poll backs off to, when this watch * asks for a shorter one; the cache's * {@link ReactiveDatasetCacheConfig.pollBackoffMs} when omitted * @returns A function that stops the watch; the poller stops once nothing * watches the workspace */ watchHash(workspace: string, path: TreePath, onHash: (hash: string | null) => void, intervalMs?: number, backoffMs?: number): () => void; /** * A watcher of a dataset's hash says which hash it holds now, by evidence * of its own: a write's answer naming the state it committed, a read * refused that names the dataset's state. The watch is told of the * dataset's hash where it differs from that one, by the first poll * started from here on — a poll in flight may have read before the * evidence, and says nothing to this watcher — which is asked in full, * and soon. Without it the watch compares each poll's hash with the last * it told: a watcher put at a state the dataset has since left, where the * dataset's hash is the one last told, would hear nothing more, and hold * that state until the dataset next changed. * * @param workspace - The workspace * @param path - The dataset's path * @param onHash - The watcher, as {@link watchHash} was given it * @param hash - The hash it holds now, `null` for no value */ hashHeld(workspace: string, path: TreePath, onHash: (hash: string | null) => void, hash: string | null): void; /** * Force one immediate workspace-status poll, reconciling every watched * path's content against the server (hash-gated; only changed datasets * refetch). Use after an out-of-band server mutation (e.g. a record * mutation commit) so a watched dataset picks up the new bytes without * waiting for the standing poll interval. A poll already in flight may * have read the status before the mutation, so the refresh polls again * once it settles. The poll goes back to its interval, as for any act of * the viewer's. No-op if the workspace has no active poller. * Fire-and-forget; resolves when the refresh's poll settles. */ refresh(workspace: string): Promise; /** * A mark of a workspace's status polls as they stand now: a poll started * after it reads the workspace's status after it. * * @remarks * With {@link confirmedSince}, what says that the content the cache holds * of a dataset is the dataset's own as of a read made since some moment — * since a record's commit was answered, say, which the content then holds. * A hash alone cannot say so: it names content, and a dataset put back as * it was is under the hash it had before. * * @param workspace - The workspace * @returns The mark */ pollMark(workspace: string): number; /** * Whether a status poll started since a mark has found the content the * cache holds of a dataset to be the dataset's: fetched by that poll, or * held already under the hash it read. * * @param workspace - The workspace * @param path - The dataset's path, one whose content the cache polls * @param mark - A mark {@link pollMark} gave * @returns Whether one has */ confirmedSince(workspace: string, path: TreePath, mark: number): boolean; /** * The moment a status poll started since a mark finds the content the * cache holds of a dataset to be the dataset's ({@link confirmedSince}). * A dataset put back as it was is found so with no change to tell anyone * of, so whoever waits on one is told here. * * @param workspace - The workspace * @param path - The dataset's path * @param mark - A mark {@link pollMark} gave * @returns A promise settled at that moment — at once, where a poll has * found it so already; `undefined` for a dataset whose content no poll * of the cache reconciles: one never watched, or held only as it was * written here */ confirmed(workspace: string, path: TreePath, mark: number): Promise | undefined; /** * Whether a status poll started since a mark has read the hash of a * dataset whose hash the cache follows ({@link watchHash}), every watcher * of it holding that hash from then: told it, or holding it already. What * says that the revision a paged source is pinned to is the dataset's as * of a read made since some moment — a record's commit being answered — * as {@link confirmedSince} says it of content. * * @param workspace - The workspace * @param path - The dataset's path * @param mark - A mark {@link pollMark} gave * @returns Whether one has */ hashReadSince(workspace: string, path: TreePath, mark: number): boolean; /** * The moment a status poll started since a mark has read the hash of a * dataset whose hash the cache follows ({@link hashReadSince}). A dataset * whose hash is as its watchers hold it is read so with nothing to tell * them, so whoever waits on one is told here. * * @param workspace - The workspace * @param path - The dataset's path * @param mark - A mark {@link pollMark} gave * @returns A promise settled at that moment — at once, where a poll has * read it so already; `undefined` for a dataset whose hash no watch follows */ hashRead(workspace: string, path: TreePath, mark: number): Promise | undefined; /** Subscribe to changes on a specific key */ subscribe(key: string, callback: () => void): () => void; /** Subscribe to all changes */ subscribe(callback: () => void): () => void; /** Get global snapshot version */ getSnapshot(): number; /** Get version for a specific key */ getKeyVersion(key: string): number; /** Set notification scheduler */ setScheduler(scheduler: ((notify: () => void) => void) | undefined): void; /** Batch multiple operations */ batch(fn: () => T): T; /** Get the configuration */ getConfig(): ReactiveDatasetCacheConfig; /** Clean up resources */ destroy(): void; } /** * Convert a dataset path to a string key for caching. * * @remarks * Dot-joined to match the server's own path encoding (workspaceStatus * reports `.a.b` paths) — field names containing `.` are ambiguous at * the e3 wire level itself, so the cache doesn't try to out-encode it. */ export declare function datasetPathToString(path: TreePath): string; /** * Create a cache key from workspace and path. */ export declare function datasetCacheKey(workspace: string, path: TreePath): string; /** * ReactiveDatasetCache manages dataset caching and reactivity. * * @remarks * Content bytes live in a `@tanstack/query-core` {@link QueryClient} * (structured query keys, fetch dedup + cancellation); statuses, content * hashes, write pipelines, the workspace-status poll loop, and the * string-keyed subscription shim are cache-owned. See the module remarks * for the write/poll race rules. * * This differs from raw `@elaraai/e3-api-client` dataset functions which * are for direct API calls without reactive binding or caching. */ export declare class ReactiveDatasetCache implements ReactiveDatasetCacheInterface { private destroyed; private api; private config; private readonly client; private knownHashes; private statuses; private writeEpochs; private writeChains; private writeBaselines; private pendingWriteCounts; private keySubscribers; private globalSubscribers; private version; private keyVersions; private workspacePollers; private readonly clock; private readonly visibility; /** Whether the page is hidden, as last seen: no workspace is polled while it is */ private hidden; /** Stops the watch on the page's visibility */ private readonly unwatchVisibility; private inFlightPolls; /** * How many refreshes each workspace has been asked for: a poll in flight as one is asked for was overtaken by it — * it may have read the status before what the refresh was asked for — and tells no hash watch what it read * ({@link ReactiveDatasetCache.refresh}). */ private refreshesAsked; /** How many status polls each workspace has started: what {@link ReactiveDatasetCache.pollMark} gives. */ private pollsStarted; /** The last poll, by its number among its workspace's, that found each key's held content to be its dataset's. */ private confirmedAt; /** Who waits to hear a key's content found its dataset's by a poll started since a mark ({@link ReactiveDatasetCache.confirmed}). */ private confirmWaits; /** The last poll, by its number among its workspace's, that read each watched key's hash, its watchers holding that hash from then. */ private hashReadAt; /** Who waits to hear a watched key's hash read by a poll started since a mark ({@link ReactiveDatasetCache.hashRead}). */ private hashReadWaits; private hashWatches; private batchDepth; private changedKeys; private scheduler; private flushScheduled; /** * @param config - The cache's configuration: its workspace, and the * intervals its polls run at * @param api - What every server round-trip goes through * @param clock - What the polls are timed by; the real clock unless given * @param visibility - Whether the page is hidden, on which the polls * stop; the document's unless given */ constructor(config: ReactiveDatasetCacheConfig, api: DatasetApi, clock?: Clock, visibility?: Visibility); /** Structured query key for a dataset's content. */ private contentKey; /** * Read the cache's own configuration. Server identity (apiUrl, * repo, token) is NOT here — read it from `` via * `useE3Config()` instead. */ getConfig(): ReactiveDatasetCacheConfig; /** The interval a workspace is polled at unless a watch asks for a shorter one. */ private get pollIntervalMs(); /** The longest a workspace's poll backs off to unless a watch asks for a shorter one. */ private get pollBackoffMs(); /** The time now, by the cache's clock. */ private now; /** * Read a dataset value synchronously from cache. */ read(workspace: string, path: TreePath): Uint8Array | undefined; /** * Check if a dataset is cached. */ has(workspace: string, path: TreePath): boolean; /** * Get the platform status of a dataset. Defaults to `unset` until the * first poll returns a server status. */ getStatus(workspace: string, path: TreePath): PlatformDatasetStatus; /** * Write a dataset value (async - mutates remotely). * * @remarks * Optimistic and synchronous: the bytes are readable via {@link read} * before this method's first await. Concurrent writes to the same key * are serialized server-side (issue order preserved); on failure, only * the newest write rolls the key back — to the last server-confirmed * baseline, not to a possibly-superseded optimistic intermediate. */ write(workspace: string, path: TreePath, value: Uint8Array): Promise; /** * Write a dataset value AND launch a workspace dataflow run so downstream * tasks pick up the change. The launch is fire-and-await: it returns once * the server has accepted the request (not when the dataflow finishes). * Polling continues to surface live status as tasks complete. */ writeAndStart(workspace: string, path: TreePath, value: Uint8Array): Promise; /** * Launch a workspace dataflow run without writing first. The standalone * half of {@link writeAndStart}; see the interface doc for semantics. */ launchDataflow(workspace: string): Promise; /** * Preload a dataset into cache. Concurrent preloads of the same key * share one fetch (query-core dedup); a write racing the fetch cancels * it, so a preload can never clobber optimistic bytes. */ preload(workspace: string, path: TreePath): Promise; /** * List fields at a path. Empty path lists workspace root. */ list(workspace: string, path: TreePath): Promise; /** * Set refetch interval for a dataset (polling). * * @remarks * Uses hash-based change detection for efficiency: * 1. Polls workspaceStatus to get dataset hashes (lightweight) * 2. Compares hashes to detect changes * 3. Only fetches full content when hash changes * * Multiple subscriptions to the same workspace share a single poller, * at the shortest interval any asked for, which backs off while nothing * it shows changes; a new watch brings it back to that interval. * Pair each call with one {@link clearRefetchInterval} on unmount so the * poller can stop when nothing is watching. */ setRefetchInterval(workspace: string, path: TreePath, intervalMs?: number, backoffMs?: number): void; /** * Starts a workspace's poller: its timer, unless the page is hidden, and * an immediate poll. The poll's promise is floated — the dedup map * handles concurrency, and errors are logged. */ private startPoller; /** * Stops every workspace's timer as the page is hidden, keeping what each * poller watches; and as it is shown, polls every workspace at once and * at its interval again. */ private onVisibilityChange; /** * Stop polling a dataset for one watcher; the path goes when its last * watcher clears it, and the workspace poller is torn down when its last * path goes. */ clearRefetchInterval(workspace: string, path: TreePath): void; /** * Follow a dataset's content hash without fetching its content; see the * interface doc. */ watchHash(workspace: string, path: TreePath, onHash: (hash: string | null) => void, intervalMs?: number, backoffMs?: number): () => void; hashHeld(workspace: string, path: TreePath, onHash: (hash: string | null) => void, hash: string | null): void; /** Stops a workspace's poller once it has no path to reconcile and no hash * to follow — without this, a long-lived session polls forever. */ private stopIdlePoller; /** Runs a workspace's poll every `ms` from now, restarting its timer when * that is another interval than it runs at; no timer runs while the * page is hidden. */ private pollEvery; /** Brings a workspace's poll back to the interval its watchers asked for: * what it shows changed, or the viewer acted. */ private pollSoon; /** Backs a workspace's poll off once it saw nothing change: its interval * doubles, to at most the poller's backoff, and never below the interval * asked for. */ private backOff; refresh(workspace: string): Promise; pollMark(workspace: string): number; confirmedSince(workspace: string, path: TreePath, mark: number): boolean; confirmed(workspace: string, path: TreePath, mark: number): Promise | undefined; /** * Records that a poll found the content held of a key to be its dataset's, * and tells whoever waited for one started since their mark. * * @param key - The dataset's key * @param poll - The poll, by its number among its workspace's */ private confirm; hashReadSince(workspace: string, path: TreePath, mark: number): boolean; hashRead(workspace: string, path: TreePath, mark: number): Promise | undefined; /** * Records that a poll read a watched key's hash, every watcher of it holding that hash from then, and tells * whoever waited for one started since their mark. * * @param key - The dataset's key * @param poll - The poll, by its number among its workspace's */ private readHash; /** Tells those waiting on a key for a poll started since their mark, and keeps the rest. */ private static settleWaits; /** * Poll workspace status and reconcile the cache with the server. * Concurrent calls for the same workspace dedupe to a single fetch. */ private pollWorkspaceStatus; private doPollWorkspaceStatus; /** * Convert a path string back to TreePath. */ private stringToPath; /** * Subscribe to changes on a specific key or all changes. */ subscribe(callback: () => void): () => void; subscribe(key: string, callback: () => void): () => void; /** * Get global version for useSyncExternalStore. */ getSnapshot(): number; /** * Get version for a specific key. */ getKeyVersion(key: string): number; /** * Set scheduler for deferred notifications. */ setScheduler(scheduler: ((notify: () => void) => void) | undefined): void; /** * Batch multiple operations. */ batch(fn: () => T): T; /** * Notify subscribers of a change. */ private notifyChange; /** * Flush pending notifications. */ private flush; private doFlush; /** * Cleanup resources. After `destroy()` returns, in-flight fetches, * polls, and writes that are still mid-await won't write to the cache — * `this.destroyed` short-circuits their post-await branches, and the * query client's in-flight fetches are torn down with it. */ destroy(): void; } /** * Create a new {@link ReactiveDatasetCache}. The caller is responsible * for constructing a {@link DatasetApi} adapter; in a React tree the * `` builds one from the surrounding * ``. Tests inject a fake `clock` to drive polling * deterministically, and a `visibility` to hide and show the page. * * @param config - The cache's configuration: its workspace, and the * intervals its polls run at * @param api - What every server round-trip goes through * @param clock - What the polls are timed by; the real clock unless given * @param visibility - Whether the page is hidden; the document's unless given * @returns The cache */ export declare function createReactiveDatasetCache(config: ReactiveDatasetCacheConfig, api: DatasetApi, clock?: Clock, visibility?: Visibility): ReactiveDatasetCache; //# sourceMappingURL=dataset-store.d.ts.map