import { type Heads } from '@automerge/automerge'; import { type AnyDocumentId, type AutomergeUrl, type DocumentId } from '@automerge/automerge-repo'; import * as EffectContext from 'effect/Context'; import * as Layer from 'effect/Layer'; import * as SqlClient from 'effect/sql/SqlClient'; import { Context, Resource } from '@dxos/context'; import { EntityStructure } from '@dxos/echo-protocol'; import * as RuntimeProvider from '@dxos/effect/RuntimeProvider'; import { FeedStore } from '@dxos/feed'; import { IndexEngine, type IndexTransactionLimits } from '@dxos/index-core'; import { type PublicKey, SpaceId } from '@dxos/keys'; import { FeedProtocol } from '@dxos/protocols'; import { type DataService, type FeedService } from '@dxos/protocols/rpc'; import { AutomergeHost, type AutomergeReplicator, type CreateDocOptions, type DocumentLease, type EchoDataStats, type LoadDocOptions, type PeerIdProvider, type RootDocumentSpaceKeyProvider } from '../automerge/index.ts'; import { DataServiceImpl } from './data-service.ts'; import { type DatabaseRoot } from './database-root.ts'; import { type IndexRequestReason } from './index-scheduler.ts'; import { IndexStatusTracker } from './index-status.ts'; import { type QueryDebounceOptions, QueryServiceImpl } from './query-service.ts'; import { type SpaceRootRefs } from './space-state-manager.ts'; import { type QueryExecutorMode } from '../query/index.ts'; export type EchoHostProps = { /** Query evaluation path; defaults to `DX_ECHO_QUERY_EXECUTOR`, else the compiled SQL executor. */ queryExecutor?: QueryExecutorMode; /** Overrides how live queries are debounced in proportion to their cost; see {@link QueryDebounceOptions}. */ queryDebounce?: Partial; /** Overrides the bounds on one index write transaction; see {@link IndexTransactionLimits}. */ indexTransactionLimits?: Partial; /** Overrides how often index progress is counted, once a second by default. */ indexRecountInterval?: number; peerIdProvider?: PeerIdProvider; getSpaceKeyByRootDocumentId?: RootDocumentSpaceKeyProvider; runtime: RuntimeProvider.RuntimeProvider; /** * This peer is allowed to assign positions (global-order) to items appended to the queue. * @default false */ assignQueuePositions?: boolean; /** * Enable Subduction sedimentree transport for Automerge document replication. * @default false */ useSubduction?: boolean; }; /** * Feed sync handlers wired after construction to break the EchoHost <-> FeedSyncer cycle. */ export type FeedSyncHandlers = { /** * Callback to run blocking feed sync. */ syncFeed: (ctx: Context, request: FeedService.SyncFeedRequest) => Promise; }; declare const EchoHostService_base: EffectContext.ServiceClass; /** * Effect service tag for {@link EchoHost}. */ export declare class EchoHostService extends EchoHostService_base { } /** * Host for the Echo database. * Manages multiple spaces. * Stores data to disk. * Can sync with pluggable data replicators. */ export declare class EchoHost extends Resource { #private; private readonly _automergeHost; private readonly _queryService; private readonly _dataService; private readonly _spaceStateManager; private readonly _echoDataMonitor; private readonly _automergeDataSource; /** Built in `_open`: resolving the SQL client is asynchronous on some platforms. */ private _indexEngine; /** Resolved when the host opens; the query planner builds compiled statements with it. */ private _sql; private readonly _convergenceKeyMerger; private readonly _runtime; private readonly _feedStore; private readonly _feedDataSource; private readonly _indexScheduler; /** What the index is doing, for boot screens and progress indicators; see {@link DataService.IndexStatus}. */ readonly indexStatus: IndexStatusTracker; private _feedService; /** Last known document set per space, to detect what left the directory. */ private readonly _spaceDocumentIds; constructor({ peerIdProvider, getSpaceKeyByRootDocumentId, runtime, queryExecutor, queryDebounce, indexTransactionLimits, indexRecountInterval, assignQueuePositions, useSubduction, }: EchoHostProps); get spaceIds(): SpaceId[]; get queryService(): QueryServiceImpl; get dataService(): DataServiceImpl; get feedService(): FeedService.Handlers; get roots(): ReadonlyMap; get feedStore(): FeedStore; /** * Automerge document store backing every space. */ get automergeHost(): AutomergeHost; /** * Wires the feed sync handlers after the composing stack is fully constructed. */ setFeedSyncHandlers(handlers: FeedSyncHandlers): void; /** * Index engine for queries. */ get indexEngine(): IndexEngine; protected _open(ctx: Context): Promise; protected _close(ctx: Context): Promise; /** * Flush all pending writes to the underlying storage. */ flush(ctx: Context): Promise; /** * Waits until every change made before the call is indexed. Changes made during the wait are left * to later passes, so a stream of writes cannot hold the caller. * * Bails as a no-op when the host has been closed: a late `db.flush()` RPC * (client still has an open service ref while the host is in/post-teardown) * has nothing to update against. The pre-loop and post-iteration * `_ctx.disposed` checks prevent `runBlocking` from being entered against a * disposed context — which would throw `ContextDisposedError` and escape as * an unhandled rejection at the fire-and-forget originating caller. Other * `Resource` methods in this codebase (e.g. `SqliteStorageAdapter.load`) * follow the same closed-host early-out pattern. */ updateIndexes({ secondaryIndexes, reason, }?: { secondaryIndexes?: boolean; reason?: IndexRequestReason; }): Promise; /** * Indexes the secondary-index backlog to completion, which the debounced flush otherwise gets to * on its own schedule (see {@link IndexEngine.updateSecondaryIndexes}). Runs one at a time: a call * made during a run waits for it, then runs on its own to cover what the run may have missed. * * @returns Number of records indexed. */ updateSecondaryIndexes(): Promise; /** * Leases the document and waits for it to be ready. Dispose the lease when done with it. * * @returns `null` when the document is not available yet (e.g. storage-only load with no local chunks). */ loadDoc(ctx: Context, documentId: AnyDocumentId, opts?: LoadDocOptions): Promise | null>; /** Leases the document without waiting for it to load. Dispose the lease when done with it. */ acquireDoc(documentId: AnyDocumentId): DocumentLease; exportDoc(id: AnyDocumentId): Promise; /** * Create new persisted document. */ createDoc(initialValue?: T, opts?: CreateDocOptions): Promise>; /** * Create new space root. */ createSpaceRoot(ctx: Context, spaceKey: PublicKey): Promise; /** * Creates a space anchored on an immutable space root document, which carries the credentials * document. The id still derives from the space genesis key, exactly as a feed-backed space's * does — the root changes where credentials live, not how the space is identified. * * NOTE: `createSpaceRoot` above creates the DIRECTORY, which predates this naming. */ createSpaceWithRootDocument(ctx: Context, spaceKey: PublicKey): Promise; /** * Mints a space root over a legacy space's existing directory, keeping the space id: it was derived * from the space key and cannot be reproduced from a document, which is what `spaceKey` derivation * records. Idempotent — a space that already has a root keeps it, so a re-run cannot fork the anchor. */ migrateSpaceToRootDocument(ctx: Context, spaceId: SpaceId): Promise; /** * Links an already-created credentials document from the space root, once. Idempotent — the link is * what the per-space source flip keys off, so a second document would fork the chain. The document * itself is built a layer up, where credential encoding lives. */ /** * Adopts a space root minted elsewhere, so a joining peer records the root the space already has * rather than minting a second one over it. Idempotent; the root must name this space. */ adoptSpaceRoot(ctx: Context, spaceId: SpaceId, spaceRootUrl: AutomergeUrl, { fetchFromNetwork, timeout }?: { fetchFromNetwork?: boolean; timeout?: number; }): Promise; setCredentialsDocument(ctx: Context, spaceId: SpaceId, credentialsDocUrl: AutomergeUrl): Promise; /** References carried by the space root document, or undefined for a space that predates it. */ getSpaceRootRefs(spaceId: SpaceId): SpaceRootRefs | undefined; get spaces(): ReadonlyArray<{ spaceId: SpaceId; rootDocUrl: AutomergeUrl; }>; openSpaceRoot(ctx: Context, spaceId: SpaceId): Promise; updateSpaceRoot(ctx: Context, spaceId: SpaceId, automergeUrl: AutomergeUrl): Promise; /** * The directory JSON the index holds for a space root, when it was read at the heads the root is stored at: what * a client or this host can show the root from without loading it. */ readDirectorySnapshot(documentId: DocumentId): Promise<{ heads: Heads; json: string; } | undefined>; closeSpace(spaceId: SpaceId): Promise; /** * Runs `wipe`, which deletes this host's rows while it stays open, with indexing stopped and the feed * store's caches dropped after it: either would otherwise write cursors under tokens the wipe deleted. */ wipeStorage(wipe: () => Promise): Promise; removeSpace(spaceId: SpaceId): Promise; /** * Install data replicator. */ addReplicator(ctx: Context, replicator: AutomergeReplicator): Promise; /** * Remove data replicator. */ removeReplicator(replicator: AutomergeReplicator): Promise; /** * Run collection sync for the given space. * Does not wait for the sync to complete. */ runCollectionSync(spaceId: SpaceId): Promise; /** * Get all feeds and their blocks for a space. * Used for space archive export. */ getAllFeedsForSpace(spaceId: SpaceId): Promise>; /** * Per-space storage metrics: objects (alive/deleted), automerge documents, feeds, feed blocks, * plus what the host is holding in memory. See `docs/GARBAGE_COLLECTION.md`. */ getSpaceStats(spaceId: SpaceId): Promise; /** * Reclaim storage held by soft-deleted objects and unreachable documents for a space. * See `docs/GARBAGE_COLLECTION.md` for the full algorithm and its safety invariants: unlink * soft-deleted objects from the space directory (step 1), wipe every document owned by the space * that is no longer reachable from the post-unlink directory (step 2), then drop the reclaimed * documents' index rows (step 5). */ runGarbageCollection(spaceId: SpaceId, options?: DataService.RunGarbageCollectionRequest): Promise; /** * Writes each object into a new document of its own and links it from the space directory in one change, which is * the shape every object takes: the directory itself holds no objects. */ addObjects(ctx: Context, spaceId: SpaceId, objects: Readonly>): Promise; /** * Moves every object inlined in a space directory into a document of its own, linked from the directory, and * waits for the pass. Runs on its own whenever a space opens or its document list changes; exposed so callers * that must observe the result (tests, tooling) need not wait for that. */ migrateInlineObjects(spaceId: SpaceId): Promise; /** * One indexing pass over both data sources. * * Spanned so that a pass is a single trace naming the requests that caused it, instead of one * parentless `IndexEngine.update` root per data source with nothing to attribute it to. The * `ctx` the decorator hands back carries the pass span, and `EffectEx.withContext` is what * carries it across into the Effect world. */ private _runIndexPass; } export type { EchoDataStats }; export type EchoStatsDiagnostic = { loadedDocsCount: number; dataStats: EchoDataStats; }; /** A space created from a space root document, before any credentials exist for it. */ export type CreatedSpace = { spaceId: SpaceId; /** Automerge URL of the immutable root; goes into the `SpaceMember` credential as `spaceRootUrl`. */ spaceRootUrl: AutomergeUrl; directory: DatabaseRoot; }; export type EchoHostLayerOptions = Pick; /** * Effect Layer constructing a dormant {@link EchoHost}. */ export declare const EchoHostLayer: (options?: EchoHostLayerOptions) => Layer.Layer; //# sourceMappingURL=echo-host.d.ts.map