import { Batch, Batcher, EventSubscriber, ServerMessage, VerdantInternalPresence, initialInternalPresence, } from '@verdant-web/common'; import { Context } from '../context/context.js'; import type { UserInfo } from '../index.js'; import { LocalReplicaInfo } from '../persistence/interfaces.js'; export const HANDLE_MESSAGE = Symbol('handleMessage'); export class PresenceManager< Profile = any, Presence = any, > extends EventSubscriber<{ /** * Fired when a particular peer's presence changes */ peerChanged: (userId: string, presence: UserInfo) => void; /** * Fired immediately when a change to local presence is made. This change may not * yet have been sent to the server (see: "update" event) */ selfChanged: (presence: UserInfo) => void; /** Fired when any number of peer presences have changed */ peersChanged: (peers: Record>) => void; /** Fired when a peer presence goes offline */ peerLeft: (userId: string, lastPresence: UserInfo) => void; /** Fired after local presence changes are flushed to the server. */ update: (data: { presence?: Presence; internal?: VerdantInternalPresence; }) => void; load: () => void; /** Fired on any change to a peer or the local user */ change: () => void; /** The server's in-memory presence revision was reset. */ versionReset: () => void; }> { private _peers = {} as Record>; private _self = { profile: {} } as UserInfo; // keep track of own replica IDs - applications may care if we're "alone" but with multiple devices. private _selfReplicaIds = new Set(); private _peerIds = new Array(); private presenceEpoch: string | undefined; private snapshotRevision = -1; private newerUpdates = new Map< string, { revision: number; offline: boolean; } >(); private _updateBatcher; private _updateBatch: Batch<{ presence?: Partial; internal?: Partial; }>; get self() { return this._self; } get peers() { return this._peers; } get peerIds() { return this._peerIds; } get everyone() { const everyone = { ...this._peers }; everyone[this.self.id] = this.self; return everyone; } get selfReplicaIds() { return this._selfReplicaIds; } constructor({ initialPresence, updateBatchTimeout = 200, defaultProfile, ctx, }: { initialPresence: Presence; defaultProfile: Profile; updateBatchTimeout?: number; ctx: Context; }) { super(); this.self.presence = initialPresence; this.self.profile = defaultProfile; this.self.internal = initialInternalPresence; this.self.id = ''; this.self.replicaId = ''; // set the local replica ID as soon as it's loaded ctx.waitForInitialization .then(() => ctx.meta) .then((meta) => meta.getLocalReplica()) .then((info) => { this.self.replicaId = info.id; }); this._updateBatcher = new Batcher(this.flushPresenceUpdates); this._updateBatch = this._updateBatcher.add({ max: 25, timeout: updateBatchTimeout, items: [], key: 'default', }); } /** * Decides if an update is for the local user or not. Even if it's a different replica * than the local one. * * If the replicaId matches, we use that first - we may not know the local replica's User ID yet, * e.g. on the first presence update. * * Otherwise, match the user ID to our local copy. */ private isSelf = ( localReplicaInfo: LocalReplicaInfo, userInfo: UserInfo, ) => { return ( localReplicaInfo.id === userInfo.replicaId || this._selfReplicaIds.has(userInfo.replicaId) || this._self.id === userInfo.id ); }; [HANDLE_MESSAGE] = async ( localReplicaInfo: LocalReplicaInfo, message: ServerMessage, ) => { let peersChanged = false; let selfChanged = false; const peerIdsSet = new Set(this.peerIds); let peerSnapshot = message.type === 'sync-resp' || (message.type === 'server-ack' && message.peerPresence) ? message.peerPresence : undefined; const version = message.type === 'presence-changed' || message.type === 'presence-offline' || message.type === 'sync-resp' || message.type === 'server-ack' ? message.presenceVersion : undefined; if (version) { if (this.presenceEpoch !== version.epoch) { const hadEpoch = this.presenceEpoch !== undefined; this.presenceEpoch = version.epoch; this.snapshotRevision = -1; this.newerUpdates.clear(); if (hadEpoch) this.emit('versionReset'); } if (peerSnapshot) { if (version.revision < this.snapshotRevision) return; this.snapshotRevision = version.revision; peerSnapshot = { ...peerSnapshot }; for (const [userId, update] of this.newerUpdates) { if (update.revision <= version.revision) { this.newerUpdates.delete(userId); } else if (update.offline) { delete peerSnapshot[userId]; } else if (userId === this._self.id) { peerSnapshot[userId] = this._self; } else if (this._peers[userId]) { peerSnapshot[userId] = this._peers[userId]; } } } else if ( message.type === 'presence-changed' || message.type === 'presence-offline' ) { const userId = message.type === 'presence-changed' ? message.userInfo.id : message.userId; if ( version.revision <= this.snapshotRevision || version.revision <= (this.newerUpdates.get(userId)?.revision ?? -1) ) { return; } this.newerUpdates.set(userId, { revision: version.revision, offline: message.type === 'presence-offline', }); } } else if ( peerSnapshot || message.type === 'presence-changed' || message.type === 'presence-offline' ) { // Unversioned messages can replace state that the revision metadata describes. this.snapshotRevision = -1; this.newerUpdates.clear(); } if (message.type === 'presence-changed') { if (this.isSelf(localReplicaInfo, message.userInfo)) { this.updateSelf(localReplicaInfo, message.userInfo); selfChanged = true; } else { peerIdsSet.add(message.userInfo.id); this._peers[message.userInfo.id] = message.userInfo; peersChanged = true; this.emit('peerChanged', message.userInfo.id, message.userInfo); } } else if (peerSnapshot) { // reset to provided presence data, which includes all peers. const previousPeerIds = this._peerIds; this._peers = {}; peerIdsSet.clear(); for (const [id, userInfo] of Object.entries(peerSnapshot)) { if (this.isSelf(localReplicaInfo, userInfo)) { this.updateSelf(localReplicaInfo, userInfo); selfChanged = true; } else { peersChanged = true; peerIdsSet.add(id); this._peers[id] = userInfo; this.emit('peerChanged', id, userInfo); } } // also notify when peers have all left if (previousPeerIds.length !== peerIdsSet.size) { peersChanged = true; } } else if (message.type === 'presence-offline') { peerIdsSet.delete(message.userId); const lastPresence = this._peers[message.userId]; delete this._peers[message.userId]; peersChanged = true; this.emit('peerLeft', message.userId, lastPresence); } if (peersChanged) { // important that this stays sorted to keep stable order, don't want // peers swapping around. this._peerIds = Array.from(peerIdsSet).sort(); this.emit('peersChanged', this._peers); } if (peersChanged || selfChanged) { this.emit('change'); } }; private updateSelf = ( localReplicaInfo: LocalReplicaInfo, userInfo: UserInfo, ) => { this._self = userInfo; if (userInfo.replicaIds) { // the server reports the full set of this user's active replicas, // so replace rather than accumulate; that way replicas which go // away are forgotten. this._selfReplicaIds = new Set([ localReplicaInfo.id, ...userInfo.replicaIds, ]); } else { this._selfReplicaIds.add(userInfo.replicaId); } this.emit('selfChanged', userInfo); }; update = async (presence: Partial) => { this._updateBatch.update({ items: [{ presence }], }); // proactively update the local presence this.self.presence = { ...this.self.presence, ...presence }; this.emit('selfChanged', this.self); this.emit('change'); }; flushPresenceUpdates = ( presenceUpdates: { presence?: Partial; internal?: Partial; }[], ) => { const data = { presence: this.self.presence, internal: this.self.internal, }; for (const update of presenceUpdates) { if (update.presence) { Object.assign(data.presence as any, update.presence); } if (update.internal) { Object.assign(data.internal, update.internal); } } this.emit('update', data); }; setViewId = (viewId: string | undefined) => { this._updateBatch.update({ items: [{ internal: { viewId } }], }); this.self.internal.viewId = viewId; this.emit('selfChanged', this.self); this.emit('change'); }; setFieldId = (fieldId: string | undefined, timestamp = Date.now()) => { this._updateBatch.update({ items: [ { internal: { lastFieldId: fieldId, lastFieldTimestamp: timestamp } }, ], }); this.self.internal.lastFieldId = fieldId; this.emit('selfChanged', this.self); this.emit('change'); }; /** * Get all peers that are in the same view as the local user. */ getViewPeers = () => { return ( this._peerIds .map((id) => this._peers[id]) // undefined view matches all peers. otherwise, // filter to only those in the same view. .filter( (peer) => this.self.internal.viewId === undefined || peer.internal.viewId === this.self.internal.viewId, ) ); }; /** * Get all peers that have interacted with the specified * field most recently. */ getFieldPeers = (fieldId: string, expirationPeriod = 60 * 1000) => { return this._peerIds .map((id) => this._peers[id]) .filter( (peer) => peer.internal.lastFieldId === fieldId && Date.now() - peer.internal.lastFieldTimestamp! < expirationPeriod, ); }; }