// // Copyright 2024 DXOS.org // import * as EffectContext from 'effect/Context'; import * as Layer from 'effect/Layer'; import { type Context } from '@dxos/context'; import { type CollectionId } from '@dxos/echo-protocol'; import { invariant } from '@dxos/invariant'; import { PublicKey, type SpaceId } from '@dxos/keys'; import { log } from '@dxos/log'; import type * as TeleportAutomergeReplicator from '@dxos/teleport-extension-automerge-replicator'; import { ComplexSet, defaultMap } from '@dxos/util'; import { type AutomergeReplicator, type AutomergeReplicatorContext, type ShouldAdvertiseProps, } from './echo-replicator.ts'; import { MeshReplicatorConnection } from './mesh-echo-replicator-connection.ts'; import { getSpaceIdFromCollectionId } from './space-collection.ts'; // TODO(dmaretskyi): Move out of @dxos/echo-host. /** * Used to replicate with other peers over the network. */ export class MeshEchoReplicator implements AutomergeReplicator { /** * We might have multiple connections open with a peer (one per space), but there'll be only one enabled * connection at any given moment, because there's a single repo for all the spaces. * When a connection closes (space was closed) it gets removed from the list and the next connection * in the line gets enabled. */ private readonly _connectionsPerPeer = new Map(); /** * A set of all connections (enabled and disabled). */ private readonly _connections = new Set(); /** * spaceId -> deviceKey[] */ private readonly _authorizedDevices = new Map>(); private _context: AutomergeReplicatorContext | null = null; async connect(_ctx: Context, context: AutomergeReplicatorContext): Promise { this._context = context; } async disconnect(): Promise { for (const connection of this._connections) { if (connection.isEnabled) { this._context?.onConnectionClosed(connection); } } for (const connection of this._connections) { await connection.close(); } this._connections.clear(); this._connectionsPerPeer.clear(); this._context = null; } createExtension( extensionFactory?: TeleportAutomergeReplicator.AutomergeReplicatorFactory, ): TeleportAutomergeReplicator.AutomergeReplicator { invariant(this._context); const connection: MeshReplicatorConnection = new MeshReplicatorConnection({ ownPeerId: this._context.peerId, replicatorFactory: extensionFactory, onRemoteConnected: async () => { log('onRemoteConnected', { peerId: connection.peerId }); invariant(this._context); const existingConnections = this._connectionsPerPeer.get(connection.peerId); if (existingConnections?.length) { const enabledConnection = existingConnections[0]; this._context.onConnectionAuthScopeChanged(enabledConnection); existingConnections.push(connection); } else { this._connectionsPerPeer.set(connection.peerId, [connection]); this._context.onConnectionOpen(connection); connection.enable(); } }, onRemoteDisconnected: async () => { log('onRemoteDisconnected', { peerId: connection.peerId }); this._connections.delete(connection); const existingConnections = this._connectionsPerPeer.get(connection.peerId) ?? []; const index = existingConnections.indexOf(connection); if (index < 0) { log.warn('disconnected connection not found', { peerId: connection.peerId }); return; } existingConnections.splice(index, 1); // A closed connection's extension is destroyed, so promoting it would hand the adapter a peer // it can never write to (DX-1279). const liveConnections = existingConnections.filter((candidate) => !candidate.isClosed); this._connectionsPerPeer.set(connection.peerId, liveConnections); if (connection.isEnabled) { this._context?.onConnectionClosed(connection); connection.disable(); // Promote the next connection to enabled if (liveConnections.length > 0) { this._context?.onConnectionOpen(liveConnections[0]); liveConnections[0].enable(); } } }, shouldAdvertise: async (params: ShouldAdvertiseProps) => { log('shouldAdvertise', { peerId: connection.peerId, documentId: params.documentId }); invariant(this._context); try { // Resolve space membership via `getContainingSpaceIdForDocument`, which answers from the // local collection state (the space root's document list) and so still identifies a doc // the node owns whose handle is evicted or still loading. const spaceId = await this._context.getContainingSpaceIdForDocument(params.documentId); if (!spaceId) { const remoteDocumentExists = await this._context.isDocumentInRemoteCollection({ documentId: params.documentId, peerId: connection.peerId, }); log('document not found locally for share policy check', { peerId: connection.peerId, documentId: params.documentId, acceptDocument: remoteDocumentExists, }); // If a document is not present locally return true if another peer claims to have it. // Simply returning true will add the peer to "generous peers list" for this document which will // start replication of the document after we receive, even if the peer is not in the corresponding space. return remoteDocumentExists; } const authorizedDevices = this._authorizedDevices.get(spaceId); if (!connection.remoteDeviceKey) { log('device key not found for share policy check', { peerId: connection.peerId, documentId: params.documentId, }); return false; } const isAuthorized = authorizedDevices?.has(connection.remoteDeviceKey) ?? false; log('share policy check', { localPeer: this._context.peerId, remotePeer: connection.peerId, documentId: params.documentId, deviceKey: connection.remoteDeviceKey, spaceId, isAuthorized, }); return isAuthorized; } catch (err) { log.catch(err); return false; } }, shouldSyncCollection: ({ collectionId }) => { const spaceId = getSpaceIdFromCollectionId(collectionId as CollectionId); const authorizedDevices = this._authorizedDevices.get(spaceId); if (!connection.remoteDeviceKey) { log('device key not found for collection sync check', { peerId: connection.peerId, collectionId, }); return false; } const isAuthorized = authorizedDevices?.has(connection.remoteDeviceKey) ?? false; return isAuthorized; }, }); this._connections.add(connection); return connection.replicatorExtension; } /** * Takes a space id rather than a key: a root-anchored space's id is not derivable from its key, so * deriving here would record the authorization under an id no document belongs to. */ async authorizeDevice(spaceId: SpaceId, deviceKey: PublicKey): Promise { log('authorizeDevice', { spaceId, deviceKey }); defaultMap(this._authorizedDevices, spaceId, () => new ComplexSet(PublicKey.hash)).add(deviceKey); for (const connection of this._connections) { if (connection.isEnabled && connection.remoteDeviceKey && connection.remoteDeviceKey.equals(deviceKey)) { if (this._connectionsPerPeer.has(connection.peerId)) { this._context?.onConnectionAuthScopeChanged(connection); } } } } } /** * Effect service tag for {@link MeshEchoReplicator}. * * Distinct from the generic {@link AutomergeReplicatorService} because `DataSpaceManager` drives * mesh-specific hooks (`authorizeDevice`, `createExtension`) not present on the base interface. */ export class MeshEchoReplicatorService extends EffectContext.Service()( '@dxos/echo-host/MeshEchoReplicator', ) {} /** * Effect Layer constructing a {@link MeshEchoReplicator}. */ export const MeshEchoReplicatorLayer = (): Layer.Layer => Layer.succeed(MeshEchoReplicatorService, new MeshEchoReplicator());