// // Copyright 2024 DXOS.org // import { type Heads } from '@automerge/automerge'; import type { DocumentId, PeerId } from '@automerge/automerge-repo'; import * as Array from 'effect/Array'; import * as Record from 'effect/Record'; import { Event, asyncReturn, scheduleTask, scheduleTaskInterval } from '@dxos/async'; import { type Context, Resource } from '@dxos/context'; import { isEdgePeerId } from '@dxos/echo-protocol'; import { PublicKey } from '@dxos/keys'; import { log } from '@dxos/log'; import { trace } from '@dxos/tracing'; import { defaultMap } from '@dxos/util'; import { PeerNotFoundError } from './errors.ts'; import { tryGetSpaceIdFromCollectionId } from './space-collection.ts'; const MIN_QUERY_INTERVAL = 5_000; const POLL_INTERVAL = 10_000; /** Whether the local replica of a document contains the change with the given hash; `false` marks it `advertised`. */ export type HasLocalChange = (documentId: DocumentId, changeHash: string) => boolean; export type CollectionSynchronizerProps = { sendCollectionState: (collectionId: string, peerId: PeerId, state: CollectionState) => void; queryCollectionState: (collectionId: string, peerId: PeerId) => void; shouldSyncCollection: (collectionId: string, peerId: PeerId) => boolean; /** Tells an ancestor head from a change worth a sync round. */ hasLocalChange?: HasLocalChange; }; /** * Implements collection sync protocol. */ export class CollectionSynchronizer extends Resource { private readonly _sendCollectionState: CollectionSynchronizerProps['sendCollectionState']; private readonly _queryCollectionState: CollectionSynchronizerProps['queryCollectionState']; private readonly _shouldSyncCollection: CollectionSynchronizerProps['shouldSyncCollection']; private readonly _hasLocalChange: CollectionSynchronizerProps['hasLocalChange']; /** * CollectionId -> State. */ private readonly _perCollectionStates = new Map(); private readonly _activeCollections = new Set(); private readonly _connectedPeers = new Set(); /** Open sync span ids, by collection then peer. */ private readonly _syncSpans = new Map>(); /** Open sync spans with EDGE, by collection alone: each reconnect reaches EDGE under a new peer id. */ private readonly _edgeSyncSpans = new Map(); /** The manual span registry is global, so ids must differ across synchronizers and across a pair's spans. */ private readonly _spanIdPrefix = `collection-sync-${PublicKey.random().toHex()}`; private _syncSpanCount = 0; public readonly peerCollectionStateUpdated = new Event<{ collectionId: string; peerId: PeerId; newDocsAppeared: boolean; }>(); constructor(params: CollectionSynchronizerProps) { super(); this._sendCollectionState = params.sendCollectionState; this._queryCollectionState = params.queryCollectionState; this._shouldSyncCollection = params.shouldSyncCollection; this._hasLocalChange = params.hasLocalChange; } protected override async _open(ctx: Context): Promise { scheduleTaskInterval( this._ctx, async () => { for (const collectionId of this._perCollectionStates.keys()) { if (this._activeCollections.has(collectionId)) { this.refreshCollection(collectionId); await asyncReturn(); } } }, POLL_INTERVAL, ); } protected override async _close(_ctx: Context): Promise { this._endSyncSpans('closed', () => true); this._endEdgeSyncSpans('closed', () => true); } getRegisteredCollectionIds(): string[] { return [...this._activeCollections]; } getLocalCollectionState(collectionId: string): CollectionState | undefined { return this._perCollectionStates.get(collectionId)?.localState; } setLocalCollectionState(collectionId: string, state: CollectionState): void { this._activeCollections.add(collectionId); log('setLocalCollectionState', { collectionId, state }); const perCollectionState = this._getOrCreatePerCollectionState(collectionId); const trigger = perCollectionState.localState ? 'local' : 'initial'; perCollectionState.localState = state; for (const peerId of this._connectedPeers) { this._diffCollectionState(collectionId, peerId, trigger); } this._scheduleBroadcast(collectionId); } /** * Coalesce bursts of `setLocalCollectionState` (e.g. from `_onHeadsChanged` during an * import) into one broadcast microtask per collection. If another call arrives while * the microtask is pending, we just flag the collection dirty — the in-flight run * already reads the latest `localState`. If it arrives during the run itself, we * schedule exactly one follow-up. */ private _scheduleBroadcast(collectionId: string): void { const perCollectionState = this._getOrCreatePerCollectionState(collectionId); queueMicrotask(() => { this._refreshInterestedPeers(collectionId); this._broadcastLocalState(collectionId); this.refreshCollection(collectionId); }); } clearLocalCollectionState(collectionId: string): void { this._endSyncSpans('closed', (spanCollectionId) => spanCollectionId === collectionId); this._endEdgeSyncSpans('closed', (spanCollectionId) => spanCollectionId === collectionId); this._activeCollections.delete(collectionId); this._perCollectionStates.delete(collectionId); log('clearLocalCollectionState', { collectionId }); } getRemoteCollectionStates(collectionId: string): ReadonlyMap { return this._getOrCreatePerCollectionState(collectionId).remoteStates; } refreshCollection(collectionId: string): void { let scheduleAnotherRefresh = false; const state = this._getOrCreatePerCollectionState(collectionId); for (const peerId of this._connectedPeers) { if (state.interestedPeers.has(peerId)) { const lastQueried = state.lastQueried.get(peerId) ?? 0; if (Date.now() - lastQueried > MIN_QUERY_INTERVAL) { state.lastQueried.set(peerId, Date.now()); this._queryCollectionState(collectionId, peerId); } else { scheduleAnotherRefresh = true; } } } if (scheduleAnotherRefresh) { scheduleTask(this._ctx, () => this.refreshCollection(collectionId), MIN_QUERY_INTERVAL); } } /** * Callback when a connection to a peer is established. */ onConnectionOpen(peerId: PeerId): void { log('onConnectionOpen', { peerId }); this._connectedPeers.add(peerId); queueMicrotask(async () => { if (this._ctx.disposed) { return; } for (const [collectionId, state] of this._perCollectionStates.entries()) { if (this._activeCollections.has(collectionId) && this._shouldSyncCollection(collectionId, peerId)) { state.interestedPeers.add(peerId); state.lastQueried.set(peerId, Date.now()); this._queryCollectionState(collectionId, peerId); } } }); } /** * Callback when a connection to a peer is closed. */ onConnectionClosed(peerId: PeerId): void { log('onConnectionClosed', { peerId }); // An EDGE span outlives the connection: the next one resumes it, so it only counts the drop. for (const span of this._edgeSyncSpans.values()) { if (span.connectedPeers.delete(peerId)) { span.disconnects++; } } this._endSyncSpans('disconnected', (_, spanPeerId) => spanPeerId === peerId); this._connectedPeers.delete(peerId); for (const perCollectionState of this._perCollectionStates.values()) { perCollectionState.remoteStates.delete(peerId); perCollectionState.interestedPeers.delete(peerId); perCollectionState.lastQueried.delete(peerId); perCollectionState.lastBroadcast.delete(peerId); perCollectionState.syncedVerdicts.delete(peerId); } } /** * Callback when a peer queries the state of a collection. * * If we have no local state yet we silently drop the query; the peer will receive our * state via {@link _broadcastLocalState} once `setLocalCollectionState` is called. */ onCollectionStateQueried(collectionId: string, peerId: PeerId): void { const perCollectionState = this._getOrCreatePerCollectionState(collectionId); if (perCollectionState.localState) { try { this._sendCollectionState(collectionId, peerId, withoutEmptyHeads(perCollectionState.localState)); } catch (error) { if (PeerNotFoundError.is(error)) { log('peer not found when sending collection state callback', { error }); return; } throw error; } } } /** * Callback when a peer sends the state of a collection. */ onRemoteStateReceived(collectionId: string, peerId: PeerId, state: CollectionState): void { log('onRemoteStateReceived', { collectionId, peerId, state }); validateCollectionState(state); const perCollectionState = this._getOrCreatePerCollectionState(collectionId); const previousRemoteState = perCollectionState.remoteStates.get(peerId); // Dedupe an unchanged remote state only while that peer is fully caught up. A peer whose // state is unchanged AND still diverges from ours is a stalled sync: skipping the diff // would suppress `peerCollectionStateUpdated`, and with it the `_handleCollectionSync` // replication retry, for as long as the remote keeps repeating itself — i.e. forever. // The poll below can then only ever act on change, never on a stall, and the sole escape // is a reconnect. if ( previousRemoteState && isCollectionStateEqual(previousRemoteState, state) && this._isSyncedWithPeer(collectionId, peerId) ) { return; } perCollectionState.remoteStates.set(peerId, state); this._diffCollectionState(collectionId, peerId, previousRemoteState ? 'remote' : 'initial'); } /** True when the last recorded state for `peerId` has no outstanding work against our local state. */ private _isSyncedWithPeer(collectionId: string, peerId: PeerId): boolean { const perCollectionState = this._getOrCreatePerCollectionState(collectionId); const remoteState = perCollectionState.remoteStates.get(peerId); if (!remoteState) { return false; } const verdict = perCollectionState.syncedVerdicts.get(peerId); if (verdict && verdict.local === perCollectionState.localState && verdict.remote === remoteState) { return verdict.synced; } const localState = perCollectionState.localState ?? { documents: {} }; const synced = isDiffEmpty( diffCollectionStateForPeer(localState, remoteState, { isEdgePeer: isEdgePeerId(peerId), hasLocalChange: this._hasLocalChange, }), ); perCollectionState.syncedVerdicts.set(peerId, { local: perCollectionState.localState, remote: remoteState, synced, }); return synced; } private _diffCollectionState(collectionId: string, peerId: PeerId, trigger: SyncSpanTrigger) { const perCollectionState = this._getOrCreatePerCollectionState(collectionId); const remoteState = perCollectionState.remoteStates.get(peerId); if (!remoteState) { return; } log('diffCollectionState', { collectionId, peerId }); const localState = perCollectionState.localState ?? { documents: {} }; const diff = diffCollectionStateForPeer(localState, remoteState, { isEdgePeer: isEdgePeerId(peerId), hasLocalChange: this._hasLocalChange, }); if (isDiffEmpty(diff)) { if (isEdgePeerId(peerId)) { this._endEdgeSyncSpan(collectionId, 'synced'); } else { this._endSyncSpan(collectionId, peerId, 'synced'); } } else { this._startSyncSpan(collectionId, peerId, trigger, diff); } log('diff', { localState: localState.documents, remoteState: remoteState.documents, missingOnLocal: diff.missingOnLocal, missingOnRemote: diff.missingOnRemote, different: diff.different, advertised: diff.advertised, }); log('emit peer collection state update'); this.peerCollectionStateUpdated.emit({ peerId, collectionId, newDocsAppeared: diff.missingOnLocal.length > 0, }); } /** * Opens a span when a collection diverges from a peer; see {@link SYNC_SPAN_METHOD} for its dashboard. * Spans with EDGE are keyed by the collection, so one span covers a catch-up however many connections * it takes; spans with other peers, whose ids survive a reconnect, are keyed by the peer as well. */ private _startSyncSpan( collectionId: string, peerId: PeerId, trigger: SyncSpanTrigger, diff: CollectionStateDiff, ): void { // Nothing would end a span for a closed synchronizer, a gone peer or an inactive collection. if (!this.isOpen || !this._connectedPeers.has(peerId) || !this._activeCollections.has(collectionId)) { return; } const edgeSpan = isEdgePeerId(peerId) ? this._edgeSyncSpans.get(collectionId) : undefined; if (edgeSpan) { if (!edgeSpan.connectedPeers.has(peerId)) { edgeSpan.connectedPeers.add(peerId); edgeSpan.connections++; } return; } if (this._syncSpans.get(collectionId)?.has(peerId)) { return; } const spanId = `${this._spanIdPrefix}-${collectionId}-${peerId}-${++this._syncSpanCount}`; if (isEdgePeerId(peerId)) { this._edgeSyncSpans.set(collectionId, { spanId, connections: 1, disconnects: 0, connectedPeers: new Set([peerId]), }); } else { defaultMap(this._syncSpans, collectionId, () => new Map()).set(peerId, spanId); } const spaceId = tryGetSpaceIdFromCollectionId(collectionId); // The derived ctx is discarded: the downstream `_queryCollectionState` hop is a user-supplied callback with no ctx. void trace.spanStart({ id: spanId, methodName: SYNC_SPAN_METHOD, instance: this, parentCtx: this._ctx, showInBrowserTimeline: true, attributes: { peerId, collectionId, ...(spaceId ? { spaceId } : {}), trigger, missingOnLocal: diff.missingOnLocal.length, missingOnRemote: diff.missingOnRemote.length, different: diff.different.length, }, }); } private _endEdgeSyncSpan(collectionId: string, outcome: SyncSpanOutcome): void { const span = this._edgeSyncSpans.get(collectionId); if (!span) { return; } this._edgeSyncSpans.delete(collectionId); trace.spanEnd(span.spanId, { attributes: { outcome, connections: span.connections, disconnects: span.disconnects }, }); } private _endEdgeSyncSpans(outcome: SyncSpanOutcome, matches: (collectionId: string) => boolean): void { for (const collectionId of [...this._edgeSyncSpans.keys()]) { if (matches(collectionId)) { this._endEdgeSyncSpan(collectionId, outcome); } } } private _endSyncSpan(collectionId: string, peerId: PeerId, outcome: SyncSpanOutcome): void { const spans = this._syncSpans.get(collectionId); const spanId = spans?.get(peerId); if (!spans || spanId === undefined) { return; } spans.delete(peerId); if (spans.size === 0) { this._syncSpans.delete(collectionId); } trace.spanEnd(spanId, { attributes: { outcome } }); } private _endSyncSpans(outcome: SyncSpanOutcome, matches: (collectionId: string, peerId: PeerId) => boolean): void { for (const [collectionId, spans] of this._syncSpans) { for (const peerId of spans.keys()) { if (matches(collectionId, peerId)) { this._endSyncSpan(collectionId, peerId, outcome); } } } } private _getOrCreatePerCollectionState(collectionId: string): PerCollectionState { return defaultMap(this._perCollectionStates, collectionId, () => ({ localState: undefined, remoteStates: new Map(), interestedPeers: new Set(), lastQueried: new Map(), lastBroadcast: new Map(), syncedVerdicts: new Map(), })); } /** * Push local state to interested peers whose last-known remote state differs from local * (or is unknown), then pull from peers via {@link refreshCollection}. * * Diff-gating avoids spamming peers that are already in sync; this matters because * {@link setLocalCollectionState} is called on every local heads change. */ private _broadcastLocalState(collectionId: string): void { if (this._ctx.disposed || !this._activeCollections.has(collectionId)) { return; } const perCollectionState = this._getOrCreatePerCollectionState(collectionId); const localState = perCollectionState.localState; if (!localState) { return; } // Edge replicators are pull-only from our perspective: the edge is the source of truth and // already holds every doc in the space, so proactively pushing our heads on every local // change is wasted work. The edge can still pull our state via `onCollectionStateQueried`. for (const peerId of perCollectionState.interestedPeers) { if (isEdgePeerId(peerId)) { continue; } const lastBroadcast = perCollectionState.lastBroadcast.get(peerId) ?? 0; if (Date.now() - lastBroadcast > MIN_QUERY_INTERVAL) { perCollectionState.lastBroadcast.set(peerId, Date.now()); try { this._sendCollectionState(collectionId, peerId, withoutEmptyHeads(localState)); } catch (error) { if (PeerNotFoundError.is(error)) { log('peer not found when broadcasting collection state', { error }); return; } throw error; } } } } private _refreshInterestedPeers(collectionId: string): void { for (const peerId of this._connectedPeers) { if (this._shouldSyncCollection(collectionId, peerId)) { this._getOrCreatePerCollectionState(collectionId).interestedPeers.add(peerId); } else { this._getOrCreatePerCollectionState(collectionId).interestedPeers.delete(peerId); } } } } type PerCollectionState = { localState?: CollectionState; remoteStates: Map; interestedPeers: Set; lastQueried: Map; lastBroadcast: Map; syncedVerdicts: Map; }; export type CollectionState = { /** * DocumentId -> Heads. */ readonly documents: Readonly>; }; export type CollectionStateDiff = { missingOnRemote: DocumentId[]; missingOnLocal: DocumentId[]; different: DocumentId[]; /** * In sync, since the heads overlap, but the remote advertises a change the local replica lacks: worth one sync * round in case it is new, never a divergence. */ advertised: DocumentId[]; }; /** One collection's sync span with EDGE, across however many connections the catch-up takes. */ type EdgeSyncSpan = { spanId: string; /** Connections to EDGE that diverged while the span was open. */ connections: number; /** Connections to EDGE that dropped while the span was open. */ disconnects: number; /** EDGE peers of this span still connected; a drop counts once per peer. */ connectedPeers: Set; }; /** What exposed a divergence: the pair's first comparison, a peer change, or a local change. */ type SyncSpanTrigger = 'initial' | 'remote' | 'local'; /** * `closed` covers both a cleared collection and a closed synchronizer; `disconnected` ends only a * span with a non-EDGE peer, since one with EDGE carries on over the next connection. */ type SyncSpanOutcome = 'synced' | 'disconnected' | 'closed'; /** In sync: a document that is only {@link CollectionStateDiff.advertised} does not count. */ const isDiffEmpty = (diff: CollectionStateDiff): boolean => diff.different.length === 0 && diff.missingOnLocal.length === 0 && diff.missingOnRemote.length === 0; export const isCollectionStateEqual = (left: CollectionState, right: CollectionState): boolean => { let unmatched = 0; for (const documentId in left.documents) { const heads = left.documents[documentId as DocumentId]; if (heads.length === 0) { continue; } const other = right.documents[documentId as DocumentId]; if (!other || !headsEqual(heads, other)) { return false; } unmatched++; } for (const documentId in right.documents) { if (right.documents[documentId as DocumentId].length > 0) { unmatched--; } } return unmatched === 0; }; /** * Strip entries whose heads array is empty before sending a CollectionState * over the wire. Empty-heads entries are inert (they don't participate in the * diff thanks to `Record.filter` in {@link diffCollectionState}) but they * inflate the on-wire payload AND end up advertised as "I know about this * document with no commits" to the receiver — leaking sedimentree ids that * leaked into the local store from other spaces via the subduction * fingerprint exchange. Filtering at the send site is the cheapest place to * keep collection-state semantics aligned with `diffCollectionState`. */ export const withoutEmptyHeads = (state: CollectionState): CollectionState => ({ documents: Record.filter(state.documents, (heads) => heads.length > 0), }); /** * Restrict a remote {@link CollectionState} to the document keys present in `local`. * * Used when diffing against an edge peer: edge subduction storage retains every * sedimentree id it has ever seen (old roots, partial creations, cross-space * fingerprint leaks), so a raw symmetric diff would surface those as * `missingOnLocal` forever. The local root's `links` are authoritative for * "what docs are in this space"; intersecting the remote view with the local * key set drops the noise without changing wire format. */ export const subsetRemoteToLocal = (local: CollectionState, remote: CollectionState): CollectionState => ({ documents: Record.filter(remote.documents, (_heads, documentId) => documentId in local.documents), }); /** * Peer-aware wrapper around {@link diffCollectionState}. * * For mesh peers the diff is symmetric (every doc on either side participates). * For edge peers we first intersect the remote state with the local key set — * see {@link subsetRemoteToLocal} for why. */ export const diffCollectionStateForPeer = ( local: CollectionState, remote: CollectionState, { isEdgePeer, hasLocalChange }: { isEdgePeer: boolean; hasLocalChange?: HasLocalChange }, ): CollectionStateDiff => { const effectiveRemote = isEdgePeer ? subsetRemoteToLocal(local, remote) : remote; return diffCollectionState(local, effectiveRemote, { hasLocalChange }); }; export type DiffCollectionStateOptions = { hasLocalChange?: HasLocalChange; /** Compares head sets exactly instead of applying the overlap rule. */ exact?: boolean; }; export const diffCollectionState = ( local: CollectionState, remote: CollectionState, { hasLocalChange, exact = false }: DiffCollectionStateOptions = {}, ): CollectionStateDiff => { const localDocuments = Record.filter(local.documents, (heads) => heads.length > 0); const remoteDocuments = Record.filter(remote.documents, (heads) => heads.length > 0); // NOTE: Using `Array.union` is slow. const allDocuments = [...new Set([...Record.keys(localDocuments), ...Record.keys(remoteDocuments)])] as DocumentId[]; const missingOnRemote: DocumentId[] = []; const missingOnLocal: DocumentId[] = []; const different: DocumentId[] = []; const advertised: DocumentId[] = []; for (const documentId of allDocuments) { if (!localDocuments[documentId]) { missingOnLocal.push(documentId); } else if (!remoteDocuments[documentId]) { missingOnRemote.push(documentId); } else if (exact) { if (!headsEqual(local.documents[documentId], remote.documents[documentId])) { different.push(documentId); } } else if (!headsOverlap(local.documents[documentId], remote.documents[documentId])) { // Subduction's `getAllHeads()` on the edge mixes raw `LooseCommit` tips with // fragment heads (commit IDs promoted to depth >= 1 by leading-zero count of the // hash). The host's `automerge.getHeads(doc)` only ever sees raw change tips — // it has no notion of fragments — so the two views can disagree on a doc's // head set even when every change byte is replicated. We treat the doc as in // sync as long as both sides agree on at least one head. different.push(documentId); } else if ( advertisesMissingChange(documentId, local.documents[documentId], remote.documents[documentId], hasLocalChange) ) { advertised.push(documentId); } } return { missingOnRemote, missingOnLocal, different, advertised, }; }; /** * Returns true when two head-sets share at least one element. Used by the collection-state * diff so transient fragment-vs-commit-ID mismatches between subduction peers don't get * reported as `differentDocuments` while the underlying change bytes are fully replicated. */ const headsOverlap = (a: readonly string[], b: readonly string[]): boolean => { if (a.length === 0 || b.length === 0) { return false; } const aset = new Set(a); for (const h of b) { if (aset.has(h)) { return true; } } return false; }; const headsEqual = (a: readonly string[], b: readonly string[]): boolean => { if (a.length === b.length && a.every((head, index) => head === b[index])) { return true; } const aset = new Set(a); const bset = new Set(b); return aset.size === bset.size && [...bset].every((head) => aset.has(head)); }; const advertisesMissingChange = ( documentId: DocumentId, local: readonly string[], remote: readonly string[], hasLocalChange: HasLocalChange | undefined, ): boolean => { if (!hasLocalChange) { return false; } const localSet = new Set(local); return remote.some((head) => !localSet.has(head) && !hasLocalChange(documentId, head)); }; const validateCollectionState = (state: CollectionState) => { for (const documentId in state.documents) { if (!isValidDocumentId(documentId as DocumentId)) { throw new Error(`Invalid documentId: ${documentId}`); } const heads = state.documents[documentId as DocumentId]; if (Array.isArray(heads)) { for (const head of heads) { if (typeof head !== 'string') { throw new Error(`Invalid heads: ${heads}`); } } } } }; const isValidDocumentId = (documentId: DocumentId) => { return typeof documentId === 'string' && !documentId.includes(':'); }; /** * The PostHog dashboard "EDGE replication latency" (https://eu.posthog.com/project/126171/dashboard/973334) queries * this name, the attributes set in `_startSyncSpan` and the trigger and outcome values: update it when changing them. * A span with EDGE also ends with `connections` and `disconnects`: how many connections diverged and dropped under it. */ const SYNC_SPAN_METHOD = 'syncPeer';