// // Copyright 2024 DXOS.org // import { type DocumentId, type Message, NetworkAdapter, type PeerId, type PeerMetadata, } from '@automerge/automerge-repo'; import { Event, Trigger, synchronized } from '@dxos/async'; import { type Context, LifecycleState } from '@dxos/context'; import { invariant } from '@dxos/invariant'; import { type PublicKey, type SpaceId } from '@dxos/keys'; import { log } from '@dxos/log'; import { isNonNullable } from '@dxos/util'; import { type AutomergeReplicator, type AutomergeReplicatorConnection, type RemoteDocumentExistenceCheckProps, type ReplicatorConnectionMessage, type ShouldAdvertiseProps, type ShouldSyncCollectionProps, } from './echo-replicator.ts'; import { PeerNotFoundError } from './errors.ts'; import { type CollectionQueryMessage, type CollectionStateMessage, isCollectionQueryMessage, isCollectionStateMessage, } from './network-protocol.ts'; export interface NetworkDataMonitor { recordPeerConnected(peerId: string): void; recordPeerDisconnected(peerId: string): void; recordMessageSent(message: Message, duration: number): void; recordMessageReceived(message: Message): void; recordMessageSendingFailed(message: Message): void; } export type EchoNetworkAdapterProps = { getContainingSpaceForDocument: (documentId: string) => Promise; getContainingSpaceIdForDocument: (documentId: string) => Promise; isDocumentInRemoteCollection: (params: RemoteDocumentExistenceCheckProps) => Promise; onCollectionStateQueried: (collectionId: string, peerId: PeerId) => void; onCollectionStateReceived: (collectionId: string, peerId: PeerId, state: unknown) => void; /** Invoked when a replicator connection opens (including after reconnect). */ onConnectionOpen?: () => void; /** What a connected peer gaining access to more spaces does: re-announce it, or run this handler instead. */ onConnectionAuthScopeChanged: 'reannounce-peer' | ((peerId: PeerId) => void); monitor?: NetworkDataMonitor; }; type ConnectionEntry = { isOpen: boolean; connection: AutomergeReplicatorConnection; reader: ReadableStreamDefaultReader; writer: WritableStreamDefaultWriter; requestedDocuments: Set; }; /** * Manages a set of {@link AutomergeReplicator} instances. */ export class EchoNetworkAdapter extends NetworkAdapter { private readonly _replicators = new Set(); /** * Remote peer id -> connection. */ private readonly _connections = new Map(); /** Peers mid-reset, whose event pair must not read as a peer leaving and rejoining (DX-1277). */ private readonly _resettingTransports = new Set(); private _lifecycleState: LifecycleState = LifecycleState.CLOSED; private readonly _connected = new Trigger(); private readonly _ready = new Trigger(); public readonly documentRequested = new Event<{ documentId: DocumentId; peerId: PeerId }>(); constructor(private readonly _params: EchoNetworkAdapterProps) { super(); } override isReady(): boolean { return this._lifecycleState === LifecycleState.OPEN; } override whenReady(): Promise { return this._ready.wait(); } override connect(peerId: PeerId, peerMetadata?: PeerMetadata | undefined): void { this.peerId = peerId; this.peerMetadata = peerMetadata; this._connected.wake(); } override send(message: Message): void { this._send(message); } override disconnect(): void { // No-op } @synchronized async open(): Promise { if (this._lifecycleState === LifecycleState.OPEN) { return; } this._lifecycleState = LifecycleState.OPEN; this._ready.wake(); } @synchronized async close(): Promise { if (this._lifecycleState === LifecycleState.CLOSED) { return this; } for (const replicator of this._replicators) { await replicator.disconnect(); } this._replicators.clear(); this._ready.reset(); this._lifecycleState = LifecycleState.CLOSED; } async whenConnected(): Promise { await this._connected.wait({ timeout: 10_000 }); } /** True while {@link _onConnectionTransportReset} is emitting for `peerId`; see that method. */ public isTransportResetting(peerId: PeerId): boolean { return this._resettingTransports.has(peerId); } public onConnectionAuthScopeChanged(peer: PeerId): void { const entry = this._connections.get(peer); if (entry) { this._onConnectionAuthScopeChanged(entry.connection); } } @synchronized async addReplicator(ctx: Context, replicator: AutomergeReplicator): Promise { invariant(this._lifecycleState === LifecycleState.OPEN); invariant(this.peerId); invariant(!this._replicators.has(replicator)); this._replicators.add(replicator); await replicator.connect(ctx, { peerId: this.peerId, onConnectionOpen: this._onConnectionOpen.bind(this), onConnectionClosed: this._onConnectionClosed.bind(this), onConnectionAuthScopeChanged: this._onConnectionAuthScopeChanged.bind(this), onConnectionTransportReset: this._onConnectionTransportReset.bind(this), isDocumentInRemoteCollection: this._params.isDocumentInRemoteCollection, getContainingSpaceForDocument: this._params.getContainingSpaceForDocument, getContainingSpaceIdForDocument: this._params.getContainingSpaceIdForDocument, }); } @synchronized async removeReplicator(replicator: AutomergeReplicator): Promise { invariant(this._lifecycleState === LifecycleState.OPEN); invariant(this._replicators.has(replicator)); await replicator.disconnect(); this._replicators.delete(replicator); } async shouldAdvertise(peerId: PeerId, params: ShouldAdvertiseProps): Promise { const connection = this._connections.get(peerId); if (!connection) { // Denies every document for the peer, so a stale peerId reads as a share-policy refusal. log.verbose('share policy probe: no connection for peer', { peerId, documentId: params.documentId }); return false; } return connection.connection.shouldAdvertise(params); } shouldSyncCollection(peerId: PeerId, params: ShouldSyncCollectionProps): boolean { const connection = this._connections.get(peerId); if (!connection) { return false; } return connection.connection.shouldSyncCollection(params); } queryCollectionState(collectionId: string, targetId: PeerId): void { const message: CollectionQueryMessage = { type: 'collection-query', senderId: this.peerId as PeerId, targetId, collectionId, }; this._send(message); } sendCollectionState(collectionId: string, targetId: PeerId, state: unknown): void { const message: CollectionStateMessage = { type: 'collection-state', senderId: this.peerId as PeerId, targetId, collectionId, state, }; this._send(message); } // TODO(dmaretskyi): Remove. getPeersInterestedInCollection(collectionId: string): PeerId[] { return Array.from(this._connections.values()) .map((connection) => { return connection.connection.shouldSyncCollection({ collectionId }) ? (connection.connection.peerId as PeerId) : null; }) .filter(isNonNullable); } private _send(message: Message): void { const connectionEntry = this._connections.get(message.targetId); if (!connectionEntry) { throw new PeerNotFoundError({ context: { peerId: message.targetId } }); } // TODO(dmaretskyi): Find a way to enforce backpressure on AM-repo. const start = Date.now(); connectionEntry.writer .write(message as ReplicatorConnectionMessage) .then(() => { this._params.monitor?.recordMessageSent(message, Date.now() - start); }) .catch((err) => { if (connectionEntry.isOpen) { log.catch(err); } this._params.monitor?.recordMessageSendingFailed(message); }); } private _onConnectionOpen(connection: AutomergeReplicatorConnection): void { log('connection opened', { peerId: connection.peerId }); invariant(!this._connections.has(connection.peerId as PeerId)); const connectionEntry: ConnectionEntry = { isOpen: true, connection, reader: connection.readable.getReader(), writer: connection.writable.getWriter(), requestedDocuments: new Set(), }; this._connections.set(connection.peerId as PeerId, connectionEntry); // Read inbound messages. queueMicrotask(async () => { try { while (true) { // TODO(dmaretskyi): Find a way to enforce backpressure on AM-repo. const { done, value } = await connectionEntry.reader.read(); if (done) { break; } this._onMessage(connectionEntry, value as Message); } } catch (err) { if (connectionEntry.isOpen) { log.catch(err); } } }); log('emit peer-candidate', { peerId: connection.peerId }); this._emitPeerCandidate(connection); this._params.monitor?.recordPeerConnected(connection.peerId); this._params.onConnectionOpen?.(); } private _onMessage(connectionEntry: ConnectionEntry, message: Message): void { const amMessage = message as ReplicatorConnectionMessage; if (amMessage.type === 'request') { this.documentRequested.emit({ documentId: amMessage.documentId as DocumentId, peerId: connectionEntry.connection.peerId as PeerId, }); } if (isCollectionQueryMessage(message)) { this._params.onCollectionStateQueried(message.collectionId, message.senderId); } else if (isCollectionStateMessage(message)) { this._params.onCollectionStateReceived(message.collectionId, message.senderId, message.state); } else { this.emit('message', message); } this._params.monitor?.recordMessageReceived(message); } private _onConnectionClosed(connection: AutomergeReplicatorConnection): void { log('connection closed', { peerId: connection.peerId }); const entry = this._connections.get(connection.peerId as PeerId); invariant(entry); entry.isOpen = false; this.emit('peer-disconnected', { peerId: connection.peerId as PeerId }); this._params.monitor?.recordPeerDisconnected(connection.peerId); void entry.writer.abort().catch((err) => log.catch(err)); void entry.reader.cancel().catch((err) => log.catch(err)); this._connections.delete(connection.peerId as PeerId); } /** * Trigger doc-synchronizer shared documents set recalculation. Happens on peer-candidate. * TODO(y): replace with a proper API call when sharePolicy update becomes supported by automerge-repo */ private _onConnectionAuthScopeChanged(connection: AutomergeReplicatorConnection): void { log('Connection auth scope changed', { peerId: connection.peerId }); const entry = this._connections.get(connection.peerId as PeerId); invariant(entry); if (this._params.onConnectionAuthScopeChanged !== 'reannounce-peer') { this._params.onConnectionAuthScopeChanged(connection.peerId as PeerId); return; } this.emit('peer-disconnected', { peerId: connection.peerId as PeerId }); this._emitPeerCandidate(connection); } /** * Re-run the peer's transport handshake without closing the connection (DX-1275). The event pair * is the only thing that drives `AdapterConnections` to rebuild a subduction transport; the mark * covers exactly this pair, since both emissions are synchronous. */ private _onConnectionTransportReset(connection: AutomergeReplicatorConnection): boolean { const peerId = connection.peerId as PeerId; const entry = this._connections.get(peerId); if (!entry?.isOpen) { log('no open connection to reset', { peerId }); return false; } log('resetting connection transport', { peerId }); this._resettingTransports.add(peerId); try { this.emit('peer-disconnected', { peerId }); this._emitPeerCandidate(connection); } finally { this._resettingTransports.delete(peerId); } return true; } private _emitPeerCandidate(connection: AutomergeReplicatorConnection): void { this.emit('peer-candidate', { peerId: connection.peerId as PeerId, peerMetadata: createEchoPeerMetadata(), }); } } export const createEchoPeerMetadata = (): PeerMetadata => ({ // TODO(dmaretskyi): Refactor this. dxos_peerSource: 'EchoNetworkAdapter', }) as any; export const isEchoPeerMetadata = (metadata: PeerMetadata): boolean => (metadata as any)?.dxos_peerSource === 'EchoNetworkAdapter';