import { CID } from 'multiformats'; import type { BlockStoreish } from '@wovin/core/ipfs'; import { SignedDelegation } from './types.ts'; export interface CarMirrorBlock { cid: CID; bytes: Uint8Array; } /** * Minimal blockstore interface for pull operations. * Compatible with IDBBlockstore and standard Blockstore interfaces. */ export interface BlockStoreForPull { has(key: CID): Promise; get(key: CID): Promise; put(key: CID, val: Uint8Array): Promise; /** * Optional bulk write, one transaction for many blocks instead of one * transaction per `put()` call. On a cold pull of a large thread, per-block * `put()` (e.g. IDBBlockstore's default, which opens a fresh IndexedDB * transaction per call) dominates total pull time — measured at ~95% of a * ~294s round for ~94K blocks (~280s in `put()` alone vs ~9s combined for * hash verification + link extraction + network). `carMirrorPull` buffers * blocks and calls this every `PUT_BATCH_SIZE` blocks (and once more at * round end) when the caller provides it, falling back to sequential * `put()` otherwise — see note3's `putManyBlocks` for the same pattern * already used on the gateway-fetch write path. */ putMany?(pairs: { cid: CID; bytes: Uint8Array; }[]): Promise; } export interface CarMirrorOptions { signal?: AbortSignal; delegation?: SignedDelegation; maxRounds?: number; headers?: Record; /** * Maximum bytes per CAR round (default 30MB, just under the proxy's 32MB * receive_maximum). Push auto-falls-back to 1.9MB rounds against old servers. */ sendMaximum?: number; /** Live progress callback, invoked each round and on completion. See CarMirrorProgress. */ onProgress?: (progress: CarMirrorProgress) => void; /** * The root CID of the last snapshot the *receiving* side is known to already have * completely (wovin invariant: having a snapshot root implies having its whole DAG). * Typically the previous successful push's `rootCid` (push) or the subscription's * `lastCID` (pull) for this same DAG/thread — NOT the current operation's own root. * * Push: seeds the send walk's skip-root set with it, so the walk prunes at that * snapshot's subtree instead of descending the entire `prev` chain on every push. * The server's own advertised skip roots (PushResponse.ss — its pinned history) * extend the set from round 2 on. * * Pull: seeds the local have-set with it (if the block is present locally), so the * want-discovery walk stops at the boundary instead of re-walking the entire local * history — and asserts it on the wire (PullRequest.ss), so the SERVER prunes its * send walk below it too: round 1 of a new snapshot transfers only the delta * instead of the whole shared history. * * Self-healing if stale or wrong: explicitly requested subgraph roots always * bypass both the bloom and skip claims (on either side), so a stale boundary * costs extra round-trips, never incorrect data. Omit if there is no known * prior sync. */ prevBoundary?: CID; /** * Pull only. Cross-call memoization for the local-store walk — see * `DagLinkCache`. Pass the SAME instance across every pull done by a given * worker/session (create one with `createDagLinkCache()` at that scope) so * re-pulling an already-partially-or-fully-synced thread (e.g. reopening a * preview) doesn't re-walk blocks already proven present. Omit for a * one-shot pull with no benefit from memoization. */ dagLinkCache?: DagLinkCache; } /** * Live progress for a car-mirror pull or push, emitted each round + on completion. * * Note: car-mirror discovers the DAG as it walks, so `frontier` (the count of blocks * still wanted for a pull) is a moving frontier — NOT a known total. There is no * reliable "percent complete" until the final round; prefer showing live counts, * throughput and round number over a fake progress ratio. */ export interface CarMirrorProgress { direction: 'pull' | 'push'; /** 'round-start' before a request, 'round-done' after blocks are processed, 'complete' when finished */ phase: 'round-start' | 'round-done' | 'complete'; /** 1-based round number */ round: number; maxRounds: number; /** cumulative blocks transferred (received for pull / sent for push) */ blocks: number; /** blocks transferred in the most recent round */ blocksThisRound: number; /** cumulative CAR bytes transferred over the wire */ bytes: number; /** CAR bytes in the most recent round */ bytesThisRound: number; /** remaining frontier: wanted blocks (pull) or subgraph roots the server still needs (push) */ frontier: number; /** bloom filter size in bytes for the current round (0 if none) */ bloomBytes: number; /** bloom hash count k for the current round (0 if none) */ bloomK: number; /** HTTP round-trips issued so far */ requests: number; } export declare class BloomFilter { readonly bytes: Uint8Array; readonly hashCount: number; readonly bitSize: number; private xxh3; private constructor(); /** * Create a bloom filter sized for `itemCount` items with the car-mirror FPR formula. */ static create(itemCount: number): Promise; /** * Reconstruct a bloom filter from wire data. */ static fromWire(hashCount: number, bytes: Uint8Array): Promise; /** * Insert an item (raw CID bytes). */ insert(item: Uint8Array): Promise; /** * Check if an item is (probably) in the set. */ has(item: Uint8Array): Promise; /** * Compute hash indices using xxh3_64 with sequential seeds + rejection sampling. */ private hashIndices; toWire(): { bk: number; bb: Uint8Array; }; } /** * Memoizes "children of a confirmed-present block" across repeated calls to * `IncrementalDagVerification` (separate rounds, separate `carMirrorPull` * invocations, e.g. re-previewing the same thread within one tab session). * * Why this is sound as a *permanent* cache: blocks are immutable and * content-addressed, so "block X is present locally and links to * [Y, Z]" is a fact that, once true, never becomes false or needs * invalidation — the store only ever gains blocks, never mutates or (today) * garbage-collects them. Only *presence* is memoized, never *absence*: a * block that's missing now may be pulled a moment later, so cache misses * always re-check the real store rather than caching a negative result. * * Deliberately just a link-adjacency cache, not a "this whole subtree is * complete" cache: the existing BFS walk in `updateHaveCids` already dedupes * per-call via its own `visited` set, so a subtree-completeness cache would * duplicate that bookkeeping for no extra benefit while adding real * complexity (recursion/post-order marking). Caching just the links lets a * warm walk skip the IndexedDB `get()` + block-parse for every previously-seen * CID — the dominant cost — while staying a simple flat Map. * * Share one instance across every pull done by the same worker/session (see * callers) so e.g. re-opening a preview you already partially or fully synced * doesn't re-walk blocks already proven present. */ export declare class DagLinkCache { private links; get(cidStr: string): string[] | undefined; set(cidStr: string, childrenCidStrs: string[]): void; } export declare function createDagLinkCache(): DagLinkCache; /** * Push a DAG to a car-mirror server using multi-round bloom-filtered sync. * * Lazily walks the DAG from the blockStore each round, skipping blocks * the server already has (via bloom filter from previous round's response). * * @param baseUrl - Base URL of the car-mirror endpoint (e.g. "https://store.example.com") * @param rootCid - Root CID of the DAG to push * @param blockStore - Block store to lazily fetch blocks from * @param opts - Options (signal, delegation, maxRounds, headers, sendMaximum) */ export declare function carMirrorPush(baseUrl: string, rootCid: CID, blockStore: BlockStoreish, opts?: CarMirrorOptions): Promise; /** * Pull a DAG from a car-mirror server using multi-round bloom-filtered sync. * * Incrementally verifies and stores blocks into the provided blockStore. * Uses IncrementalDagVerification to track which blocks we have/want, * sending bloom-filtered PullRequests with frontier CIDs each round. * * @param baseUrl - Base URL of the car-mirror endpoint * @param rootCid - Root CID of the DAG to pull * @param blockStore - Block store to verify against and store received blocks into * @param opts - Options (signal, delegation, maxRounds, headers) */ export declare function carMirrorPull(baseUrl: string, rootCid: CID, blockStore: BlockStoreForPull, opts?: CarMirrorOptions): Promise; /** * Quick check whether the server has the DAG for a given root CID. * * Sends a single pull round to check if the server can serve blocks for this root. * Relies on the application invariant that if the server has a root CID, * it has the complete DAG. This is NOT a general car-mirror protocol guarantee. */ export declare function carMirrorHasCid(baseUrl: string, rootCid: CID, opts?: CarMirrorOptions): Promise; //# sourceMappingURL=car-mirror.d.ts.map