import { PeerState } from "./PeerState.js"; import { SyncStateManager } from "./SyncStateManager.js"; import { UnsyncedCoValuesTracker } from "./UnsyncedCoValuesTracker.js"; import { CoValueHeader, Transaction } from "./coValueCore/verifiedState.js"; import { Signature } from "./crypto/crypto.js"; import { RawCoID, SessionID } from "./ids.js"; import { LocalNode } from "./localNode.js"; import { CoValuePriority } from "./priority.js"; import { IncomingMessagesQueue } from "./queue/IncomingMessagesQueue.js"; import { CoValueKnownState, KnownStateSessions } from "./knownState.js"; import { StorageAPI } from "./storage/index.js"; export type SyncMessage = LoadMessage | KnownStateMessage | NewContentMessage | DoneMessage | ReconcileMessage | ReconcileAckMessage; export type LoadMessage = { action: "load"; } & CoValueKnownState; export type KnownStateMessage = { action: "known"; isCorrection?: boolean; asDependencyOf?: RawCoID; } & CoValueKnownState; export type LocalStoreDurabilityListener = (hasPending: boolean, sessionID: SessionID) => void; export type NewContentMessage = { action: "content"; id: RawCoID; header?: CoValueHeader; priority: CoValuePriority; new: { [sessionID: SessionID]: SessionNewContent; }; expectContentUntil?: KnownStateSessions; }; export type SessionNewContent = { after: number; newTransactions: Transaction[]; lastSignature: Signature; }; export type DoneMessage = { action: "done"; id: RawCoID; }; export type ReconcileBatchID = string; export type ReconcileMessage = { action: "reconcile"; id: ReconcileBatchID; values: [coValue: RawCoID, sessionsHash: string][]; }; export type ReconcileAckMessage = { action: "reconcile-ack"; id: ReconcileBatchID; }; /** * Determines when network sync is enabled. * - "always": sync is enabled for both Anonymous Authentication and Authenticated Account * - "signedUp": sync is enabled when the user is authenticated * - "never": sync is disabled, content stays local * Can be dynamically modified to control sync behavior at runtime. */ export type SyncWhen = "always" | "signedUp" | "never"; export type PeerID = string; export type DisconnectedError = "Disconnected"; export interface IncomingPeerChannel { close: () => void; onMessage: (callback: (msg: SyncMessage | DisconnectedError) => void) => void; onClose: (callback: () => void) => void; } export interface OutgoingPeerChannel { push: (msg: SyncMessage | DisconnectedError) => void; close: () => void; onClose: (callback: () => void) => void; } export interface Peer { id: PeerID; incoming: IncomingPeerChannel; outgoing: OutgoingPeerChannel; role: "server" | "client"; priority?: number; persistent?: boolean; } export type ServerPeerSelector = (id: RawCoID, serverPeers: PeerState[]) => PeerState[]; /** * Manages the sync of coValues between peers. * It is responsible for sending, receiving and processing sync messages. * For more details on how the sync protocol works, see the sync protocol documentation: * {@link docs/sync-protocol.md} */ export declare class SyncManager { #private; peers: { [key: PeerID]: PeerState; }; local: LocalNode; /** * Tracks pending reconcile acks from the server. */ private reconciliationAckTracker; /** * Tracks ongoing storage reconciliation batches in a server. */ private ongoingStorageReconciliationTracker; get pendingReconciliationAck(): Map; private skipVerify; private _ignoreUnknownCoValuesFromServers; ignoreUnknownCoValuesFromServers(): void; fullStorageReconciliationEnabled: boolean; peersCounter: import("@opentelemetry/api").UpDownCounter; private transactionsSizeHistogram; serverPeerSelector?: ServerPeerSelector; constructor(local: LocalNode); syncState: SyncStateManager; unsyncedTracker: UnsyncedCoValuesTracker; disableTransactionVerification(): void; getPeers(id: RawCoID): PeerState[]; getClientPeers(): PeerState[]; getServerPeers(id: RawCoID, excludePeerId?: PeerID): PeerState[]; getPersistentServerPeers(id: RawCoID): PeerState[]; handleSyncMessage(msg: SyncMessage, peer: PeerState): void; sendNewContent(id: RawCoID, peer: PeerState, forceKnownReplyOnNoDelta?: boolean): void; /** * Reconciles all in-memory CoValues with all persistent server peers */ reconcileServerPeers(): void; /** * Ensures all CoValues in storage are synced to the given server peer. * Sends "reconcile" message(s) with [coValueId, sessionsHash] for each CoValue. * Server responds with "known" only where it is missing the CoValue or has different sessions, * so that client can send missing content. * Processes CoValues in batches of RECONCILIATION_BATCH_SIZE. * @param peer - The server peer to reconcile with. * @param initialOffset - Offset to start from (for resuming after interrupt). Default 0. * @param onComplete - Called when reconciliation is fully complete (all batches sent and acked). */ startStorageReconciliation(peer: PeerState, initialOffset?: number, onComplete?: () => void): void; private buildStorageReconciliationEntries; private maybeStartStorageReconciliationForPeer; resumeUnsyncedCoValues(): Promise; /** * Reconciles all in-memory CoValues with the given peer. * Creates a subscription for each CoValue that is not already subscribed to. */ startPeerReconciliation(peer: PeerState): void; messagesQueue: IncomingMessagesQueue; private processing; pushMessage(incoming: SyncMessage, peer: PeerState): void; /** * Get the storage streaming queue if available. * Returns undefined if storage doesn't have a streaming queue. */ private getStorageStreamingQueue; /** * Unified queue processing that coordinates both incoming messages * and storage streaming entries. * * Processes items from both queues with priority ordering: * - Incoming messages are processed via round-robin across peers * - Storage streaming entries are processed by priority (MEDIUM before LOW) * * Implements time budget scheduling to avoid blocking the main thread. */ private processQueues; addPeer(peer: Peer, skipReconciliation?: boolean): void; removePeer(peerId: PeerID): void; trySendToPeer(peer: PeerState, msg: SyncMessage): void; /** * Handles the load message from a peer. * * Differences with the known state message: * - The load message triggers the CoValue loading process on the other peer * - The peer known state is stored as-is instead of being merged * - The load message always replies with a known state message */ handleLoad(msg: LoadMessage, peer: PeerState): void; /** * Helper to load from storage and respond appropriately. * Falls back to peers if not found in storage. */ private loadFromStorageAndRespond; /** * Helper to load from peers and respond appropriately. */ private loadFromPeersAndRespond; /** * Handle case when CoValue is not found. */ private handleLoadNotFound; /** * Request full content from a peer when we don't have the CoValue. */ private requestFullContent; handleKnownState(msg: KnownStateMessage, peer: PeerState): void; handleReconcile(msg: ReconcileMessage, peer: PeerState): void; handleReconcileAck(msg: ReconcileAckMessage, peer: PeerState): void; private hashKnownStateSessions; recordTransactionsSize(newTransactions: Transaction[], source: string): void; handleNewContent(msg: NewContentMessage, from: PeerState | "storage" | "import"): void; handleCorrection(msg: KnownStateMessage, peer: PeerState): void; private maybeMarkCoValueAsReconciled; private syncQueue; syncLocalTransaction: (coValue: import("./coValueCore/verifiedState.js").VerifiedState, knownStateBefore: CoValueKnownState) => void; trackDirtyCoValues: () => { done: () => Set<`co_z${string}`>; }; /** * Tracks locally-created content that has been handed to async storage but * is not yet durably stored. If such content is also sent to a peer and the * process crashes before the write completes, local storage ends up behind * what the server received for this session — reusing the session after * restart would then fork its hash chain. The listener lets the platform * layer mark the session as unsafe to reuse while that window is open. * * With synchronous storage the store completes inline, the counter is back * to 0 before any send, and the listener never fires. * * Exceptions thrown by the listener are caught and logged so they can't * disrupt the sync/store flow. */ onLocalStoreDurabilityChange?: LocalStoreDurabilityListener; private pendingLocalStores; private localStoreDurabilityWindowOpen; private emitLocalStoreDurabilityChange; private handleLocalStoreDone; private openLocalStoreDurabilityWindow; syncContent(content: NewContentMessage): void; private trackSyncState; private storeContent; /** * Returns true if the local CoValue changes have been synced to all persistent server peers. * * Used during garbage collection to determine if the coValue is pending sync. */ isSyncedToServerPeers(id: RawCoID): boolean; waitForSyncWithPeer(peerId: PeerID, id: RawCoID, timeout: number): Promise | undefined; waitForStorageSync(id: RawCoID): Promise | undefined; waitForSync(id: RawCoID, timeout?: number): Promise; waitForAllCoValuesSync(timeout?: number): Promise; setStorage(storage: StorageAPI): void; removeStorage(): void; /** * Closes all the peer connections and ensures the list of unsynced coValues is persisted to storage. * @returns Promise of the current pending store operation, if any. */ gracefulShutdown(): Promise | undefined; } /** * Returns a ServerPeerSelector that implements the Highest Weighted Random (HWR) algorithm. * * The HWR algorithm deterministically selects the top `n` peers for a given CoValue ID by assigning * each peer a "weight" based on the MD5 hash of the concatenation of the CoValue ID and the peer's ID. * The first 4 bytes of the hash are interpreted as a 32-bit unsigned integer, which serves as the peer's weight. * Peers are then sorted in descending order of weight, and the top `n` are selected. */ export declare function hwrServerPeerSelector(n: number): ServerPeerSelector; //# sourceMappingURL=sync.d.ts.map