import { type Doc, type Heads } from '@automerge/automerge'; import { type AnyDocumentId, type DocumentId, type PeerId } from '@automerge/automerge-repo'; import { type Subduction } from '@automerge/automerge-subduction'; import * as Effect from 'effect/Effect'; import * as SqlClient from 'effect/sql/SqlClient'; import type * as SqlError from 'effect/sql/SqlError'; import { Event } from '@dxos/async'; import { Context, Resource } from '@dxos/context'; import { type CollectionId } from '@dxos/echo-protocol'; import * as RuntimeProvider from '@dxos/effect/RuntimeProvider'; import { PublicKey, type SpaceId } from '@dxos/keys'; import { type DataService } from '@dxos/protocols/rpc'; import { type CollectionState } from './collection-synchronizer.ts'; import { type DocumentLease } from './document-lease.ts'; import { type EchoDataMonitor } from './echo-data-monitor.ts'; import { type AutomergeReplicator } from './echo-replicator.ts'; import { type DocumentSize, type QuarantineReason, type QuarantineRecord } from './quarantine.ts'; import { SqliteStorageAdapter } from './sqlite-storage-adapter.ts'; export type PeerIdProvider = () => string | undefined; export type RootDocumentSpaceKeyProvider = (documentId: string) => PublicKey | undefined; export type AutomergeHostProps = { runtime: RuntimeProvider.RuntimeProvider; dataMonitor?: EchoDataMonitor; /** * Used for creating stable ids. A random key is generated on open, if no value is provided. */ peerIdProvider?: PeerIdProvider; getSpaceKeyByRootDocumentId?: RootDocumentSpaceKeyProvider; /** * Enable Subduction sedimentree transport. * * When `false` (default), the host wires {@link EchoNetworkAdapter} as a classical * automerge-repo network adapter and skips all Subduction-specific initialization * (WASM init, signer generation, subduction policy / adapters). When `true`, the * host runs Subduction as the document byte transport. */ useSubduction?: boolean; /** * Residency policy for loaded documents. The default evicts a released document after * {@link EVICT_IDLE_DELAY} and keeps no floor; a host whose invocations are shorter than the delay * (a Worker) should set its own. */ residency?: { /** How long a document stays resident after its last lease is disposed. */ evictionDelay?: number; /** How many released documents stay resident regardless of age. */ minResidentDocuments?: number; /** How many released documents may wait out the delay before the oldest are evicted at once. */ maxIdleDocuments?: number; }; }; export type LoadDocOptions = { timeout?: number; /** Internal: set on the one retry `_loadLeasedDoc` takes after an eviction raced its wait. */ retried?: boolean; /** * Controls whether `loadDoc` is allowed to wait on the network. * * - `true` / unset (default): announce that we want the doc and wait * until any source (storage OR network) delivers it. * - `false`: probe local storage only. If chunks for the doc exist * on disk, wait for storage to populate the handle; otherwise * throw `'unavailable'` immediately without ever consulting the * network. Note that this does not guarantee that the document * will not be fetched from the network — an inbound peer announce * can still deliver bytes — but the host will never request it. */ fetchFromNetwork?: boolean; }; export type CreateDocOptions = { /** * Import the document together with its history. */ preserveHistory?: boolean; documentId?: DocumentId; }; /** * Abstracts over the AutomergeRepo. * * Runs Subduction as the document byte transport ({@link Repo.subductionAdapters}), while * the DXOS-specific {@link CollectionSynchronizer} rides on the same {@link EchoNetworkAdapter} * via `sync-request` / `sync-state` control messages that are intercepted at the adapter * level and never reach the Subduction sedimentree layer. */ export declare class AutomergeHost extends Resource { #private; private readonly _runtime; private readonly _echoNetworkAdapter; private readonly _collectionSynchronizer; private _repo; /** Changes confirmed while resident, so an evicted document answers without a load; forgetting costs one load. */ private readonly _confirmedChanges; private _storage; private readonly _headsStore; /** Fired when a document is quarantined, so waits on it end and the space that links it can retire it. */ readonly documentQuarantined: Event; /** Fired for every document loaded from disk, with its size, so the space can retire one whose history bloated. */ readonly documentLoaded: Event<{ documentId: DocumentId; } & DocumentSize>; private _syncTask; /** * Cache of collections that would be synced on next sync task run. */ private readonly _collectionsToSync; private _peerId; private readonly _peerIdProvider?; private readonly _getSpaceKeyByRootDocumentId?; readonly collectionStateUpdated: Event<{ collectionId: CollectionId; }>; /** * Fired after a batch of documents was saved to disk. */ readonly documentsSaved: Event; /** Fired per document whose heads a save advanced — what a reader of that document must catch up on. */ readonly documentHeadsChanged: Event<{ documentId: DocumentId; heads: Heads; }>; private readonly _headsUpdates; private _onHeadsChangedTask?; /** * Documents created in this session. */ private _createdDocuments; /** * Documents that need to be synced based on the result of collection-sync. */ private _documentsToSync; /** * Documents that are not available locally that should be requested. */ private _documentsToRequest; /** * Consecutive non-converging collection-sync passes, keyed by `:` — a pair * making no progress is otherwise indistinguishable from idle polling in the logs. */ private _nonConvergingSyncPasses; /** * The heads each classical sync peer last reported for a document, kept across evictions. Evicting a document drops * the sync round that would deliver its latest change, so one stays resident until every connected peer that synced * it holds its heads. */ private readonly _peerHeads; /** * Heads a diverged document was last re-synced at, keyed by `::`. * * {@link resyncDocument} re-arms the Subduction heal loop, which then retries with its own * backoff — so one call per observed head pair is the whole retry budget, and calling it again * on the next diff pass would reset that backoff to zero and pin it there. Keyed by the heads * rather than a plain "already tried" flag so that a genuine change on either side (the peer * advanced, or we committed again) re-opens the retry. An evicted document spends it on the load that * faults it in. * * The map key is only for lookup: collection and peer ids both contain `:`, so no joined string is * unambiguous, and cleanup compares the ids stored on each entry instead. */ private _divergedResyncHeads; /** Earliest time the repo-wide share-policy kick may fan out again. See {@link SHARE_POLICY_KICK_MS_PER_DOCUMENT}. */ private _sharePolicyKickNextAllowedAt; /** Whether a trailing share-policy kick is parked at {@link _sharePolicyKickNextAllowedAt}. */ private _sharePolicyKickParked; /** * Documents requested by remote peers. */ private _documentsRequested; /** * Reference counts the documents held loaded. The repo caches a document forever once anything * faults it in, so residency is decided here instead — see {@link DocumentLeaseRegistry}. */ private readonly _leases; /** * Leases held for documents being replicated after a collection-sync diff, released when the * document settles: the trigger is fire-and-forget, so nothing else holds the document while its * bytes are in flight. */ private readonly _replicationLeases; private _sharePolicyChangedTask?; private _signer; private readonly _useSubduction; /** Subduction Ed25519 PeerId hex → automerge-repo PeerId, populated from `subduction-peer-bound`. */ private readonly _subductionPeerIdHexToRepoPeerId; constructor({ runtime, dataMonitor, peerIdProvider, getSpaceKeyByRootDocumentId, useSubduction, residency, }: AutomergeHostProps); protected _open(ctx: Context): Promise; protected _close(ctx: Context): Promise; /** * Runs the data migrations in `./subduction-migrations` over the stored Subduction records, then * repairs the self-checkpointed fragments stored since the last open. Contained: a failed * migration is logged and the host opens on the records as stored, since every migration is a * repair of data the host can already read. * * The repair runs on every open, not once: a peer forwards a fragment with the signature it * received it with and clients on `@automerge/automerge` < 3.5 still write the shape, so one * kept as received would be uploaded to the next empty EDGE store and hide the document's head. */ private _runSubductionMigrations; /** * Creates automerge_chunks and automerge_heads tables if they do not exist. * Must be called (via RuntimeProvider.runPromise) before opening the host. */ get migrate(): Effect.Effect; get peerId(): PeerId; get loadedDocsCount(): number; /** Ids of the documents resident in the repo cache — ids only, so no caller can bypass a lease. */ get loadedDocumentIds(): DocumentId[]; /** * Cached handles owned by one space — residency, not the space's document count. * * Counted by testing the space's collection state (which survives handle eviction, and is the * same mapping `getContainingSpaceIdForDocument` trusts first) against the repo's cache, rather * than by asking each cached handle which space it belongs to: that lookup can await a load, and * a stats call must not fault documents in. */ loadedDocsCountForSpace(spaceId: SpaceId): number; /** The Repo's Subduction engine, for storage-level inspection (tests, devtools). */ get subduction(): Promise; get storage(): SqliteStorageAdapter; addReplicator(ctx: Context, replicator: AutomergeReplicator): Promise; removeReplicator(replicator: AutomergeReplicator): Promise; /** * automerge-repo's `findWithProgress` does not re-issue a parked DocumentQuery; repo-wide, * `shareConfigChanged` clears `all-failed` entries and the heal backoff, then re-syncs. */ kickStalledSync(): void; /** * Re-drives one document's Subduction sync round, re-arming its heal loop. * * {@link kickStalledSync} only revives `all-failed`/`no-peers` entries, so it cannot move a * sedimentree Subduction already considers settled — which is the state a document sits in when * its heads stay behind the sync server with no round in flight. */ resyncDocument(documentId: DocumentId): void; /** * Leases a document, waiting until it is loaded. The lease is the only route to a `DocHandle`; * dispose it (`using`, or in the holder's teardown) so the document can be evicted. * * Returns null when `fetchFromNetwork: false` and the document is not on disk, and when the document is * quarantined — including one quarantined while this call waits on it. */ loadDoc(ctx: Context, documentId: AnyDocumentId, opts?: LoadDocOptions): Promise | null>; /** * Leases a document without waiting for it to load — the lease's query carries the readiness * state. Faults the document in, so a caller that only wants to know whether it is already * resident must not use this. */ acquireDoc(documentId: AnyDocumentId): DocumentLease; /** Whether the host refuses to load the document; see {@link quarantineDocument}. */ isQuarantined(documentId: AnyDocumentId): boolean; /** Documents the host refuses to load, with why. */ get quarantinedDocuments(): ReadonlyMap; /** * Stops loading, replicating and serving a document for the life of this host: one that cannot be loaded would * otherwise stall the start that reaches it. Waits on it resolve as unavailable. Its bytes stay on disk until * {@link removeDocument}. */ quarantineDocument(documentId: DocumentId, { reason, error }: { reason: QuarantineReason; error?: unknown; }): Promise; /** Documents currently leased — what the host holds because something is using it. */ get leasedDocsCount(): number; /** Settles pending evictions, for a caller measuring residency. */ drainEvictions(): Promise; /** * Drops a document from the repo cache, draining its pending save so it cannot re-persist. * Resolves `false` when the document was left resident, so the registry retries it later. */ private _evictDocument; /** Whether a connected peer that synced the document last reported heads other than ours. */ private _hasPeerBehind; private _loadLeasedDoc; /** * Resolve on `'ready'`, reject on `'failed'`, treat `'unavailable'` as transient; caller bounds via * `opts.timeout` / `ctx`. * * `signal` unsubscribes an abandoned wait: a bounded caller stops awaiting but the query lives on, * so without it a document that never settles gains a subscriber per attempt. */ private _waitForReady; exportDoc(id: AnyDocumentId): Promise; /** * The document's saved changes as storage holds them, without loading the document: its snapshot and * incremental chunks, concatenated in the form `A.loadIncremental` reads. Undefined when storage holds * none, or more than `limit` bytes. */ readStoredChanges(id: DocumentId, { limit }?: { limit?: number; }): Promise; /** * Probe local storage to determine whether the document has any persisted * chunks. Does not request the document from the network and does not * touch the in-memory `Repo`. Returns `true` iff at least one non-empty * chunk exists on disk for the document. * * Intended for query-driven (disk-only) loads that need to know quickly * whether a document is locally available without waiting on network * latency. See `DocumentsSynchronizer.addDocuments` and the `requesting` * transition in `DocHandleProxy`. */ hasDocOnDisk(id: AnyDocumentId): Promise; /** * Wipe a document from local storage: its automerge chunks and its heads-store row (both, or the * heads row is orphaned). Used by garbage collection for documents that are no longer reachable * from any space directory. */ removeDocument(id: AnyDocumentId): Promise; /** * Create new persisted document. */ createDoc(initialValue?: T | Doc | Uint8Array, opts?: CreateDocOptions): Promise>; /** Leases a freshly created document and announces it, so the creator holds it until it lets go. */ private _afterCreate; waitUntilHeadsReplicated(ctx: Context, heads: DataService.DocHeadsList): Promise; reIndexHeads(documentIds: DocumentId[]): Promise; /** * Share policy for the Repo's classical automerge-repo sync path (CollectionSynchronizer / * DocSynchronizer — see `src/synchronizer/DocSynchronizer.ts#resolveSharePolicy`). * * NOTE: Subduction replication does NOT consult `shareConfig`. * {@link AutomergeReplicator}s via {@link EchoNetworkAdapter}. */ private readonly _shareConfig; /** * Subduction sedimentree authorization policy. Mirrors {@link _shareConfig.announce} * on the OUTBOUND side (`authorizeFetch`, `filterAuthorizedFetch`) via the same * per-connection `shouldAdvertise` predicate on `_echoNetworkAdapter`. * * `authorizePut` is intentionally allow-all to mirror classical sync (`useSubduction: * false`), which has no inbound gate. Gating inbound here creates a bootstrapping * deadlock during invitations: the joining peer's `_getContainingSpaceForDocument` * cannot resolve the space-root doc until it's loaded, which can't happen if the * inbound write is denied — and subduction `authorizePut` denials are sticky on the * receiver (see .claude/skills/subduction/SKILL.md), so the entry never recovers. * Inbound trust here is bounded by `authorizeFetch` on the sender side (peers can't * push docs we wouldn't have served them) and by the sedimentree's internal * cryptographic structure. */ private readonly _subductionPolicy; /** * Translates subduction PeerId → repo PeerId and delegates to the per-connection * `shouldAdvertise`. Default-allow when the binding hasn't arrived yet (narrow race * window: the handshake event fires before any sedimentree sync round). */ private _shouldShareDocumentWithSubductionPeer; private _shouldSyncCollection; /** * Called by SqliteStorageAdapter after a chunk is committed to SQLite. * Updates heads store and schedules collection sync notification. */ private _afterSave; private _isDocumentInRemoteCollection; private _getContainingSpaceForDocument; private _isInLocalCollection; /** * Resolve the space id owning a document for the share policy. * * Membership is answered first from the local collection state — the space root's document * list (root + linked docs), maintained by `updateLocalCollectionState`. That mapping survives * handle eviction and never blocks on the document loading, so a doc the node owns but whose * handle is evicted or still `'loading'` resolves to its space instead of reading as "not in any * space" and producing a spurious `authorizeFetch`/share-policy denial (logged by the peer as * `not authorized to access sedimentree`). This must stay synchronous for the same reason * `_getContainingSpaceForDocument` refuses to await the load: the network source's availability * is itself gated on the share policy returning, so awaiting the document here would deadlock. * * Falls back to the document's own embedded space key (loaded handle) / the root-doc lookup for * a doc not yet linked into any local collection (e.g. inbound during initial sync). */ getContainingSpaceIdForDocument(documentId: string): Promise; /** * Flush documents to disk. * * Persists ready handles via `_repo.flush`. Head updates are published into * the collection synchronizer asynchronously by {@link _onHeadsChangedTask}; * callers needing an up-to-date sync-state view should subscribe to * {@link collectionStateUpdated} rather than sampling immediately after flush. */ flush(ctx: Context, { documentIds }?: DataService.FlushRequest): Promise; /** * Returns current heads of each requested document. * * Loaded handles are read directly; unloaded documents fall back to the {@link SqliteHeadsStore}, * then to reconstruction from the automerge storage chunks (for docs persisted before * the SqliteHeadsStore was populated). */ getHeads(documentIds: DocumentId[]): Promise<(Heads | undefined)[]>; /** The heads each document's saved changes reach, from the heads store, whatever is loaded and unsaved. */ getStoredHeads(documentIds: DocumentId[]): Promise<(Heads | undefined)[]>; /** * Iterate over all document heads stored on disk. */ listDocumentHeads(): AsyncGenerator<{ documentId: DocumentId; heads: Heads; }>; getLocalCollectionState(collectionId: string): CollectionState | undefined; getRemoteCollectionStates(collectionId: string): ReadonlyMap; refreshCollection(collectionId: string): void; /** * Snapshot of local-vs-remote collection state for the given collectionId. * * Eventually consistent. A single emission via `collectionStateUpdated` may * reflect stale local heads if a local save is mid-propagation through * `_onHeadsChangedTask` (the deferred task that publishes `_afterSave` head * updates into `_collectionSynchronizer`). The follow-up emission from * `_onHeadsChanged` will reflect the up-to-date heads. Consumers must not * treat any single emission as authoritative; subscribe to the stream and * converge. * */ getCollectionSyncState(collectionId: string): Promise; /** * Update the local collection state based on the locally stored document heads. */ updateLocalCollectionState(collectionId: string, allDocumentIds: DocumentId[]): Promise; clearLocalCollectionState(collectionId: string): Promise; /** For the collection diff: an evicted document holds only the changes confirmed while it was resident. */ private _hasLocalChange; private _confirmFromStorage; private _storedHistoryCheck; private _confirmChange; private _onCollectionStateQueried; private _onCollectionStateReceived; private _queryCollectionState; private _sendCollectionState; private _onPeerConnected; private _onPeerDisconnected; private _onRemoteCollectionStateUpdated; private _handleCollectionSync; /** Counts a pass that left the pair diverged, with both sides' heads so a stuck document is diagnosable from logs. */ private _reportNonConvergence; /** * Leases a document until its query settles, which both triggers replication and keeps the * document resident while its bytes are in flight — nothing else holds it until they land. * * Bounded by {@link REPLICATION_LEASE_TIMEOUT} rather than waiting for `'ready'` forever: a peer * can advertise a document it never delivers, and `'unavailable'` is transient here (the query * reports it whenever no source can serve the document *yet*), so it cannot be the release signal. */ private _leaseUntilSettled; private _onHeadsChanged; } export declare const documentIdToSedimentreeIdHex: (documentId: DocumentId) => string; //# sourceMappingURL=automerge-host.d.ts.map