import { extractErrorMsg, getUUID, // so our uuid's are uniform across all ibgib code getTimestamp, // so our timestamp strings are uniform pretty, clone, delay, } from "@ibgib/helper-gib/dist/helpers/utils-helper.mjs"; import { getIbGibAddr } from "@ibgib/ts-gib/dist/helper.mjs"; import { Factory_V1 } from "@ibgib/ts-gib/dist/V1/factory.mjs"; import { IbGib_V1, } from "@ibgib/ts-gib/dist/V1/types.mjs"; import { IbGibAddr } from "@ibgib/ts-gib/dist/types.mjs"; import { validateIbGibIntrinsically } from "@ibgib/ts-gib/dist/V1/validate-helper.mjs"; import { GLOBAL_LOG_A_LOT } from "../core-constants.mjs"; import { IbGibSpaceAny } from "../witness/space/space-base-v1.mjs"; import { putInSpace, getLatestAddrs, getFromSpace, registerNewIbGib } from "../witness/space/space-helper.mjs"; import { MetaspaceService } from "../witness/space/metaspace/metaspace-types.mjs"; import { SyncStage, SYNC_ATOM, SYNC_MSG_REL8N_NAME, SYNC_SAGA_PAYLOAD_ADDRS_DOMAIN, SyncConflictStrategy, SYNC_CONFLICT_STRATEGY_VALID_VALUES, } from "./sync-constants.mjs"; import { GraftPreference } from "./graft-info/graft-info-types.mjs"; import { appendToTimeline, createTimeline, getHistory, getHistoryAddrs, Rel8nInfo, Rel8nRemovalInfo } from "../timeline/timeline-api.mjs"; import { SyncData_V1, SyncIbGib_V1, SyncMode, SyncRel8ns_V1, DomainIbGibAnalysisInfo, NextSagaFrameInfo, HandleSagaResponseContextResult, SyncSagaFrameDependencyGraph, SyncSenderIdentityInfo, SnapshotSyncManifest, SyncDomainAdapter, } from "./sync-types.mjs"; import { getSyncSagaFrameOrigin, getFullSyncSagaHistory, getSyncIb, getTempSpaceName, createInMemoryTempSpace, isPastFrame, putInSpace_dnasThenNonDnas, validateFullSyncSagaHistory, getAllOrphanedAddresses, getFinalConflictsInfo, getSyncSagaFrameDependencyGraph } from "./sync-helpers.mjs"; import { getDeltaDependencyGraph, getDependencyGraph, toFlatGraph } from "../common/other/graph-helper.mjs"; import { SyncSagaMessageData_V1, SyncSagaMessageInitData_V1, SyncSagaMessageAckData_V1, SyncSagaMessageDeltaData_V1, SyncSagaMessageCommitData_V1, SyncSagaConflictInfo, SyncSagaPushOfferInfo, SyncSagaRequestAddrInfo, SyncSagaMessageRel8ns_V1, } from "./sync-saga-message/sync-saga-message-types.mjs"; import { getSyncSagaMessageIb } from "./sync-saga-message/sync-saga-message-helpers.mjs"; import { SYNC_SAGA_MSG_ATOM } from "./sync-saga-message/sync-saga-message-constants.mjs"; import { SyncSagaInfo } from "./sync-types.mjs"; import { splitPerTjpAndOrDna, getTimelinesGroupedByTjp, isIbGib, getIbGibsFromCache_fallbackToSpaces, toDto, getTjpAddr } from "../common/other/ibgib-helper.mjs"; import { SyncPeerWitness } from "./sync-peer/sync-peer-types.mjs"; import { SyncSagaContextData_V1, SyncSagaContextIbGib_V1, SyncSagaContextRel8ns_V1, } from "./sync-saga-context/sync-saga-context-types.mjs"; import { getSyncSagaContextIb, validateContextAndSagaFrame } from "./sync-saga-context/sync-saga-context-helpers.mjs"; import { newupSubject, } from "../common/pubsub/subject/subject-helper.mjs"; import { SubjectWitness } from "../common/pubsub/subject/subject-types.mjs"; import { getSyncSagaMessageFromFrame } from "./sync-saga-message/sync-saga-message-helpers.mjs"; import { fnObs } from "../common/pubsub/observer/observer-helper.mjs"; import { ErrorIbGib_V1 } from "../common/error/error-types.mjs"; import { IbGibSpaceResultData, IbGibSpaceResultIbGib, IbGibSpaceResultRel8ns } from "../witness/space/space-types.mjs"; import { FlatIbGibGraph } from "../common/other/graph-types.mjs"; import { GRAFT_INFO_REL8N_NAME } from "./graft-info/graft-info-constants.mjs"; import { GraftInfoIbGib_V1 } from "./graft-info/graft-info-types.mjs"; import { SYNC_SAGA_CONTEXT_ATOM } from "./sync-saga-context/sync-saga-context-constants.mjs"; import { KeystoneIbGib_V1 } from "../keystone/keystone-types.mjs"; import { isKeystone } from "../keystone/keystone-helpers.mjs"; import { createStandardPoolConfig } from "../keystone/keystone-config-builder.mjs"; import { POOL_ID_CONNECT, POOL_ID_SYNC, KEYSTONE_VERB_CONNECT, KEYSTONE_VERB_SYNC } from "../keystone/keystone-constants.mjs"; import { KeystonePoolConfig, KeystoneReplenishStrategy } from "../keystone/keystone-types.mjs"; import { SyncPeer_V1 } from "./sync-peer/sync-peer-v1.mjs"; import { GraftStrategyService } from "./graft-info/graft-strategy-service.mjs"; import { startPerfTimer } from "../common/perf/perf-timer.mjs"; import { B2TFS_CHILD_ITEM_REL8N_NAME } from "../cosmology/branching/item/item-types.mjs"; import { getCosmosByName } from "../cosmology/cosmos/cosmos-helpers.mjs"; import { parseSpaceQualifiedIbGibAddr, getIbGibFromSpace } from "../common/other/ibgib-helper.mjs"; import { getBranchInfoFromGalaxy } from "../cosmology/branching/branch/branch-helpers.mjs"; import { getLatestBranchSnapshot } from "../cosmology/branching/snapshot/snapshot-helpers.mjs"; import { diffSnapshotTrees } from "../cosmology/branching/snapshot/diff-snapshot-trees.mjs"; import { B2tFSBranchIbGib_V1 } from "../cosmology/branching/branch/branch-types.mjs"; const logalot = GLOBAL_LOG_A_LOT; const logalotControlDomain = false; const lcControlDomain = '[ControlDomain]'; /** * Orchestrates the synchronization process between two spaces (Source and Destination). * * ## Execution Contexts * * The methods in this class are designed to be run on specific nodes in the sync topology: * * * **Sender/Local Node**: The node *initiating* the sync (calling `sync()`). * * **Receiver/Remote Node**: The node *accepting* the sync request (the Peer). * * Note that in a peer-to-peer architecture, "Sender" and "Receiver" are roles * relative to a specific Saga, not fixed node ids. */ export class SyncSagaCoordinator { private lc: string = `[${SyncSagaCoordinator.name}]`; private currentAccelerationHint?: SnapshotSyncManifest; private currentAdapter?: SyncDomainAdapter; public latestSagaFrame?: SyncIbGib_V1; constructor() { } /** * Default pool config for the session keystone's `connect` pool. * Consumed exactly once per saga during `peer.connect()`. * Uses `deleteAll` replenish strategy — after the handshake, the pool is gone. * * Override in subclasses or pass custom config via opts to change security parameters. */ protected defaultSessionConnectPoolConfig(): KeystonePoolConfig { return createStandardPoolConfig({ id: POOL_ID_CONNECT, salt: `session-connect-${Date.now()}`, verbs: [KEYSTONE_VERB_CONNECT], size: 20, sequential: 2, random: 2, targetBinding: 0, replenishStrategy: KeystoneReplenishStrategy.deleteAll, }); } /** * Default pool config for the session keystone's per-turn `sync` pool. * Used on each outgoing context frame (Init, Delta, Commit). * Uses `topUp` replenish strategy to stay active throughout the saga. * * Override in subclasses or pass custom config via opts to change security parameters. */ protected defaultSessionSyncPoolConfig(): KeystonePoolConfig { return createStandardPoolConfig({ id: POOL_ID_SYNC, salt: `session-sync-${Date.now()}`, verbs: [KEYSTONE_VERB_SYNC], size: 200, sequential: 3, random: 3, targetBinding: 3, replenishStrategy: KeystoneReplenishStrategy.topUp, }); } /** * Executes a synchronization saga using the Symmetric Sync Protocol. * * @remarks * **Execution Context**: **Sender (Local)**. * This method is the entry point for starting a sync saga. */ public async sync({ peer, domainIbGibs, domainAddrs, mode = SyncMode.sync, senderIdentityInfo, fnSenderSecret, conflictStrategy = SyncConflictStrategy.abort, graftPreference, metaspace, controlSpace, domainSpace, targetSpaceInfo, useInMemoryTempSpace, accelerationHint, adapter, }: { /** * The peer we are syncing with. */ peer: SyncPeerWitness; /** * The primary ibgibs we wish to sync. The dependency ibgibs will be * automatically included as needed for sync. * * These should all exist in {@link domainSpace} */ domainIbGibs?: IbGib_V1[], domainAddrs?: string[], mode?: SyncMode, /** * Optional structure containing both the sender's delegate identity (Alice's device key) * and the parent root Domain Identity address (senderDomainAddr). * * NOTE: {@link fnSenderSecret} must be truthy if this is truthy, and vice versa. */ senderIdentityInfo?: SyncSenderIdentityInfo, /** * secret corresponding to {@link senderIdentityInfo.senderIdentity}. * * NOTE: {@link senderIdentityInfo} must be truthy if this is truthy, and vice versa. */ fnSenderSecret?: () => Promise; /** * Durable control space containing sync saga control/audit stones (`SyncIbGib_V1`, * `SyncSagaMessageIbGib_V1`, `SyncSagaContextIbGib_V1`) and identity/session * keystones ($I_{primary}$, $I_{sync}$, $S$). */ controlSpace: IbGibSpaceAny; /** * Durable domain space containing the {@link domainIbGibs} we want to sync. If * sync is successful, any updates to domain timelines will be stored here. */ domainSpace: IbGibSpaceAny; /** * The metaspace context (for registering sync sagas locally). */ metaspace: MetaspaceService; /** * How to handle conflicts when both Source and Dest have diverged on the * same timeline. * * defaults to {@link SyncConflictStrategy.abort} */ conflictStrategy?: SyncConflictStrategy; /** * General endpoint preference for resolving graft conflicts (receiver, sender, or timestamp). */ graftPreference?: GraftPreference; /** * Optional destination space coordinates / transport info captured * on the root frame for permanent audit logging. */ targetSpaceInfo?: SyncData_V1['targetSpaceInfo']; /** * Whether to use an in-memory scratch space for staging sync payload ibgibs. * Defaults to true for maximal speed. If false and metaspace is available, * creates a disk-backed local space. */ useInMemoryTempSpace?: boolean; /** * Optional intermediate snapshot sync manifest to accelerate gap analysis * during VCS branch synchronization. */ accelerationHint?: SnapshotSyncManifest; /** * Optional domain adapter (e.g. B2tFSSnapshotSyncAdapter) to accelerate * domain analysis and fast-forward delta payload calculations. */ adapter?: SyncDomainAdapter; }): Promise { const lc = `${this.lc}[${this.sync.name}]`; this.currentAccelerationHint = accelerationHint; this.currentAdapter = adapter; if (logalot) { console.log(`${lc} starting...`); } if (!controlSpace) { throw new Error(`${lc} controlSpace required (E: 84a129f0b3c84e1298d76e18c34b2826)`); } if (!domainSpace) { throw new Error(`${lc} domainSpace required (E: 25df3761f7686a1099a552f83c95d326)`); } if (senderIdentityInfo || fnSenderSecret) { if (!senderIdentityInfo) { throw new Error(`(UNEXPECTED) senderIdentityInfo falsy but fnSenderSecret truthy? if either is used, both must be truthy. (E: e366628a4919c7d727d2cbd8e5b75e26)`); } if (!fnSenderSecret) { throw new Error(`(UNEXPECTED) fnSenderSecret falsy but senderIdentityInfo truthy? if either is used, both must be truthy. (E: 7d55ce37ae482fec48e3398158161926)`); } const { senderIdentity, senderDomainAddr } = senderIdentityInfo; if (!senderIdentity) { throw new Error(`(UNEXPECTED) senderIdentity falsy in senderIdentityInfo? if senderIdentityInfo is provided, both senderIdentity and senderDomainAddr must be truthy. (E: d09428a277a5dbcfeb611d5a421ec273)`); } if (!senderDomainAddr) { throw new Error(`(UNEXPECTED) senderDomainAddr falsy in senderIdentityInfo? if senderIdentityInfo is provided, both senderIdentity and senderDomainAddr must be truthy. (E: d7085135b2b5d9cfe5db11c3fa8de005)`); } } const { senderIdentity, senderDomainAddr } = senderIdentityInfo ?? {}; // 1. SETUP SAGA METADATA const sagaId = await getUUID(); const sagaTimer = startPerfTimer(`[sync-saga][${sagaId.slice(0, 8)}]`); // Setup Observable & Promise // const updates$ = new Subject_V1(); const updates$ = await newupSubject(); if (!updates$.next) { throw new Error(`(UNEXPECTED) updates$.next falsy? (E: d24cd82184aec130c89a320819b39126)`); } let resolveDone!: () => void; let rejectDone!: (err: any) => void; const done = new Promise((resolve, reject) => { resolveDone = resolve; rejectDone = reject; }); // WORKING CONTEXT (Transactional Scratch Space) const inMemory = useInMemoryTempSpace ?? true; let tempSpace: IbGibSpaceAny; if (inMemory) { tempSpace = await createInMemoryTempSpace(); } else { const diskSpace = await metaspace.createNewLocalSpace({ opts: { allowCancel: false, spaceName: `tmp_sync_${sagaId.slice(0, 8)}`, getFnPrompt: metaspace.getFnPrompt!, logalot } }); if (!diskSpace) { throw new Error(`couldn't create a temp space (E: e563c639556247c4baedcfd2cfbfa993)`); } await diskSpace.initialized; tempSpace = diskSpace; } sagaTimer.mark('0.createTempSpace'); const cleanup = async () => { // temp space cleanup if applicable }; // Async execution wrapper (async () => { try { const targetAddrs = domainAddrs ?? (domainIbGibs && domainIbGibs.length > 0 ? domainIbGibs.map(domain => getIbGibAddr({ ibGib: domain })) : undefined); // Attach saga-scoped identity opts to peer now that sagaId is known. peer.setOptionalOpts({ sagaId, senderIdentity, senderDomainAddr, fnSenderSecret, sessionConnectPoolConfig: this.defaultSessionConnectPoolConfig(), sessionSyncPoolConfig: this.defaultSessionSyncPoolConfig(), targetAddrs, } as any); // ESTABLISH SESSION IDENTITY (pre-connect, if identity provided) await peer.establishSessionIdentity(); if (senderIdentityInfo && peer.currentSenderIdentity) { senderIdentityInfo.senderIdentity = peer.currentSenderIdentity; } // CONNECT PEER (if needed) await peer.connect({ sagaId }); sagaTimer.mark('1.peerConnect'); // CREATE INITIAL FRAME (Stage.init) const { initFrame, initDomainGraph } = await this.createInitFrame({ sagaId, domainIbGibs: domainIbGibs ?? [], domainAddrs, mode, conflictStrategy, graftPreference, targetSpaceInfo, metaspace, controlSpace, domainSpace, tempSpace, peer, }); sagaTimer.mark('2.createInitFrame'); // KICK OFF THE PING-PONG SAGA LOOP (FSM) await this.executeSagaLoop({ initFrame, initDomainGraph, peer, updates$, controlSpace, domainSpace, tempSpace, metaspace }); sagaTimer.mark('3.executeSagaLoop'); resolveDone(); if (!updates$.complete) { throw new Error(`(UNEXPECTED) updates$.complete falsy? (E: d24cd82184aec130c89a320819b39126)`); } updates$.complete(); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); rejectDone(error); if (!updates$.error) { throw new Error(`(UNEXPECTED) updates$.error falsy? (E: 392ce77c073272e4c398c3e86583ce26)`); } updates$.error(error); } finally { sagaTimer.stop(); await cleanup(); } })(); return { sagaId, updates$, done }; } /** * Executes a strictly read-only clone / pull operation against a remote target domain. * * Invariants guaranteed: * 1. Zero writes to the target domain's space (Alice's space). * 2. Complete DoS isolation: SyncSaga audit logs are written exclusively to caller's controlSpace (Bob's local space). * 3. Target snapshot address is pinned at start. */ public async cloneReadOnly({ peer, targetAddrs, controlSpace, domainSpace, metaspace, senderIdentityInfo, fnSenderSecret, useInMemoryTempSpace = true, }: { peer: SyncPeerWitness; targetAddrs: string[]; controlSpace: IbGibSpaceAny; domainSpace: IbGibSpaceAny; metaspace: MetaspaceService; senderIdentityInfo?: SyncSenderIdentityInfo; fnSenderSecret?: () => Promise; useInMemoryTempSpace?: boolean; }): Promise { if (!targetAddrs || targetAddrs.length === 0) { throw new Error(`targetAddrs required in cloneReadOnly (E: c41aa40dce7f546d0bc7812fb9b107e0)`); } return await this.sync({ peer, domainAddrs: targetAddrs, mode: SyncMode.pull, conflictStrategy: SyncConflictStrategy.abort, controlSpace, domainSpace, metaspace, senderIdentityInfo, fnSenderSecret, useInMemoryTempSpace, }); } /** * This is what the receiving side of the sync calls to drive the FSM to the * next stage. * * So whereas the sender executes a saga loop and drives the entire process, * this is a reactive one-off that drives just the single step that the * receiver does in that saga. * * @returns next context result if another round, else if commit returns * null */ public async continueSync({ sagaContext, controlSpace, domainSpace, myTempSpace, metaspace, peer, }: { sagaContext: SyncSagaContextIbGib_V1, /** * Durable control space relative to the execution context's POV */ controlSpace: IbGibSpaceAny, /** * Durable domain space relative to the execution context's POV */ domainSpace: IbGibSpaceAny, /** * Local temp space relative to the execution context's POV */ myTempSpace: IbGibSpaceAny, metaspace: MetaspaceService, /** * the peer that is continuing the sync */ peer: SyncPeer_V1, }): Promise { const lc = `${this.lc}[${this.continueSync.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: f64e08bf77d1425378601f380384ec26)`); } if (!controlSpace) { throw new Error(`${lc} controlSpace required (E: 41b829d3f018432e88c45f18e2390826)`); } if (!domainSpace) { throw new Error(`${lc} domainSpace required (E: 92e418a7c108475a98d12b38a45c1826)`); } if (!myTempSpace) { throw new Error(`${lc} myTempSpace required (E: 37f928c1b458491d88a23e98d1204826)`); } if (sagaContext.sagaFrame) { this.latestSagaFrame = sagaContext.sagaFrame; } const contextResult = await this.handleResponseSagaContext({ sagaContext, controlSpace, domainSpace, myTempSpace, metaspace, peer, }); if (!contextResult) { if (logalot) { console.log(`${lc} Handler returned null (Saga End). (I: 43da8bb6c846b1fe7766332643be0e26)`); } // does this ever hit now? return null; /* <<<< returns early */ } else if (contextResult.nextFrameInfo?.sagaComplete) { // this is the current proper workflow I believe as of 01/22/2026 return null; /* <<<< returns early */ } // #region error conditions throw if (contextResult.errorMsg) { throw new Error(`Couldn't handle response saga context. errorMsg: ${contextResult.errorMsg} (E: 7b41a183cf3cb58a5859c803800cf826)`); } else if (!contextResult.nextFrameInfo) { throw new Error(`(UNEXPECTED) contextResult.nextFrameInfo falsy? (E: 5740542f5eb8ccb41dfec188d87c1e26)`); } // #endregion error conditions throw // create the return context const { frame, payloadIbGibsDomain } = contextResult.nextFrameInfo; this.latestSagaFrame = frame; const responseCtx = await this.createSyncSagaContext({ sagaFrame: frame, controlSpace, payloadIbGibsDomain, metaspace, sessionIdentityAddr: sagaContext.rel8ns?.sessionIdentity?.[0], peer, skipSign: true, }); const immediateValidationErrors = await validateContextAndSagaFrame({ context: responseCtx, }); if (immediateValidationErrors.length > 0) { throw new Error(`(UNEXPECTED) just created sync saga context () and there were immediateValidationErrors? immediateValidationErrors: ${immediateValidationErrors} (E: c120e8e0aa98673d685267a8a36e5826)`); } return responseCtx; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Drives the FSM loop of the Saga. * * @remarks * **Execution Context**: **Sender (Local)**. * * This method manages the "Ping Pong" request-response cycle on the Sender. * It sends frames via the Peer Witness and processes the responses using `handleSagaResponseContext`. * * **Data Transport Note**: * Actual ibGib data (payloads) are transported via `SyncSagaContext.rel8ns.payload`. * When `handleSagaResponseContext` returns a `nextPayloadIbGibs` (data to send), this loop injects it into * the NEXT request context. * When the Peer responds with data (in the response context), it is resolved and put into `tempSpace`. */ private async executeSagaLoop({ initFrame, initDomainGraph, peer, updates$, controlSpace, domainSpace, tempSpace, metaspace }: { initFrame: SyncIbGib_V1, /** * This is the initial dependency graph of all domain ibgibs passed in * to the original {@link sync} call. * * if we're executing on the sender, this will be populated */ initDomainGraph: FlatIbGibGraph, peer: SyncPeerWitness, updates$: SubjectWitness, metaspace: MetaspaceService, controlSpace: IbGibSpaceAny, domainSpace: IbGibSpaceAny, tempSpace: IbGibSpaceAny, }): Promise { const lc = `${this.lc}[${this.executeSagaLoop.name}]`; /** The current frame we just generated (e.g., Init or Delta Request) */ let currentFrame: SyncIbGib_V1 | null = initFrame; this.latestSagaFrame = currentFrame; /** The **domain** payload we need to transmit (data we are sending) */ let nextDomainIbGibs: IbGib_V1[] = []; while (currentFrame) { // first, prepare for context transmission... /** * this is used later in pollForDomainPayloads **iif** payloads are * received **in the response**, i.e., on the return trip. So if we * request addrs, the response should have these addrs and their * dependencies. The ibgibs corresponding to these addrs will be * streamed and placed into this map. */ const domainPayloadsMap = new Map(); // #region set up peer observable for any domainPayloadsMap const sublc = `${lc}[peer.payloadIbGibsDomainReceived$]`; const subscription = await peer.payloadIbGibsDomainReceived$.subscribe(fnObs({ next: async (ibgib: IbGib_V1) => { if (logalot) { console.log(`${sublc} next fired. (I: 2b4bdf502a38a90ba33d9711e7cb7826)`); } if (isKeystone(ibgib)) { throw new Error(`Security violation: Keystone received in domain sync payload stream (${getIbGibAddr({ ibGib: ibgib })}). Keystones may only be synchronized via dedicated keystone endpoints. (E: 88f2190847cb4e819b15b3648f828e26)`); } const addr = getIbGibAddr({ ibGib: ibgib }); if (logalotControlDomain) { console.log(`${lc}${lcControlDomain} DOMAIN STREAM RECEIVED <- observable: ${addr} (I: d69ee80fcaece272483ec33b2d289826)`); } domainPayloadsMap.set(addr, ibgib); }, error: async (e: string | Error | ErrorIbGib_V1) => { if (isIbGib(e)) { console.error(`${sublc} error fired. error: ${JSON.stringify((e as IbGib_V1).data)} (E: 01cc08ba05ad99682831174fd7c31a26)`); } else { console.dir(e); console.error(`${sublc} error fired. error: ${extractErrorMsg(e)} (E: 73d3d61464e8e4ce4cd6efd8b9675826)`); } }, complete: async () => { if (logalot) { console.log(`${sublc} complete fired. (I: a47218aa9e4433fdb97c068880a45826)`); } await subscription.unsubscribe(); }, })); // #endregion set up peer observable for any domainPayloadsMap try { // ...create/compose the Request Context itself... const requestCtx = await this.createSyncSagaContext({ sagaFrame: currentFrame, /** * init frame: empty * ack frame: possible push offers * delta frame: requested ibgibs or commit offer * commit frame: empty */ payloadIbGibsDomain: nextDomainIbGibs, controlSpace, metaspace, sessionIdentityAddr: peer.currentSessionIdentityAddr, peer, }); // #region Log what we're sending if (logalotControlDomain) { const domainAddrs = nextDomainIbGibs.map(p => getIbGibAddr({ ibGib: p })); console.log(`${lc}${lcControlDomain} SENDER TRANSMIT -> peer.witness (I: 5b0081803698770f0bf64992220b312)`); console.log(`${lc}${lcControlDomain} Context: ${getIbGibAddr({ ibGib: requestCtx })}`); console.log(`${lc}${lcControlDomain} Frame: ${getIbGibAddr({ ibGib: currentFrame })}`); console.log(`${lc}${lcControlDomain} DOMAIN Payloads (${domainAddrs.length}): ${domainAddrs.join(', ') || '(none)'}`); } // #endregion Log what we're sending // update our saga listeners... // if (logalot) { console.log(`${lc} transmitting... requestCtx: ${pretty(requestCtx)} (I: 8cf20817c66899abdb1e76df50356826)`); } updates$.next(requestCtx); // spins off for saga UI updates // ...And send the context. peer.setOptionalOpts({ controlSpace, domainSpace, localTempSpace: tempSpace, }); const responseCtx = await peer.witness(requestCtx); // the send returned, but a peer can return a falsy responseCtx, if // we just sent a commit to them and they're done. If so, there will // necessarily be no payload to wait to receive if (!responseCtx) { if (currentFrame) { // Check for Commit (Peer silence expected) const msg = await getSyncSagaMessageFromFrame({ frameIbGib: currentFrame, space: controlSpace }); if (msg?.data?.stage === SyncStage.commit) { if (logalot) { console.log(`${lc} Sender sent Commit. Peer returned no response. Saga Complete. (I: 26f9ee073858ca78b8284753368b5226)`); } currentFrame = null; break; } else { throw new Error(`(UNEXPECTED) responseCtx falsy and currentFrame truthy, but we're not in the commit stage? This may be expected ultimately, but atow I am not seeing this as being expected. (E: cc34498962bd370deeff351fac939f26)`); } } else { throw new Error(`(UNEXPECTED) no response and currentFrame falsy? (E: 8d1085ea2f28cfc3f9c922649864a826)`); } } // at this point, we did indeed receive a response to analyze. BUT! // we have only necessarily received the response context ibgib. // if there were payloads expected to be transferred, they may not // be done yet. if (!responseCtx.data) { throw new Error(`(UNEXPECTED) responseCtx.data falsy? (E: a969992bae53ab18a827ec58aec15826)`); } updates$.next(responseCtx); // spins off for saga UI updating // immediately validate context/saga frame (but not payloads because // we may not have those yet) const contextAndSagaFrameValidationErrors = await validateContextAndSagaFrame({ context: responseCtx }); if (contextAndSagaFrameValidationErrors.length > 0) { throw new Error(`contextAndSagaFrameValidationErrors: ${contextAndSagaFrameValidationErrors} (E: 6eebe8e7fa437c00a8cde3ada3c66826)`); } // Turn-by-turn continuation & identity checks const returnContextErrors = await this.validateReturnContext({ requestCtx, responseCtx, controlSpace, }); if (returnContextErrors.length > 0) { throw new Error(`validateReturnContext errors: ${returnContextErrors.join(', ')} (E: cb8a023b9d0728cceb09fa3da0bb8226)`); } // Extract expected domain addresses from response context const responsePayloadAddrsDomain = responseCtx.data[SYNC_SAGA_PAYLOAD_ADDRS_DOMAIN] as string[] || []; // Poll for them if needed. see above jsdocs for domainPayloadsMap if (responsePayloadAddrsDomain.length > 0) { responseCtx.payloadIbGibsDomain = await this.pollForDomainPayloads({ expectedAddrs: responsePayloadAddrsDomain, pollIntervalMs: 20, // relatively arbitrary right now domainPayloadsMap, tempSpace, }); } // #region Log what we received back if (!responseCtx.sagaFrame) { throw new Error(`(UNEXPECTED) responseCtx.sagaFrame falsy? the Peer should have set this when it got the response back from the remote. (E: e650adadf9a2063ec6764a1e31d3d826)`); } this.latestSagaFrame = responseCtx.sagaFrame; if (logalotControlDomain) { const responseControlAddrs = responseCtx.data?.['@payloadAddrsControl'] as string[] || []; console.log(`${lc}${lcControlDomain} SENDER RECEIVED <- peer.witness (I: 3dc76a9744d89a4fc3e2f076c2be4826)`); console.log(`${lc}${lcControlDomain} Response Context: ${getIbGibAddr({ ibGib: responseCtx })}`); console.log(`${lc}${lcControlDomain} Response Saga Frame: ${getIbGibAddr({ ibGib: responseCtx.sagaFrame })}`); console.log(`${lc}${lcControlDomain} CONTROL Payloads (${responseControlAddrs.length}): ${responseControlAddrs.join(', ') || '(none)'}`); console.log(`${lc}${lcControlDomain} DOMAIN Payloads (${responsePayloadAddrsDomain.length}): ${responsePayloadAddrsDomain.join(', ') || '(none)'}`); } // #endregion Log what we received back // at this point, we have received the context AND **all** of the // domain payloads (if applicable), so we are ready to do the next // iteration in the saga loop // this is the part that drives the FSM forward, i.e., when we // evolve the sync saga ibgib itself to the next frame if we aren't // finished/errored out. const contextResult = await this.handleResponseSagaContext({ sagaContext: responseCtx, initDomainGraph, controlSpace, domainSpace, myTempSpace: tempSpace, metaspace, peer, }); if (!contextResult) { // should this ever hit? console.error(`${lc} NAG ERROR (DOES NOT THROW): does this ever hit now? (E: e04d02efc2a8e72a88b79f1f0f95ca26)`); break; } else if (contextResult.nextFrameInfo?.sagaComplete) { if (logalot) { console.log(`${lc} Handler returned null (Saga End). (I: 123bf9e7dca8886de72553a8d4f29e26)`); } break; } // #region error conditions throw if (contextResult.errorMsg) { throw new Error(`Couldn't handle response saga context. errorMsg: ${contextResult.errorMsg} (E: c948e81d513b2a0eb8b8afa878edc626)`); } else if (!contextResult.nextFrameInfo) { throw new Error(`(UNEXPECTED) contextResult.nextFrameInfo falsy? (E: c287a82e823e662a77923278e2418826)`); } // #endregion error conditions throw // we have another frame to process and send out, with possibly // payload domain ibgibs as well const { frame, payloadIbGibsDomain, } = contextResult.nextFrameInfo; currentFrame = frame; this.latestSagaFrame = currentFrame; nextDomainIbGibs = [...(payloadIbGibsDomain || [])]; // #region Log handler output for next iteration if (logalotControlDomain) { const handlerDomainAddrs = nextDomainIbGibs.map(p => getIbGibAddr({ ibGib: p })); console.log(`${lc}${lcControlDomain} HANDLER RESULT -> next iteration (I: 6b0d88c4c28857ccd812381515bd7826)`); console.log(`${lc}${lcControlDomain} Next Frame: ${getIbGibAddr({ ibGib: currentFrame })}`); console.log(`${lc}${lcControlDomain} DOMAIN for next (${handlerDomainAddrs.length}): ${handlerDomainAddrs.join(', ') || '(none)'}`); } // #endregion Log handler output for next iteration } finally { await subscription.unsubscribe(); } } } /** * Creates new SyncSagaContext stone. Puts/registers in {@link controlSpace} * immediately after creation. * * @returns The context ibGib. * * ## notes * * the other ibgibs that are related to this context stone should already be * put/registered in {@link controlSpace}. */ private async createSyncSagaContext({ sagaFrame, payloadIbGibsDomain, metaspace, controlSpace, sessionIdentityAddr, peer, skipSign, }: { /** * The main saga frame (Init, Ack, etc.). */ sagaFrame: SyncIbGib_V1; /** * Domain payload ibgibs when the sync saga frame includes actual domain * payloads to send, e.g., in a Delta frame. */ payloadIbGibsDomain?: IbGib_V1[]; /** * reference to the current metaspace */ metaspace: MetaspaceService, /** * we persist the context in the durable control space (relative to our * execution POV) right when we create it. */ controlSpace: IbGibSpaceAny; sessionIdentityAddr?: string; peer: SyncPeerWitness; /** * If true, will not sign context. * * For now, this should be true when we call {@link continueSync}, as * the receiver does not sign any keystones. * * ## intent * * In V1, our receiving endpoint is not signing the context, rather, it * is just returning its response context ibgib with the same session * identity addr. We are thus trusting the security of the transport * itself for now. */ skipSign?: boolean, }): Promise { const lc = `[${this.createSyncSagaContext.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 6b87bee313e811d1d2fc90e87fbec826)`); } // #region sanity/validation if (!controlSpace) { throw new Error(`(UNEXPECTED) controlSpace falsy? (E: 1e7428f9a1284b3e98c01d28e3456826)`); } if (!sagaFrame.data) { throw new Error(`(UNEXPECTED) sagaFrame.data falsy? (E: 04c49b4cccba6842a8b52e4c6f570726)`); } if (!sagaFrame.data.n && sagaFrame.data.n !== 0) { throw new Error(`(UNEXPECTED) sagaFrame.data.n falsy and not 0? (E: 45b508da64a8b28428b11765d684b826)`); } // #endregion sanity/validation const date = new Date(); const timestamp = getTimestamp(date); const timestampMs = date.getMilliseconds(); const data: SyncSagaContextData_V1 = { timestamp, timestampMs, sagaN: sagaFrame.data.n, }; // Domain Payloads const payloadAddrsDomain = payloadIbGibsDomain ? payloadIbGibsDomain?.map(x => getIbGibAddr({ ibGib: x })) : undefined; if (payloadAddrsDomain && payloadAddrsDomain.length > 0) { data[SYNC_SAGA_PAYLOAD_ADDRS_DOMAIN] = payloadAddrsDomain; } // rel8ns should always have saga frame const rel8ns: SyncSagaContextRel8ns_V1 = { sagaFrame: [getIbGibAddr({ ibGib: sagaFrame })], }; let sessionIdentity: KeystoneIbGib_V1 | undefined = undefined; if (sessionIdentityAddr) { sessionIdentityAddr = await metaspace.getLatestAddr({ addr: sessionIdentityAddr, space: controlSpace }) ?? sessionIdentityAddr; const resGet = await getFromSpace({ addr: sessionIdentityAddr, space: controlSpace }); if (resGet.success && resGet.ibGibs?.length === 1) { sessionIdentity = resGet.ibGibs![0]! as KeystoneIbGib_V1; rel8ns.sessionIdentity = [sessionIdentityAddr]; } else { debugger; // what stage of the algo is this? which side? throw new Error(`Couldn't get sessionIdentityAddr (${sessionIdentityAddr}) in controlSpace: ${controlSpace.ib} (E: 5c29e80d68dbd1749866c358be093826)`); } } // Generate standard ib const ib = await getSyncSagaContextIb({ data }); const contextIbGib = await Factory_V1.stone({ parentPrimitiveIb: SYNC_SAGA_CONTEXT_ATOM, ib, data, rel8ns, }) as SyncSagaContextIbGib_V1; const contextAddr = getIbGibAddr({ ibGib: contextIbGib }); let signedSessionIdentity: KeystoneIbGib_V1 | undefined = undefined; if (sessionIdentity && !skipSign) { // signing context persists and registers the new keystone // using the peer's localMetaspace and controlSpace signedSessionIdentity = await peer.signContext({ contextAddr }); } // put/register context immediately in controlSpace (currently is a // DTO) but we don't want a broadcast on the metaspace await putInSpace({ ibGib: contextIbGib, space: controlSpace, }); await registerNewIbGib({ ibGib: contextIbGib, space: controlSpace, fnBroadcast: undefined, }); // Attach actual ibgibs for transport contextIbGib.sagaFrame = sagaFrame; const { msgStones } = await getSyncSagaFrameDependencyGraph({ sagaIbGib: sagaFrame, controlSpace, }); if (msgStones.length !== 1) { throw new Error(`(UNEXPECTED) msgStones.length !== 1 inside createSyncSagaContext? (E: a98165cf46ab4e82b7bd5e45a273b826)`); } contextIbGib.sagaFrameMsg = msgStones[0]; if (payloadIbGibsDomain && payloadIbGibsDomain.length > 0) { contextIbGib.payloadIbGibsDomain = payloadIbGibsDomain; } if (signedSessionIdentity) { contextIbGib.signedSessionIdentity = signedSessionIdentity; } return contextIbGib; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Helper to get Knowledge Map for specific domain ibGibs or TJPs. * Useful for testing and external validation. */ public async getKnowledgeMap({ space, metaspace, domainIbGibs, tjpAddrs, }: { space: IbGibSpaceAny, metaspace: MetaspaceService, domainIbGibs?: IbGib_V1[], tjpAddrs?: string[], }): Promise<{ [tjp: string]: string | null }> { const lc = `${this.lc}[${this.getKnowledgeMap.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: e184f8a7818666febfbbd2d841ed3826)`); } if (!(domainIbGibs && domainIbGibs.length > 0) && !(tjpAddrs && tjpAddrs.length > 0) ) { throw new Error(`(UNEXPECTED) domainIbGibs and tjpAddrs falsy/empty? we need one or the other (E: f674285111c8648398cd79d8c08ec826)`); } if ((domainIbGibs && domainIbGibs.length > 0) && (tjpAddrs && tjpAddrs.length > 0) ) { throw new Error(`(UNEXPECTED) both domainIbGibs and tjpAddrs truthy? only pass in one or the other. (E: f674285111c8648398cd79d8c08ec826)`); } let tjps: string[] = []; if (tjpAddrs) { tjps = tjpAddrs; } else if (domainIbGibs && domainIbGibs.length > 0) { // Extract TJPs from domain Ibgibs const { mapWithTjp_YesDna, mapWithTjp_NoDna } = splitPerTjpAndOrDna({ ibGibs: domainIbGibs }); const allWithTjp = [...Object.values(mapWithTjp_YesDna), ...Object.values(mapWithTjp_NoDna)]; const timelineMap = getTimelinesGroupedByTjp({ ibGibs: allWithTjp }); tjps = Object.keys(timelineMap); } else { // No info provided. Return empty? Or throw? // User test context implied "everything", but implementation requires scope. console.warn(`${lc} No domainIbGibs or tjpAddrs provided. Returning empty Knowledge. (W: 2b0e115e7578a83d1b26f7c726bf9426)`); return {}; } if (tjps.length === 0) { return {}; } const res = await getLatestAddrs({ space, tjpAddrs: tjps }); if (!res.data || !res.data.latestAddrsMap) { throw new Error(`${lc} Failed to get latest addrs. (E: 7d395940c0e1419165c5196c39c6c826)`); } return res.data.latestAddrsMap; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } private async analyzeDomainIbGibs({ domainIbGibs, space, }: { domainIbGibs: IbGib_V1[], space: IbGibSpaceAny, }): Promise { const lc = `${this.lc}[${this.analyzeDomainIbGibs.name}]`; if (domainIbGibs.length === 0) { return { stones: [], timelinesMap: {}, topologicallySortedTjpAddrs: [], fullGraph: {} }; } if (this.currentAdapter?.analyzeDomainIbGibs) { const adaptedAnalysis = await this.currentAdapter.analyzeDomainIbGibs({ domainIbGibs, space, }); if (adaptedAnalysis) { if (logalot) { console.log(`${lc} using adapted domain analysis from adapter ${this.currentAdapter.adapterId} (stones: ${adaptedAnalysis.stones.length}, nodes: ${Object.keys(adaptedAnalysis.fullGraph).length})`); } return adaptedAnalysis; } } const fullGraph = await getDependencyGraph({ ibGibs: domainIbGibs, live: true, space, }); const graphIsValid = fullGraph && Object.keys(fullGraph).length > 0; if (logalot) { console.log(`${lc} graph generated. nodes: ${graphIsValid ? Object.keys(fullGraph).length : 0}`); } const srcIbGibs = graphIsValid ? Object.values(fullGraph) : []; const { mapWithTjp_YesDna: srcMapWithTjp_YesDna, mapWithTjp_NoDna: srcMapWithTjp_NoDna, mapWithoutTjps: src_MapWithoutTjps } = splitPerTjpAndOrDna({ ibGibs: srcIbGibs }); const stones = Object.values(src_MapWithoutTjps); const withTimelines = [...Object.values(srcMapWithTjp_YesDna), ...Object.values(srcMapWithTjp_NoDna)]; const timelinesMap = getTimelinesGroupedByTjp({ ibGibs: withTimelines }); const topologicallySortedTjpAddrs = this.sortTimelinesTopologically(timelinesMap); return { stones, timelinesMap, topologicallySortedTjpAddrs, fullGraph }; } /** * Creates the Initial Saga Frame (Init Stage). * * @remarks * **Execution Context**: **Sender (Local)**. * * Generates the first frame containing the Knowledge Map of the Domain Space. * This is sent to the Receiver to begin Gap Analysis. */ private async createInitFrame({ sagaId, domainIbGibs, domainAddrs, mode = SyncMode.sync, conflictStrategy, graftPreference, targetSpaceInfo, metaspace, controlSpace, domainSpace, tempSpace, peer, }: { sagaId: string, domainIbGibs: IbGib_V1[], domainAddrs?: string[], mode?: SyncMode, conflictStrategy: SyncConflictStrategy, graftPreference?: GraftPreference, targetSpaceInfo?: SyncData_V1['targetSpaceInfo'], metaspace: MetaspaceService, controlSpace: IbGibSpaceAny, domainSpace: IbGibSpaceAny, tempSpace: IbGibSpaceAny, peer: SyncPeerWitness, }): Promise<{ initFrame: SyncIbGib_V1, initDomainGraph: { [addr: string]: IbGib_V1 } }> { const lc = `${this.lc}[${this.createInitFrame.name}]`; const initTimer = startPerfTimer(`[sync-saga][createInitFrame]`); try { if (logalot) { console.log(`${lc} starting... (I: 551af8b411ae9be712ce3358d43ee726)`); } // Analyze Timelines & Stones in domainSpace const analysis = await this.analyzeDomainIbGibs({ domainIbGibs, space: domainSpace }); initTimer.mark(`analyzeDomainIbGibs (${domainIbGibs.length} roots)`); const { timelinesMap: srcTimelinesMap, fullGraph, stones: srcStones, } = analysis; // we need to store the fullGraph in our tempSpace for later... if (Object.keys(fullGraph).length > 0) { await putInSpace_dnasThenNonDnas({ ibGibs: Object.values(fullGraph), space: tempSpace }); initTimer.mark(`putInTempSpace (${Object.keys(fullGraph).length} nodes)`); } // populate our knowledge map with tjp -> latest addr/tip in timeline const knowledgeMap: { [tjp: string]: IbGibAddr } = {}; Object.keys(srcTimelinesMap).forEach(tjp => { const timeline = srcTimelinesMap[tjp]; const tip = timeline.at(-1)!; knowledgeMap[tjp] = getIbGibAddr({ ibGib: tip }); }); const initData: SyncSagaMessageInitData_V1 = { sagaId, stage: SyncStage.init, knowledgeMap: knowledgeMap, mode: mode ?? SyncMode.sync, stones: srcStones.map(s => getIbGibAddr({ ibGib: s })), targetAddrs: domainAddrs, }; if (logalot) { console.log(`${lc} SyncStage.init: ${SyncStage.init}, SyncStage.commit: ${SyncStage.commit}`); console.log(`${lc} initData.stage: ${initData.stage}`); } // create the stone and save/register it in controlSpace const initStone = await this.createSyncMsgStone({ data: initData, controlSpace, metaspace, }); // if (logalot) { console.log(`${lc} initStone: ${pretty(initStone)} (I: 06e532f8a408549069474e96bed44826)`); } // create the initial sync ibgib frame, save/register it in controlSpace const sagaFrame = await this.evolveSyncSagaIbGib({ msgStones: [initStone], conflictStrategy, graftPreference, targetSpaceInfo, metaspace, controlSpace, sessionIdentity: peer.currentSessionIdentity, }); if (logalot) { console.log(`${lc} sagaFrame (init): ${pretty(sagaFrame)} (I: b3d6a8be69248f18713cc3073cb08626)`); } return { initFrame: sagaFrame, initDomainGraph: fullGraph }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { initTimer.stop(); if (logalot) { console.log(`${lc} complete.`); } } } /** * Validates that the return context received from a peer is a valid * continuation of the outbound context and that the session identity * is consistent. */ private async validateReturnContext({ requestCtx, responseCtx, controlSpace, }: { requestCtx: SyncSagaContextIbGib_V1, responseCtx: SyncSagaContextIbGib_V1, controlSpace: IbGibSpaceAny, }): Promise { const lc = `${this.lc}[${this.validateReturnContext.name}]`; const errors: string[] = []; try { // 1. Verify saga frame continuation if (requestCtx.sagaFrame && responseCtx.sagaFrame) { const requestFrameAddr = getIbGibAddr({ ibGib: requestCtx.sagaFrame }); const responseFrameAddr = getIbGibAddr({ ibGib: responseCtx.sagaFrame }); try { const isContinuation = await isPastFrame({ olderAddr: requestFrameAddr, newerAddr: responseFrameAddr, space: controlSpace, }); if (!isContinuation) { errors.push(`Response saga frame (${responseFrameAddr}) is not a valid continuation of request saga frame (${requestFrameAddr}). (E: 2c85e8d97318ff24ac8a02bd3a068226)`); } } catch (error) { console.error(`${lc} isPastFrame just threw (E: 477888443fe89eca2c19fb684bf60126)`) throw error; } } else { errors.push(`Missing sagaFrame on requestCtx or responseCtx. (E: b65c68ff891000ddca8d22384a088226)`); } // 2. Verify session identity has not changed const expectedSessionIdAddr = requestCtx.signedSessionIdentity ? getIbGibAddr({ ibGib: requestCtx.signedSessionIdentity }) : requestCtx.rel8ns?.sessionIdentity?.[0]; const responseSessionIdAddr = responseCtx.rel8ns?.sessionIdentity?.[0]; if (expectedSessionIdAddr !== responseSessionIdAddr) { errors.push(`Session identity mismatch. Expected ${expectedSessionIdAddr}, got ${responseSessionIdAddr}. (E: 5c8dbc07cc57b01b3aae88b1723c40c3)`); } } catch (error) { errors.push(`Error during validateReturnContext: ${extractErrorMsg(error)} (E: da878e1239aa88ee27bdfca005c28226)`); } if ((logalot) && errors.length > 0) { console.log(`${lc} errors: ${errors.join('\n')} (I: cbc119df45aa13daa9009de392c4b226)`); } return errors; } /** * Helper to poll for streaming domain payloads and put them in the * local {@link tempSpace}. * * @returns when all {@link expectedAddrs} are done being transmitted. */ private async pollForDomainPayloads({ expectedAddrs, pollIntervalMs, domainPayloadsMap, tempSpace, }: { expectedAddrs: string[], pollIntervalMs: number, domainPayloadsMap: Map, tempSpace: IbGibSpaceAny, }): Promise { const lc = `${this.lc}[${this.pollForDomainPayloads.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 26dce86bfca572939885798802d6e926)`); } let resultDomainPayloads: IbGib_V1[] = []; const uniqueExpectedAddrs = [...new Set(expectedAddrs)]; let pending = [...uniqueExpectedAddrs]; const start = Date.now(); /** * This needs */ const timeoutMs = 15 * 60 * 1000; // 15 minutes for large repository initial transfers while (pending.length > 0) { if (Date.now() - start > timeoutMs) { throw new Error(`Timeout waiting for payloads: ${pending.join(', ')} (E: 46e1683c9578095261aaf798bd5e1826)`); } const stillPending: string[] = []; const found: IbGib_V1[] = []; for (const addr of pending) { if (domainPayloadsMap.has(addr)) { const foundIbGib = domainPayloadsMap.get(addr)!; if (isKeystone(foundIbGib)) { throw new Error(`Security violation: Keystone found in domain payloads (${addr}). Keystones must never be transmitted via domain sync. (E: c288f39108a74e5399ba14881023d826)`); } found.push(foundIbGib); domainPayloadsMap.delete(addr); } else { stillPending.push(addr); } } if (found.length > 0) { await putInSpace_dnasThenNonDnas({ space: tempSpace, ibGibs: found }); found.forEach(x => resultDomainPayloads.push(x)); } pending = stillPending; if (pending.length > 0) { await delay(pollIntervalMs); } } if (uniqueExpectedAddrs.length !== resultDomainPayloads.length) { throw new Error(`(UNEXPECTED) uniqueExpectedAddrs.length !== resultDomainPayloads.length? at this point, we expect all of the payload ibgibs to have been received. (E: 03749a7478c4b8b28bfc86951887a826)`); } return resultDomainPayloads; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * This is the heart of the "ping pong" transaction, where we send a context * * and receive a context. IOW, this drives the FSM of the sync saga ibgib as * a whole. * * This is called in two places: * * ## 1. Sender * * On the sender, this is called repeatedly within the the sync saga * coordinator's {@link executeSagaLoop} which initiates and drives the * overall sync process. This loop continues until there are no more frames * to be exchanged between endpoints. * * ## 2. Receiver * * On the receiver, this is called directly from {@link continueSync}, which * itself is called either directly by the concrete sync peer or from within * the receiving node endpoint. That endpoint's job is basically to get * these things collocated and prepared to make this call. * * In contrast to the sender, this can be thought of as a one-off on the * receiver, since the sender's {@link executeSagaLoop} is what actually * drives the ping-pong process. */ private async handleResponseSagaContext({ sagaContext, initDomainGraph, controlSpace, domainSpace, myTempSpace, metaspace, peer, }: { sagaContext: SyncSagaContextIbGib_V1, /** * This is the initial dependency graph of all domain ibgibs passed in * to the original {@link sync} call. * * if we're executing on the sender, this will be populated */ initDomainGraph?: FlatIbGibGraph, /** * Durable control space relative to the execution context's POV */ controlSpace: IbGibSpaceAny, /** * Durable domain space relative to the execution context's POV */ domainSpace: IbGibSpaceAny, /** * Local temp space relative to the execution context's POV */ myTempSpace: IbGibSpaceAny, metaspace: MetaspaceService, peer?: SyncPeerWitness, }): Promise { const lc = `${this.lc}[${this.handleResponseSagaContext.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 5deec8a1f7a6d263c88cd458ad990826)`); } const sagaIbGib = sagaContext.sagaFrame; if (!sagaIbGib.data) { throw new Error(`(UNEXPECTED) sagaIbGib.data falsy? (E: 71b938adf1d87c2527bfd4f86dfd0826)`); } if (logalot) { console.log(`${lc} sagaIbGib: ${pretty(sagaIbGib)} (I: 1b99d87d262e9d18d8a607a80b1a0126)`); } // Get Stage from Stone in controlSpace const { stage, messageData } = await this.getStageAndPayloadFromFrame({ sagaFrame: sagaIbGib, controlSpace }); if (logalot) { console.log(`${lc} handling frame stage: ${stage}`); } let nextFrameInfo: NextSagaFrameInfo; switch (stage) { case SyncStage.init: nextFrameInfo = await this.handleInitFrame({ sagaIbGib, messageData: messageData as SyncSagaMessageInitData_V1, metaspace, controlSpace, domainSpace, myTempSpace, peer, }); break; case SyncStage.ack: if (!initDomainGraph) { throw new Error(`(UNEXPECTED) initDomainGraph falsy on the sender? (E: a3d758ad954829aba88663188eafc826)`); } nextFrameInfo = await this.handleAckFrame({ sagaContext, sagaIbGib, initDomainGraph, metaspace, controlSpace, domainSpace, myTempSpace, }); break; case SyncStage.delta: nextFrameInfo = await this.handleDeltaFrame({ sagaContext, sagaIbGib, metaspace, controlSpace, domainSpace, myTempSpace, }); break; case SyncStage.commit: if (logalot) { console.log(`${lc}[${getSyncSagaFrameOrigin({ sagaFrame: sagaIbGib })}] domainSpace.ib: ${domainSpace.ib} (I: 5b270996d848907238d817fffa64a126)`); } nextFrameInfo = await this.handleCommitFrame({ sagaIbGib, metaspace, controlSpace, domainSpace, myTempSpace, }); break; default: throw new Error(`${lc} (UNEXPECTED) Unknown sync stage: ${stage} (E: 9c2b4c8a6d34469f8263544710183355)`); } if (logalot) { console.log(`${lc} nextFrameInfo: ${nextFrameInfo ? pretty(nextFrameInfo) : 'undefined'} (I: a8ad281ca8e89385686d18327a105726)`); } return { errorMsg: undefined, nextFrameInfo, } } catch (error) { const errorMsg = `${lc} ${extractErrorMsg(error)}`; console.error(errorMsg); return { errorMsg } } finally { if (logalot) { console.log(`${lc} complete.`); } } } // #region Handlers /** * Handles the `Init` frame. * * @remarks * **Execution Context**: **Receiver (Remote)**. * * The Receiver performs Gap Analysis here: * 1. Compares Sender's Knowledge Map (in `sagaIbGib`) vs Receiver's Local Knowledge Map. * 2. Identifies what Sender needs (`pushOfferAddrs`). * 3. Identifies what Receiver needs (`deltaRequestAddrInfos`). * 4. Returns an `Ack` frame containing these lists. */ private async handleInitFrame({ sagaIbGib, messageData, controlSpace, domainSpace, myTempSpace, metaspace, peer, }: { sagaIbGib: SyncIbGib_V1, messageData: SyncSagaMessageInitData_V1, /** * Durable control space relative to the execution context's POV */ controlSpace: IbGibSpaceAny, /** * Durable domain space relative to the execution context's POV */ domainSpace: IbGibSpaceAny, /** * Local temp space relative to the execution context's POV. * * NOTE: Since this always executes on the receiver's end, this should * be the receiver's temp space. */ myTempSpace: IbGibSpaceAny, metaspace: MetaspaceService, peer?: SyncPeerWitness, }): Promise { const lc = `${this.lc}[${this.handleInitFrame.name}]`; const gapTimer = startPerfTimer(`[sync-saga][handleInitFrame]`); try { if (logalot) { console.log(`${lc} starting... (I: 9d88dcad0408c029e898a4bcf3b08426)`); } if (logalot) { console.log(`${lc} [TEST DEBUG] Receiver domainSpace: ${domainSpace.ib}`); } // Extract Init Data const initData = messageData as SyncSagaMessageInitData_V1; // Using renamed variable for clarity if (initData.stage !== SyncStage.init) { throw new Error(`${lc} Invalid init frame: initData.stage !== SyncStage.init (E: c91be82970e4decc58f56bf8fc1ffc26)`); } // if (logalot) { console.log(`${lc} initData: ${pretty(initData)} (I: 46b0f8441b96ad7a388f1ce3239dd826)`); } if (!initData || !initData.knowledgeMap) { throw new Error(`${lc} Invalid init frame: missing knowledgeMap (E: ed02c869e028d2d06841b9c7f80f2826)`); } // Determine Strategy from Saga Data (since V1 stores it in root) const conflictStrategy = sagaIbGib.data!.conflictStrategy || SyncConflictStrategy.abort; // 2. Gap Analysis const conflicts: SyncSagaConflictInfo[] = []; const deltaRequestAddrInfos: SyncSagaRequestAddrInfo[] = []; const pushOfferInfos: SyncSagaPushOfferInfo[] = []; // If in pull mode and targetAddrs are explicitly requested or configured on receiver peer, // extract their dependency graphs from domainSpace and offer to push them const isPullMode = initData.mode === SyncMode.pull; const targetAddrsToOffer = isPullMode ? ((initData.targetAddrs && initData.targetAddrs.length > 0) ? initData.targetAddrs : (peer as any)?.opts?.targetAddrs) : undefined; if (targetAddrsToOffer && targetAddrsToOffer.length > 0) { if (logalot) { console.log(`${lc} targetAddrs explicitly requested or configured on receiver: ${targetAddrsToOffer.join(', ')}`); } try { const targetGraph = await getDependencyGraph({ space: domainSpace, ibGibAddrs: targetAddrsToOffer, live: true, }); if (targetGraph && Object.keys(targetGraph).length > 0) { const targetAddrsFound = Object.keys(targetGraph); if (logalot) { console.log(`${lc} resolved targetGraph nodes (${targetAddrsFound.length}) for push offer`); } pushOfferInfos.push({ tjpAddr: targetAddrsToOffer[0], addrs: targetAddrsFound, }); } else { console.warn(`${lc} getDependencyGraph returned empty or null for targetAddrs: ${targetAddrsToOffer.join(', ')} (W: 81a92e47c0b5421a)`); } } catch (targetGraphErr) { if (logalot) { console.warn(`${lc} targetAddrs getDependencyGraph failed: ${extractErrorMsg(targetGraphErr)} (W: 81a92e47c0b5421b)`); } } } // First do the constant stones (Non-TJPs) in domainSpace const stones = initData.stones || []; if (stones.length > 0) { if (logalot) { console.log(`${lc} processing stones: ${stones.length}`); } // Check if we have these stones in domainSpace const resStones = await getFromSpace({ space: domainSpace, addrs: stones }); const rawResultIbGib = resStones.rawResultIbGib as IbGibSpaceResultIbGib; if (!rawResultIbGib.data) { throw new Error(`(UNEXPECTED) rawResultIbGib.data falsy? (E: f3c40b492adc02c3f480b998fc7a5926)`); } const addrsNotFound = rawResultIbGib.data.addrsNotFound; if (addrsNotFound && addrsNotFound.length > 0) { if (logalot) { console.log(`${lc} stones missing (requesting): ${addrsNotFound.length}`); } addrsNotFound.forEach(addr => { if (!deltaRequestAddrInfos.some(x => x.addr === addr)) { deltaRequestAddrInfos.push({ addr }); // no tjpAddr } }); } } const senderKnowledge = initData.knowledgeMap; if (logalot) { console.log(`${lc} senderKnowledge: ${pretty(senderKnowledge)} (I: 9f957862356dfeae183c200854e86e26)`); } const senderTjpAddrs = Object.keys(senderKnowledge); if (logalot) { console.log(`${lc} [TEST DEBUG] senderTjpAddrs: ${JSON.stringify(senderTjpAddrs)}`); } if (logalot) { console.log(`${lc} senderTjpAddrs: ${pretty(senderTjpAddrs)} (I: 86ea4c53db0dc184c8b253386c402126)`); } // 1. Get receiver Latest Addrs for all TJPs in domainSpace let receiverLatestAddrsMap: { [tjp: string]: string | null } = {}; if (senderTjpAddrs.length > 0) { // Batch get latest addrs for the TJPs const resGetLatestAddrs = await getLatestAddrs({ space: domainSpace, // executing on receiver, so this is receiver's domainSpace tjpAddrs: senderTjpAddrs, }); if (!resGetLatestAddrs.data) { throw new Error(`(UNEXPECTED) resGetLatestAddrs.data falsy? (E: b180d813c088042b38e1e02e06a16926)`); } if (!resGetLatestAddrs.data.latestAddrsMap) { throw new Error(`(UNEXPECTED) resGetLatestAddrs.data.latestAddrsMap falsy? (E: 16bc386dd51d0ff53a49620b1e641826)`); } receiverLatestAddrsMap = resGetLatestAddrs.data.latestAddrsMap; gapTimer.mark(`getLatestAddrs (${senderTjpAddrs.length} TJPs)`); if (logalot) { console.log(`${lc} [TEST DEBUG] receiverLatestAddrsMap: ${JSON.stringify(receiverLatestAddrsMap)}`); } if (logalot) { console.log(`${lc} receiverLatestAddrsMap: ${pretty(receiverLatestAddrsMap)} (I: 980975642cbccd8018cf0cd808d30826)`); } } // 2. Gap Analysis for (const tjpAddr of senderTjpAddrs) { const senderTipAddr = senderKnowledge[tjpAddr]; const receiverTipAddr = receiverLatestAddrsMap[tjpAddr]; if (!receiverTipAddr) { // We (Receiver) don't have this timeline at all. Request it. if (logalot) { console.log(`${lc} [TEST DEBUG] Missing receiver timeline for TJP: ${tjpAddr}. Requesting remoteAddr: ${senderTipAddr}`); } deltaRequestAddrInfos.push({ addr: senderTipAddr, tjpAddr: tjpAddr, // we don't have this timeline at all // latestAddrAlreadyHave: undefined }); continue; } // we do have this timeline... if (receiverTipAddr === senderTipAddr) { // ...already synced if (logalot) { console.log(`${lc} [TEST DEBUG] TJP ${tjpAddr}: Synced (receiverTipAddr === remoteAddr)`); } continue; } if (logalot) { console.log(`${lc} [TEST DEBUG] TJP ${tjpAddr}: receiverTipAddr=${receiverTipAddr}, remoteAddr=${senderTipAddr} - checking for divergence...`); } // we have this timeline but it's not synced... // We're executing on receiver. Check if Remote (Sender) is in // our past, and if so, we are ahead and need to push the delta // to remote let remoteIsInPast: boolean; try { remoteIsInPast = await isPastFrame({ olderAddr: senderTipAddr, newerAddr: receiverTipAddr, space: domainSpace, }); } catch (error) { console.log(`${lc} isPastFrame just threw (E: b297244176e7380ffcaaef4861799326)`); remoteIsInPast = false; } if (remoteIsInPast) { // we're ahead, so push the delta of what the sender doesn't // have (we have full knowledge) if (logalot) { console.log(`${lc} [TEST DEBUG] TJP ${tjpAddr}: Remote (sender) is in past - offering push`); } const deltaGraph = await getDeltaDependencyGraph({ ibGibAddr: receiverTipAddr, live: false, // always live: false right? latestCommonFrameAddr: senderTipAddr, skipRel8nNames: [B2TFS_CHILD_ITEM_REL8N_NAME], space: domainSpace, }); pushOfferInfos.push({ tjpAddr: tjpAddr, addrs: Object.keys(deltaGraph), }); } else { // Remote tip is not in our past. So, either Remote is // ahead (we're in THEIR past, i.e., Fast-Backward) OR // Diverged/conflict (we've both made edits). // Check if receiver is in sender's PAST (Remote is Ahead -> Delta Request) /** * we could first check for existence of remoteAddr in * domainSpace, but this is quick and easy. If it throws, we * don't have it so it can't be in the past. */ let receiverIsInPast = false; try { receiverIsInPast = await isPastFrame({ olderAddr: receiverTipAddr, newerAddr: senderTipAddr, space: domainSpace, quietIfNewerMissing: true, }); } catch (error) { // couldn't get one of them, so receiverIsInPast remains false. if (logalot) { console.log(`${lc} isPastFrame just threw, but is an expected error if we don't have remote. verbose logging error though: ${extractErrorMsg(error)} (I: 47ea08d0b418cf4aa8a502a7bcb80826)`); } } if (receiverIsInPast) { // Fast-Forward: We update to remote's tip and we're done. if (logalot) { console.log(`${lc} [TEST DEBUG] TJP ${tjpAddr}: receiver is in past - requesting delta`); } deltaRequestAddrInfos.push({ addr: senderTipAddr, tjpAddr: tjpAddr, latestAddrAlreadyHave: receiverTipAddr, }); } else { // POTENTIAL DIVERGENCE OR FAST-FORWARD: // Because the Receiver does not have senderTipAddr locally yet, // it cannot distinguish between Fast-Forward (receiverTipAddr is in // senderTipAddr's past) and true Divergence until the Sender // inspects receiverKnowledgeTimelineAddrs in handleAckFrame. if (logalot) { console.log(`${lc} [TEST DEBUG] TJP ${tjpAddr}: POTENTIAL DIVERGENCE OR FAST-FORWARD! conflictStrategy=${conflictStrategy}`); } if ( conflictStrategy === SyncConflictStrategy.abort || conflictStrategy === SyncConflictStrategy.optimisticWithLCS ) { // Fetch Full History for receiver's Timeline in domainSpace // so the Sender in handleAckFrame can determine if this is a // fast-forward (latestCommonFrameAddr === receiverTipAddr) or // a true divergence. const resReceiverTipIbGib = await getFromSpace({ addr: receiverTipAddr, space: domainSpace, }); if (!resReceiverTipIbGib.success || resReceiverTipIbGib.ibGibs?.length !== 1) { throw new Error(`couldn't get local tip (${receiverTipAddr}) from domainSpace (${domainSpace.ib}). errorMsg: ${resReceiverTipIbGib.errorMsg ?? '[unknown error (E: b3c3d823276300aa384ebdba4a8eb826)]'} (E: 83cb88a767e22bbda99c6788bec50526)`); } const receiverTipIbGib = resReceiverTipIbGib.ibGibs[0]; const pastAddrs = await getHistoryAddrs({ timeline: receiverTipIbGib, space: domainSpace, metaspace, }); conflicts.push({ tjpAddr: tjpAddr, receiverTipAddr, senderTipAddr, receiverKnowledgeTimelineAddrs: [...pastAddrs, receiverTipAddr], reason: 'divergence', terminal: false }); } else { throw new Error(`${lc} Unsupported conflict strategy: ${conflictStrategy}. Only these currently implemented: ${SYNC_CONFLICT_STRATEGY_VALID_VALUES} (E: 8f12384180f8a718a983a749fe0adf26)`); } } } } gapTimer.mark(`gapAnalysis (conflicts: ${conflicts.length}, requests: ${deltaRequestAddrInfos.length})`); // Check if we should ABORT (if any conflict is terminal) const hasTerminalConflicts = conflicts.some(c => c.terminal); if (hasTerminalConflicts) { // Abort Strategy: Kill the saga. if (logalot) { console.warn(`${lc} ABORTING Sync Saga due to terminal conflicts: ${JSON.stringify(conflicts)}`); } throw new Error(`the saga has terminal conflicts. conflicts: ${JSON.stringify(conflicts)} (E: f2edbe93cc07a63b38bfc013d2213b26)`); } // 3. Create Ack Frame in controlSpace if (!sagaIbGib.data) { throw new Error(`(UNEXPECTED) sagaIbGib.data falsy? (E: 24203af4600fb226ae6c1afbde442826)`); } const sagaId = sagaIbGib.data.uuid; // Create Payload Stone const ackData: SyncSagaMessageAckData_V1 = { sagaId, stage: SyncStage.ack, deltaRequestAddrInfos, pushOfferInfos, }; if (conflicts?.length > 0) { ackData.conflicts = conflicts; } const ackStone = await this.createSyncMsgStone({ data: ackData, controlSpace, metaspace, }); if (logalot) { console.log(`${lc} ackStone created: ${pretty(ackStone)} (I: 313708132dd53ff946befb7833657826)`); } // Evolve Saga in controlSpace const ackFrame = await this.evolveSyncSagaIbGib({ prevSagaIbGib: sagaIbGib, msgStones: [ackStone], controlSpace, metaspace, }); // if (logalot) { console.log(`${lc} ackFrame created: ${pretty(ackFrame)} (I: be24480592eec478086bb3da49286826)`); } /** * we want to push ibgibs to the remote/sender if we have push * offers. an ack frame's payloads, if any, are those push offers */ let payloadIbGibsDomain: IbGib_V1[] | undefined; if (pushOfferInfos.length > 0) { const searchSecondSpaceAddrs: IbGibAddr[] = []; payloadIbGibsDomain = []; const domainAddrs: IbGibAddr[] = pushOfferInfos.flatMap(x => x.addrs); const resGet = await getFromSpace({ addrs: domainAddrs, space: domainSpace, }); const resGetRawData = resGet.rawResultIbGib?.data as IbGibSpaceResultData | undefined; if (!resGetRawData) { throw new Error(`(UNEXPECTED) resGet.rawResultIbGib.data falsy? (E: 1a2cc8cb99a1ffa60837e45a8229b826)`); } const addrsNotFound = resGetRawData.addrsNotFound ?? []; const addrsErrored = resGetRawData.addrsErrored ?? []; if (resGet.ibGibs && resGet.ibGibs.length === domainAddrs.length) { // found all of them resGet.ibGibs.forEach(x => { payloadIbGibsDomain!.push(x) }) } else if (resGet.ibGibs && resGet.ibGibs.length > 0) { // found some of them resGet.ibGibs.forEach(x => { payloadIbGibsDomain!.push(x) }) const foundPlusNotFoundCount = payloadIbGibsDomain.length + addrsNotFound.length + addrsErrored.length; if (foundPlusNotFoundCount === domainAddrs.length) { // we can still conceivably get the remaining addrs addrsNotFound.forEach(x => searchSecondSpaceAddrs.push(x)); addrsErrored.forEach(x => searchSecondSpaceAddrs.push(x)); } else if (addrsNotFound.length === 0 && addrsErrored.length === 0) { throw new Error(`(UNEXPECTED) found some but not all addrs but addrsNotFound and addrsErrored both empty? (E: ef1b2cf5bab8de2298ec507abe04e826)`); } else { throw new Error(`(UNEXPECTED) found some but not all addrs but addrsNotFound and addrsErrored don't contain the addrs not found? (E: ae9e015109f8c3c3a813da584cd98826)`); } } else { // found none of them(?) console.warn(`${lc} we were expecting all domainAddrs in domainSpace (${domainSpace.ib}) but we couldn't get all of them. addrsNotFound: ${addrsNotFound ?? []}. addrsErrored: ${addrsErrored ?? []}. Trying temp space (${myTempSpace.ib}). (W: f61908e264f8dddd2e3fb9084463d826)`); domainAddrs.forEach(x => searchSecondSpaceAddrs.push(x)); } if (searchSecondSpaceAddrs.length > 0) { if (logalot) { console.log(`${lc} couldn't get all addrs in domainSpace (${domainSpace.ib}). searchSecondSpaceAddrs: ${searchSecondSpaceAddrs} (I: 233fd954dbd84e51bca02fa8eed5f826)`); } if (controlSpace && controlSpace !== domainSpace && controlSpace !== myTempSpace) { const resGetControl = await getFromSpace({ addrs: searchSecondSpaceAddrs, space: controlSpace }); if (resGetControl.success && resGetControl.ibGibs) { resGetControl.ibGibs.forEach(x => { const addr = getIbGibAddr({ ibGib: x }); if (!payloadIbGibsDomain!.some(pid => getIbGibAddr({ ibGib: pid }) === addr)) { payloadIbGibsDomain!.push(x); } }); } } const resGet2 = await getFromSpace({ addrs: searchSecondSpaceAddrs, space: myTempSpace, }); if (resGet2.success && resGet2.ibGibs && resGet2.ibGibs.length === searchSecondSpaceAddrs.length) { // got them all the second try resGet2.ibGibs.forEach(x => payloadIbGibsDomain!.push(x)); } else { resGet2.ibGibs?.forEach(x => payloadIbGibsDomain!.push(x)); const addrsFailed = domainAddrs.filter(x => !payloadIbGibsDomain!.map(pid => getIbGibAddr({ ibGib: pid })).includes(x) ); throw new Error(`couldn't get some or all of addrs from either domainSpace (${domainSpace.ib}) or myTempSpace (${myTempSpace.ib}). addrsFailed: ${addrsFailed} (E: 1394d412c4ffa4dd085f269b43338826)`); } } // we have now populated payloadIbGibsDomain } return { frame: ackFrame, payloadIbGibsDomain, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { gapTimer.stop(); if (logalot) { console.log(`${lc} complete.`); } } } /** * Handles the `Ack` frame. * * @remarks * **Execution Context**: **Sender (Local)**. * * The Sender reacts to the Receiver's requirements: * 1. `deltaRequestAddrInfos`: Receiver wants this data. Sender takes this * into account, plus gathers it from `initDomainGraph` and puts them in * `payloadIbGibs` (for next frame). * 2. `pushOfferAddrs`: Receiver has newer data. these should have been * included in the incoming context from the receiver.. * * Returns a `Delta` frame. */ private async handleAckFrame({ sagaContext, sagaIbGib, initDomainGraph, controlSpace, domainSpace, myTempSpace, metaspace, }: { sagaContext: SyncSagaContextIbGib_V1, sagaIbGib: SyncIbGib_V1, /** * This is the initial dependency graph of all domain ibgibs passed in * to the original {@link sync} call. * * if we're executing on the sender, this will be populated */ initDomainGraph: FlatIbGibGraph, controlSpace: IbGibSpaceAny, domainSpace: IbGibSpaceAny, myTempSpace: IbGibSpaceAny, metaspace: MetaspaceService, }): Promise { const lc = `${this.lc}[${this.handleAckFrame.name}]`; const ackTimer = startPerfTimer(`[sync-saga][handleAckFrame]`); try { if (logalot) { console.log(`${lc} starting... (I: 605b6860e898267a5b50c6d85704be26)`); } const { messageData, } = await this.getStageAndPayloadFromFrame({ sagaFrame: sagaIbGib, controlSpace }); const ackData = messageData as SyncSagaMessageAckData_V1; /** * if at any time we find that commit will not be possible, this * will be set to false. */ let proposeCommit = true; // #region sanity/validation if (!ackData) { throw new Error(`${lc} ackData falsy (E: 3b8415edc876084c88a25b98e2d55826)`); } if (ackData.stage !== SyncStage.ack) { throw new Error(`${lc} Invalid ack frame: ackData.stage !== SyncStage.ack (E: 2e8b0a94b5954a66a6a1a7a0b3f5b7a1)`); } if (logalot) { console.log(`${lc} ackData: ${pretty(ackData)} (I: b817c5571c5e916fe8f90b892b3e8e26)`); } if (!sagaIbGib.data) { throw new Error(`(UNEXPECTED) sagaIbGib.data falsy? (E: e3f2e8f162484859787651b85c011826)`); } // #region sanity/validation // 1. Check for Conflicts /** * Starts off as a COPY of ackData.conflicts. But if conflicts * exist, we can now update these conflicts in place without * mutating ackData, and then include the modified conflicts in the * return Delta frame. */ const conflicts = (ackData.conflicts ? clone(ackData.conflicts) : []) as SyncSagaConflictInfo[]; if (sagaIbGib.data?.mode === SyncMode.pull || ackData.mode === SyncMode.pull) { conflicts.length = 0; proposeCommit = true; } if (logalot) { console.log(`${lc} [CONFLICT DEBUG] Received conflicts from Ack: ${conflicts.length}`); } if (logalot && conflicts.length > 0) { console.log(`${lc} [CONFLICT DEBUG] Conflicts detail: ${JSON.stringify(conflicts, null, 2)}`); } const terminalConflicts = conflicts.filter(c => c.terminal); if (terminalConflicts.length > 0) { if (logalot) { console.warn(`${lc} Received terminal conflicts from Ack: ${JSON.stringify(terminalConflicts)}`); } // Terminal failure. Sender should probably Commit(Fail) or just // Abort. For now, throw to trigger abort. the incoming ack // frame has already been persisted in local durable controlSpace by // now. throw new Error(`${lc} Peer reported terminal conflicts. (E: 23a0096ee05a2ccfa89334e8f156b426)`); } // we are the SENDER at this point in the sync process. // at this point, if we have conflicts, they are non-terminal. But // we will not have enough info to do the merge yet. We **do** have // enough knowledge to calculate the latestCommonFrameAddr, which // means we have enough info to calculate the delta that we // **know** the receiver does not have. So we send those delta // ibgibs that we know the receiver needs to do the merge, and we // update the conflict info with the addrs that we sent. So the // receiver will have full knowledge to complete the merge. /** * These are ibgibs that we know the remote does not have. The other * end will have to do the actual merging (assuming feasability). */ const outgoingPayloadIbGibsDomain_conflicts: IbGib_V1[] = []; const activeConflicts: SyncSagaConflictInfo[] = []; if (conflicts.length > 0) { if (logalot) { console.log(`${lc} [CONFLICT DEBUG] Processing ${conflicts.length} non-terminal conflicts`); } for (const conflict of conflicts) { const { receiverTipAddr, reason, senderTipAddr, // latestCommonFrameAddr, // to be determined in this handler terminal, receiverKnowledgeTimelineAddrs, tjpAddr, } = conflict; if (terminal) { throw new Error(`(UNEXPECTED) conflict.terminal truthy? We expect this to already throw/abort the saga before this point in execution. (E: b42e982edca8b1156765de38f9e74626)`); } // get the latest common frame addr let senderTipIbGib = initDomainGraph[senderTipAddr]; if (!senderTipIbGib) { throw new Error(`(UNEXPECTED) senderTipIbGib falsy? initDomainGraph should have had the senderTipAddr (${senderTipAddr}) that was included in the ack frame conflicts. tjpAddr: ${tjpAddr}. reason: ${reason} (E: 3bd80f2054a924be98e6a7421bff4626)`); } // we get the full history because we need the new tip if it exists const { headIbGib, orderedPastIbGibs } = await getHistory({ timeline: senderTipIbGib, getLatest: true, metaspace, space: domainSpace, }); const historyAddrs: IbGibAddr[] = orderedPastIbGibs.map(x => getIbGibAddr({ ibGib: x })); const latestLocalAddr = getIbGibAddr({ ibGib: headIbGib }); conflict.senderKnowledgeTimelineAddrs = [...historyAddrs, latestLocalAddr]; if (headIbGib.gib !== senderTipIbGib.gib) { // #region edge case: changed since sync started with new local addr conflict.senderTipAddr = latestLocalAddr; // update the conflict with the new addr...hmmm if (!initDomainGraph[latestLocalAddr]) { // small chance that history has evolved since the sync saga // started, but this is low probability for known immediate // use cases, and if the local *is* changed even more, our // conflict merge approach does not change (and should still // work just as well). const newDepGraph = await getDependencyGraph({ ibGibAddr: latestLocalAddr, live: false, skipRel8nNames: [B2TFS_CHILD_ITEM_REL8N_NAME], space: domainSpace, }); const newDepGraphAddrs = Object.keys(newDepGraph); for (const newDepGraphAddr of newDepGraphAddrs) { if (!initDomainGraph[newDepGraphAddr]) { initDomainGraph[newDepGraphAddr] = newDepGraph[newDepGraphAddr]!; } } } // #endregion edge case: changed since sync started with new local addr } const historyAddrsSet = new Set(historyAddrs); const latestCommonFrameAddr = receiverKnowledgeTimelineAddrs.findLast(x => historyAddrsSet.has(x)); if (!latestCommonFrameAddr) { throw new Error(`(UNEXPECTED) no latestCommonFrameAddr in the conflicts.receiverKnowledgeTimelineAddrs (${receiverKnowledgeTimelineAddrs.join('\n')})? This would mean that it doesn't even have the tjpAddr (${tjpAddr}). So what are we doing here? (E: 8931d1bdd6d8e100bf55f7c8a6924826)`); } let accretivePayloadAddrs: IbGibAddr[] = []; if (this.currentAdapter?.computeDeltaPayload) { const deltaResult = await this.currentAdapter.computeDeltaPayload({ latestCommonFrameAddr, latestLocalAddr, localSpace: domainSpace, }); if (deltaResult) { accretivePayloadAddrs = deltaResult.deltaPayloadAddrs; deltaResult.deltaPayloadIbGibs.forEach(deltaPayloadIbGib => { outgoingPayloadIbGibsDomain_conflicts.push(deltaPayloadIbGib); }); } } if (accretivePayloadAddrs.length === 0) { const deltaGraph = await getDeltaDependencyGraph({ ibGibAddr: latestLocalAddr, live: false, latestCommonFrameAddr, skipRel8nNames: [B2TFS_CHILD_ITEM_REL8N_NAME], space: domainSpace, }); Object.keys(deltaGraph).forEach(deltaPayloadAddr => { accretivePayloadAddrs.push(deltaPayloadAddr); const deltaPayloadIbGib = deltaGraph[deltaPayloadAddr]; outgoingPayloadIbGibsDomain_conflicts.push(deltaPayloadIbGib); }); } const isFastForward = latestCommonFrameAddr === receiverTipAddr; if (isFastForward) { if (logalot) { console.log(`${lc} [CONFLICT DEBUG] TJP ${tjpAddr}: Fast-forward detected (receiver behind sender). Excluding from active conflicts and sending delta payload.`); } } else { const conflictStrategy = sagaIbGib.data.conflictStrategy || SyncConflictStrategy.abort; if (conflictStrategy === SyncConflictStrategy.abort) { conflict.terminal = true; throw new Error(`the saga has terminal conflicts. conflicts: ${JSON.stringify([conflict])} (E: f2edbe93cc07a63b38bfc013d2213b26)`); } if (conflict.accretivePayloadAddrs) { throw new Error(`(UNEXPECTED) conflict.accretivePayloadAddrs already truthy? This is expected to be falsy at this point in the sync. (E: 6b6b1846779867849cbde208f4374326)`); } conflict.accretivePayloadAddrs = accretivePayloadAddrs; activeConflicts.push(conflict); } } if (activeConflicts.length > 0) { proposeCommit = false; } else { proposeCommit = true; } if (logalot) { console.log(`${lc} [CONFLICT DEBUG] Finished processing ${conflicts.length} conflicts. Active (divergent) conflicts: ${activeConflicts.length}. outgoingPayloadIbGibsDomain_conflicts.length (total outgoing payload ibgibs for ALL conflicts): ${outgoingPayloadIbGibsDomain_conflicts.length}`); } ackTimer.mark(`processed ${conflicts.length} conflicts delta graphs (active: ${activeConflicts.length})`); } else { if (logalot) { console.log(`${lc} [CONFLICT DEBUG] No optimistic conflicts to process`); } } // 2. Prepare Delta Payload (What Receiver Requesting + Our Conflict Logic) /** * these were requested addrs on the INCOMING frame (the ack data). * * This is in contrast to any OUTGOING requests we make in this * method. */ const outgoingPayloadIbGibsDomain_requestedByAck = await this.getPayloadsForRequestedInfos({ deltaRequestAddrInfos: ackData.deltaRequestAddrInfos || [], domainSpace, }); let outgoingPayloadsDomain_all: IbGib_V1[] | undefined = undefined; let outgoingPayloadsDomainAddrs_all: IbGibAddr[] | undefined = undefined; const combinedRaw = [ ...outgoingPayloadIbGibsDomain_conflicts, ...outgoingPayloadIbGibsDomain_requestedByAck, ]; if (combinedRaw.length > 0) { const uniqueMap = new Map(); for (const ibGib of combinedRaw) { const addr = getIbGibAddr({ ibGib }); if (!uniqueMap.has(addr)) { uniqueMap.set(addr, ibGib); } } outgoingPayloadsDomain_all = Array.from(uniqueMap.values()); outgoingPayloadsDomainAddrs_all = Array.from(uniqueMap.keys()); } // #region Non-Destructive Shadow Gap Analysis Parity Assertion const branchConflict = ackData.conflicts?.find(x => (this.currentAccelerationHint?.branchAddr && x.senderTipAddr === this.currentAccelerationHint.branchAddr) || x.tjpAddr.startsWith('b2tfs_branch') || x.senderTipAddr.startsWith('b2tfs_branch') ); const branchRequest = ackData.deltaRequestAddrInfos?.find(x => (this.currentAccelerationHint?.branchAddr && x.addr === this.currentAccelerationHint.branchAddr) || x.addr.startsWith('b2tfs_branch') ); const isIncrementalBranchSync = !!branchConflict?.receiverTipAddr || !!branchRequest?.latestAddrAlreadyHave; if (this.currentAccelerationHint && this.currentAccelerationHint.previousSnapshotAddr && isIncrementalBranchSync) { // Filter out DNA transform stones and non-branch timeline stones (cosmos, galaxy) // because the snapshot acceleration hint specifically tracks branch snapshot tree diffs without DNA. const genericPayloadAddrs = new Set( (outgoingPayloadsDomainAddrs_all || []).filter(addr => { const isDnaStone = addr.startsWith('dna^') || addr.startsWith('dna ') || addr.startsWith('mut8^') || addr.startsWith('mut8 ') || addr.startsWith('rel8^') || addr.startsWith('rel8 ') || addr.startsWith('fork^') || addr.startsWith('fork '); const isCosmosOrGalaxy = addr.startsWith('cosmos ') || addr.startsWith('cosmos^') || addr.startsWith('galaxy ') || addr.startsWith('galaxy^') || addr.startsWith('b2tfs_galaxy ') || addr.startsWith('b2tfs_galaxy^'); return !isDnaStone && !isCosmosOrGalaxy; }) ); const acceleratedPayloadAddrs = new Set(this.currentAccelerationHint.changedAddrs); console.log(`${lc} [SHADOW DEBUG] genericPayloadAddrs (${genericPayloadAddrs.size}):\n${[...genericPayloadAddrs].join('\n')}`); console.log(`${lc} [SHADOW DEBUG] acceleratedPayloadAddrs (${acceleratedPayloadAddrs.size}):\n${[...acceleratedPayloadAddrs].join('\n')}`); const inGenericNotAccelerated = [...genericPayloadAddrs].filter(a => !acceleratedPayloadAddrs.has(a)); const inAcceleratedNotGeneric = [...acceleratedPayloadAddrs].filter(a => !genericPayloadAddrs.has(a)); if (inGenericNotAccelerated.length > 0 || inAcceleratedNotGeneric.length > 0) { const msg = `${lc} [SHADOW GAP ANALYSIS MISMATCH] (W: d9a712f0b34e56c78912ef0134567890) Parity discrepancy detected between generic gap analysis and snapshot acceleration manifest.\n` + `Addresses in generic but missing in accelerated (${inGenericNotAccelerated.length}):\n${inGenericNotAccelerated.join('\n')}\n` + `Addresses in accelerated but missing in generic (${inAcceleratedNotGeneric.length}):\n${inAcceleratedNotGeneric.join('\n')}`; console.warn(msg); } else { console.log(`${lc} [SHADOW GAP ANALYSIS] 100% PARITY VERIFIED! Generic (${genericPayloadAddrs.size}) === Accelerated (${acceleratedPayloadAddrs.size}) addresses.`); } } else if (this.currentAccelerationHint && !isIncrementalBranchSync) { console.log(`${lc} [SHADOW GAP ANALYSIS] Initial branch push detected (receiver has no prior branch tip). Skipping incremental shadow check.`); } // #endregion Non-Destructive Shadow Gap Analysis Parity Assertion // 3. Create Delta Frame in controlSpace const deltaData: SyncSagaMessageDeltaData_V1 = { sagaId: sagaIbGib.data.uuid, stage: SyncStage.delta, /** * these are the modified conflicts with additional information. */ conflicts: activeConflicts, /** * we're sending these domain ibgibs as payload (they were * requested by receiver and/or they are being sent as delta * deps for conflicts) */ payloadAddrsDomain: outgoingPayloadsDomainAddrs_all, /** * we're asking for these addrs. */ deltaRequestAddrInfos: undefined, /** * if we have no changes and request none, propose commit to * finish the sync transaction. */ proposeCommit, }; let rel8ns: SyncSagaMessageRel8ns_V1 | undefined = undefined; if (logalot) { console.log(`${lc} Creating Delta Stone. Data stage: ${deltaData.stage}`); } const deltaStone = await this.createSyncMsgStone({ data: deltaData, rel8ns, controlSpace, metaspace, }); const deltaFrame = await this.evolveSyncSagaIbGib({ prevSagaIbGib: sagaIbGib, msgStones: [deltaStone], controlSpace, metaspace, }); if (logalot) { console.log(`${lc} Delta Frame created. Rel8ns: ${JSON.stringify(deltaFrame.rel8ns)}`); } return { frame: deltaFrame, payloadIbGibsDomain: outgoingPayloadsDomain_all, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { ackTimer.stop(); if (logalot) { console.log(`${lc} complete.`); } } } /** * Handles the `Delta` frame. * * @remarks * **Execution Context**: **Both** ?? * * At this time, I only conceive this as being executed by the receiver. * Initially, I was thinking that it would need to be a back and forth, * especially since we were going to resolve one conflict at a time. That * may still end up being the case, but right now (01/27/2026), I'm thinking * we just have the receiver do the merging, since they should have full * knowledge at that point for most (all?) cases AFAICT. */ private async handleDeltaFrame({ sagaContext, sagaIbGib, controlSpace, domainSpace, myTempSpace, metaspace, }: { sagaContext: SyncSagaContextIbGib_V1, sagaIbGib: SyncIbGib_V1, controlSpace: IbGibSpaceAny, domainSpace: IbGibSpaceAny, myTempSpace: IbGibSpaceAny, metaspace: MetaspaceService, }): Promise { const lc = `${this.lc}[${this.handleDeltaFrame.name}]`; const deltaTimer = startPerfTimer(`[sync-saga][handleDeltaFrame]`); try { if (logalot) { console.log(`${lc} starting... (I: a1d0a85eb4189466f86dfd61e3df2626)`); } const { messageData } = await this.getStageAndPayloadFromFrame({ sagaFrame: sagaIbGib, controlSpace }); const deltaData = messageData as SyncSagaMessageDeltaData_V1; // #region validate/sanity if (!sagaIbGib.data) { throw new Error(`(UNEXPECTED) sagaIbGib.data falsy? (E: 8874e83e1a1b307938ee832862ec5826)`); } if (!sagaIbGib.data.conflictStrategy) { throw new Error(`(UNEXPECTED) sagaIbGib.data.conflictStrategy falsy? (E: 636205ab5b78fcb31d0cb1880770c826)`); } if (!deltaData) { throw new Error(`${lc} deltaData falsy (E: 7c28c8d8f08a4421b8344e6727271421)`); } if (deltaData.stage !== SyncStage.delta) { throw new Error(`${lc} Invalid delta frame: deltaData.stage !== SyncStage.delta (E: 0c28c8d8f08a4421b8344e6727271421)`); } // #endregion validate/sanity if (logalot) { console.log(`${lc} deltaData: ${pretty(deltaData)} (I: a76008681df458cfbcdc4848f825a826)`); } if (logalot) { console.log(`${lc} [CONFLICT DEBUG] deltaData.payloadAddrsDomain count: ${deltaData.payloadAddrsDomain?.length || 0}`); } const { conflictStrategy, graftPreference } = sagaIbGib.data; const { deltaRequestAddrInfos, payloadAddrsDomain, proposeCommit, } = deltaData; const peerProposesCommit = deltaData.proposeCommit ?? false; /** * these are already in the local/receiver temp space */ const receivedPayloadIbGibs: IbGib_V1[] = sagaContext.payloadIbGibsDomain ?? []; for (const payload of receivedPayloadIbGibs) { if (isKeystone(payload)) { throw new Error(`Security violation: Keystone found in sagaContext.payloadIbGibsDomain (${getIbGibAddr({ ibGib: payload })}). Keystones must never be transmitted via domain sync. (E: 7a829108b4ef4c2988cb104928fe3926)`); } } // 2. Fulfill Peer Requests (Outgoing Payload with Delta Dependencies) from domainSpace if (logalot) { console.log(`${lc} [CONFLICT DEBUG] Fulfilling ${(deltaData.deltaRequestAddrInfos || []).length} peer requests`); } const outgoingPayload = await this.getPayloadsForRequestedInfos({ deltaRequestAddrInfos: deltaData.deltaRequestAddrInfos || [], domainSpace, }); if (logalot) { console.log(`${lc} [CONFLICT DEBUG] Outgoing payload size (with deps): ${outgoingPayload.length}`); } // if we have conflicts, then we should be able to resolve them now // at this point, yes? // iterate through any conflicts, performing the merges const conflicts = (deltaData.conflicts ? clone(deltaData.conflicts) : []) as SyncSagaConflictInfo[]; const unresolvedConflicts = conflicts.filter(x => !x.resolved); if (unresolvedConflicts.length > 0) { // #region sanity conflictStrategy if (conflictStrategy !== SyncConflictStrategy.optimisticWithLCS) { throw new Error(`(UNEXPECTED) conflictStrategy (${conflictStrategy}) is not ${SyncConflictStrategy.optimisticWithLCS}? right now, this is the only one we've implemented. (E: ba3e08d92a66b24075016208a0f83226)`); } // #endregion sanity conflictStrategy deltaTimer.mark(`start resolving ${unresolvedConflicts.length} conflicts`); const baseReceivedPayloadMap: FlatIbGibGraph = {}; if (receivedPayloadIbGibs.length > 0) { await putInSpace_dnasThenNonDnas({ ibGibs: receivedPayloadIbGibs, space: myTempSpace, }); for (const rxIbGib of receivedPayloadIbGibs) { baseReceivedPayloadMap[getIbGibAddr({ ibGib: rxIbGib })] = rxIbGib; } } const outgoingPayloadAddrsSet = new Set(outgoingPayload.map(x => getIbGibAddr({ ibGib: x }))); for (let cIdx = 0; cIdx < unresolvedConflicts.length; cIdx++) { const unresolvedConflict = unresolvedConflicts[cIdx]; const conflictTimer = startPerfTimer(`[sync-saga][conflict ${cIdx + 1}/${unresolvedConflicts.length} (${unresolvedConflict.tjpAddr.slice(0, 24)})]`); // gather/populate info const conflictPayloadIbGibMap: FlatIbGibGraph = { ...baseReceivedPayloadMap }; for (const conflictPayloadAddr of (unresolvedConflict.accretivePayloadAddrs ?? [])) { const conflictPayloadIbGib = baseReceivedPayloadMap[conflictPayloadAddr]; if (conflictPayloadIbGib) { conflictPayloadIbGibMap[conflictPayloadAddr] = conflictPayloadIbGib; } } if (unresolvedConflict.latestCommonFrameAddr) { } const { // latestCommonFrameAddr, // is not defined yet receiverKnowledgeTimelineAddrs, senderKnowledgeTimelineAddrs, reason, receiverTipAddr, senderTipAddr, tjpAddr, } = unresolvedConflict; if (!senderKnowledgeTimelineAddrs) { throw new Error(`(UNEXPECTED) senderKnowledgeTimelineAddrs falsy? (E: 2a608892d11bd848e8f0c7a8d676d826)`); } // first we need to ensure that we have the entire // dependency graph from domainSpace in our temp space. const depGraph = await getDependencyGraph({ ibGibAddrs: [receiverTipAddr], live: false, skipRel8nNames: [B2TFS_CHILD_ITEM_REL8N_NAME], space: domainSpace, }); const depGraphIbGibs = Object.values(depGraph); await putInSpace_dnasThenNonDnas({ ibGibs: depGraphIbGibs, space: myTempSpace, }); const receiverTipIbGib = depGraph[receiverTipAddr]; if (receiverTipIbGib) { await registerNewIbGib({ ibGib: receiverTipIbGib, space: myTempSpace }); } // Merge receiver's full dep graph into the read cache so graft // strategies can access both sender's and receiver's ancillary // ibgibs (e.g. binary payload nodes rel8d to timeline items) // without relying solely on a space lookup fallback. for (const [addr, ibGib] of Object.entries(depGraph)) { if (!conflictPayloadIbGibMap[addr]) { conflictPayloadIbGibMap[addr] = ibGib; } } // get the latest common point in the two timelines const receiverKnowledgeSet = new Set(receiverKnowledgeTimelineAddrs); const latestCommonFrameAddr = senderKnowledgeTimelineAddrs.findLast(addrA => receiverKnowledgeSet.has(addrA)); if (!latestCommonFrameAddr) { throw new Error(`(UNEXPECTED) latestCommonFrameAddr falsy? how we can have a conflict without a common point in history? (E: 53de0a181838b3e5bf98d0887994b826)`); } const ourDeltaDepGraph = await getDeltaDependencyGraph({ ibGibAddr: unresolvedConflict.receiverTipAddr, latestCommonFrameAddr, live: false, skipRel8nNames: [B2TFS_CHILD_ITEM_REL8N_NAME], space: myTempSpace, }); for (const ourIbGib of Object.values(ourDeltaDepGraph)) { const addr = getIbGibAddr({ ibGib: ourIbGib }); if (!outgoingPayloadAddrsSet.has(addr)) { outgoingPayloadAddrsSet.add(addr); outgoingPayload.push(ourIbGib); } } const graftStrategySvc = GraftStrategyService.instance; const resGraft = await graftStrategySvc.graftTimelines({ conflictStrategy, timelineAddrsA: senderKnowledgeTimelineAddrs, timelineAddrsB: receiverKnowledgeTimelineAddrs, latestCommonFrameAddr, ibGibReadCache: conflictPayloadIbGibMap, space: myTempSpace, graftPreference: graftPreference || GraftPreference.timestamp, }); const { dnasCreatedInGraft, dnasReplayed, intermediateIbGibsCreatedInGraft, ancillaryIbGibsCreated, newGraftTip, graftInfoCreated, } = resGraft; unresolvedConflict.createdDnaAddrs = dnasCreatedInGraft.map(x => getIbGibAddr({ ibGib: x })); unresolvedConflict.replayedDnaAddrs = dnasReplayed.map(x => getIbGibAddr({ ibGib: x })); unresolvedConflict.createdDomainAddrs = [ ...intermediateIbGibsCreatedInGraft.map(x => getIbGibAddr({ ibGib: x })), ...ancillaryIbGibsCreated.map(x => getIbGibAddr({ ibGib: x })), getIbGibAddr({ ibGib: graftInfoCreated }), getIbGibAddr({ ibGib: newGraftTip }) ]; // get/populate the graftInfoAddr for this conflict if (!newGraftTip.rel8ns) { throw new Error(`(UNEXPECTED) newGraftTip.rel8ns falsy? we expect this to have graftinfo rel8ns, let alone dna (E: 718788f5a44e815618ac1ba621c8a826)`); } const graftInfoAddrs = newGraftTip.rel8ns[GRAFT_INFO_REL8N_NAME]; if (!graftInfoAddrs || graftInfoAddrs.length === 0) { throw new Error(`(UNEXPECTED) newGraftTip.rel8ns.${GRAFT_INFO_REL8N_NAME} falsy/empty? we expect to always have graft info attached to timelines that are grafted. (E: 45abf31654c8aa517df4d0882b996826)`); } unresolvedConflict.graftInfoAddr = graftInfoAddrs.at(-1)!; // add to ibgibs created in graft to both conflict info (via // addrs) and the outgoingPayload const ibGibsCreatedOrReplayedInGraft = [ dnasCreatedInGraft, dnasReplayed, intermediateIbGibsCreatedInGraft, ancillaryIbGibsCreated, [graftInfoCreated, newGraftTip] ]; // #region debug for (const ibGib of ibGibsCreatedOrReplayedInGraft.flat()) { const validationErrors = await validateIbGibIntrinsically({ ibGib }) ?? []; if (validationErrors.length > 0) { console.dir(ibGib); debugger; console.log(pretty(ibGib)); } } // #endregion debug unresolvedConflict.accretivePayloadAddrs ??= []; const accretiveAddrsSet = new Set(unresolvedConflict.accretivePayloadAddrs); for (const ibGibList of ibGibsCreatedOrReplayedInGraft) { for (const ibGibCreated of ibGibList) { const addrCreated = getIbGibAddr({ ibGib: ibGibCreated }); if (!accretiveAddrsSet.has(addrCreated)) { accretiveAddrsSet.add(addrCreated); unresolvedConflict.accretivePayloadAddrs.push(addrCreated); } if (!outgoingPayloadAddrsSet.has(addrCreated)) { outgoingPayloadAddrsSet.add(addrCreated); outgoingPayload.push(ibGibCreated); } } } unresolvedConflict.resolved = true; conflictTimer.stop(); } deltaTimer.mark(`finished resolving ${unresolvedConflicts.length} conflicts`); } // 4. Determine Next Action const myRequests: string[] = []; // If we had more needs (e.g. partial payload), we'd add here. const hasOutgoing = outgoingPayload.length > 0; const hasMyRequests = myRequests.length > 0; if (hasOutgoing || hasMyRequests) { // We have business to attend to -> Send Delta in controlSpace const responseDeltaData: SyncSagaMessageDeltaData_V1 = { sagaId: deltaData.sagaId, stage: SyncStage.delta, payloadAddrsDomain: outgoingPayload.map(p => getIbGibAddr({ ibGib: p })), requests: hasMyRequests ? myRequests : undefined, conflicts: conflicts }; const deltaStone = await this.createSyncMsgStone({ data: responseDeltaData, controlSpace, metaspace, }); const deltaFrame = await this.evolveSyncSagaIbGib({ prevSagaIbGib: sagaIbGib, msgStones: [deltaStone], controlSpace, metaspace, }); return { frame: deltaFrame, payloadIbGibsDomain: outgoingPayload }; } else { // We have nothing to send. if (peerProposesCommit) { // Peer is done. We are done. -> Commit. const history = await getFullSyncSagaHistory({ sagaIbGib, controlSpace, }); const validationErrors = await validateFullSyncSagaHistory({ history, }); if (validationErrors.length > 0) { const errorCommitFrame = await this.createCommitFrame({ sagaIbGib, errors: validationErrors, metaspace, controlSpace, }); return { frame: errorCommitFrame, }; /* <<<< returns early */ } await this.executeLocalCommit({ sagaHistory: history, deltaFrame: sagaIbGib, localTempSpace: myTempSpace, domainSpace, metaspace, }) const commitFrame = await this.createCommitFrame({ sagaIbGib, errors: undefined, metaspace, controlSpace, }); return { frame: commitFrame, }; } else { // peer did NOT propose commit (maybe they just sent data/requests and didn't ready flag). // But we are empty. // So WE propose commit. const responseDeltaData: SyncSagaMessageDeltaData_V1 = { sagaId: deltaData.sagaId, stage: SyncStage.delta, proposeCommit: true, conflicts, }; const deltaStone = await this.createSyncMsgStone({ data: responseDeltaData, controlSpace, metaspace }); const deltaFrame = await this.evolveSyncSagaIbGib({ prevSagaIbGib: sagaIbGib, msgStones: [deltaStone], controlSpace, metaspace }); // Check if PEER proposed commit if (deltaData.proposeCommit) { if (logalot) { console.log(`${lc} Peer proposed commit. Accepting & Committing.`); } // Peer wants to commit and has no more requests. // We should Commit. const commitData: SyncSagaMessageCommitData_V1 = { sagaId: deltaData.sagaId, stage: SyncStage.commit, success: true, }; const commitStone = await this.createSyncMsgStone({ data: commitData, controlSpace, metaspace }); const commitFrame = await this.evolveSyncSagaIbGib({ prevSagaIbGib: deltaFrame, // Build on top of the Delta we just created/persisted msgStones: [commitStone], controlSpace, metaspace }); return { frame: commitFrame, }; } return { frame: deltaFrame, payloadIbGibsDomain: outgoingPayload }; } } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { deltaTimer.stop(); if (logalot) { console.log(`${lc} complete.`); } } } /** * should throw if fails */ private async executeLocalCommit({ deltaFrame, commitFrame, sagaHistory, metaspace, domainSpace, localTempSpace, }: { deltaFrame?: SyncIbGib_V1; commitFrame?: SyncIbGib_V1; sagaHistory: SyncSagaFrameDependencyGraph[]; metaspace: MetaspaceService; domainSpace: IbGibSpaceAny; localTempSpace: IbGibSpaceAny; }): Promise { const lc = `${this.lc}[${this.executeLocalCommit.name}]`; const commitTimer = startPerfTimer(`[sync-saga][executeLocalCommit]`); try { if (logalot) { console.log(`${lc} starting... (I: 6734980446b86a63c1af6e2e206de826)`); } if (!deltaFrame && !commitFrame) { throw new Error(`(UNEXPECTED) !deltaFrame && !commitFrame? we're expecting to execute the commit based off of EITHER a delta OR a commit frame. (E: 10cae319a2685a672866f5583514e326)`); } else if (deltaFrame && commitFrame) { throw new Error(`(UNEXPECTED) deltaFrame && commitFrame? we're expecting to execute the commit based off of EITHER a delta OR a commit frame. (E: b9037b1ed6d8684ac8a5d01328bad826)`); } /** * Sync has a two-stage commit. The first is from a delta frame with * `proposeCommit: true`. That produces a commit frame, which on the * other end triggers the second leg. */ const isFirstCommitLeg = !!deltaFrame; const currentFrame = isFirstCommitLeg ? deltaFrame : commitFrame; if (!currentFrame) { throw new Error(`(UNEXPECTED) !currentFrame? something wrong with my logic. (E: 4ec0ce6625cc1d677bc902c839ca1a26)`); } const currentFrameOrigin = getSyncSagaFrameOrigin({ sagaFrame: currentFrame }); if (logalot) { console.log(`${lc} currentFrameOrigin: ${currentFrameOrigin} (I: 3add8f8390c89743ae554bd3cc60b826)`); } // #region validate/sanity if (!currentFrame.data) { throw new Error(`(UNEXPECTED) currentFrame.data falsy? (E: a8be68d48668d93d992d793834823826)`); } // #endregion validate/sanity // * move all payload addrs from temp space to durable domainSpace // * register each and every iteration of each timeline (including // stones, which are like their own sealed timeline of length 1) const allPayloadAddrsDomainReceived: IbGibAddr[] = []; const fnAddPayloadAddr = (addr: IbGibAddr) => { if (!allPayloadAddrsDomainReceived.includes(addr)) { allPayloadAddrsDomainReceived.push(addr); } } const sagaHistory_onlyMyEnd = sagaHistory.filter(x => { const frameExecutionContext = getSyncSagaFrameOrigin({ sagaFrame: x.sagaIbGib }); return currentFrameOrigin !== frameExecutionContext; }); const sagaHistory_onlyOtherParty = sagaHistory.filter(x => { const frameExecutionContext = getSyncSagaFrameOrigin({ sagaFrame: x.sagaIbGib }); return currentFrameOrigin === frameExecutionContext; }); sagaHistory_onlyOtherParty.forEach(x => { if (!x.sagaIbGib.data) { throw new Error(`(UNEXPECTED) sagaIbGib.data falsy? (E: 34d7f8cdee14717ce828878d98f89826)`); } x.msgStones.forEach(msgStone => { if (!msgStone.data) { throw new Error(`(UNEXPECTED) msgStone.data falsy? (E: 21406101f91847514cc759c8a7382f26)`); } if (msgStone.data.stage === SyncStage.ack) { const ackData = msgStone.data as SyncSagaMessageAckData_V1; if (ackData.pushOfferInfos && ackData.pushOfferInfos.length > 0) { ackData.pushOfferInfos.forEach(info => { info.addrs.forEach(addr => fnAddPayloadAddr(addr)); }); } } else if (msgStone.data.stage === SyncStage.delta) { const deltaData = msgStone.data as SyncSagaMessageDeltaData_V1; if (deltaData.payloadAddrsDomain && deltaData.payloadAddrsDomain.length > 0) { deltaData.payloadAddrsDomain.forEach(addr => fnAddPayloadAddr(addr)); } } }) }); if (logalot) { console.log(`${lc}[${currentFrameOrigin}] allPayloadAddrsDomainTransferred: ${allPayloadAddrsDomainReceived.length > 0 ? allPayloadAddrsDomainReceived.join(', ') : 'none'} (I: a1950eb3ca95bdc9ec18a4b8823e9826)`); } let allPayloadIbGibsDomainTransferred: IbGib_V1[] = []; if (allPayloadAddrsDomainReceived.length > 0) { const resGetAllTransferred = await getFromSpace({ addrs: allPayloadAddrsDomainReceived, space: localTempSpace }); if (resGetAllTransferred.success && resGetAllTransferred.ibGibs && resGetAllTransferred.ibGibs.length === allPayloadAddrsDomainReceived.length) { allPayloadIbGibsDomainTransferred = resGetAllTransferred.ibGibs.concat(); } else { // errored out, gather info if (!resGetAllTransferred.rawResultIbGib) { throw new Error(`(UNEXPECTED) !resGetAllTransferred.rawResultIbGib falsy? (E: dc6cf8729668f4fbe8c024f887d97a26)`); } const { addrsNotFound, addrsErrored, errors } = resGetAllTransferred.rawResultIbGib.data as IbGibSpaceResultData; throw new Error(`(UNEXPECTED) we couldn't get all addrs transferred throughout the saga from the tempspace (${localTempSpace.ib})? addrsNotFound: ${addrsNotFound ?? []}. addrsErrored: ${addrsErrored ?? []}. errors: ${errors ?? []}(E: 222e341e634862b4d88ae7282584d826)`); } } const createdFromConflictGraftsIbGibs: IbGib_V1[] = []; const finalConflicts = await getFinalConflictsInfo({ sagaHistory }); if (finalConflicts) { // examine the conflicts for (const finalConflict of finalConflicts) { if (!finalConflict.resolved) { throw new Error(`(UNEXPECTED) finalConflict.resolved falsy? right now, we're expecting to resolve all conflicts. (E: a40ca8f1f54665407892ec21123a4f26)`); } if (!finalConflict.graftInfoAddr) { throw new Error(`(UNEXPECTED) finalConflict resolved but graftInfoAddr falsy? we're expecting all resolved conflicts to have a graftInfoAddr (E: d082488347570947b82008a835200126)`); } const resGetGraftIbGibs = await getIbGibsFromCache_fallbackToSpaces({ addrs: [finalConflict.graftInfoAddr], space: localTempSpace, }); const finalConflictGraftInfo = resGetGraftIbGibs.at(0) as GraftInfoIbGib_V1; if (!finalConflictGraftInfo) { throw new Error(`(UNEXPECTED) couldn't get finalConflictGraftInfo from localTempSpace (${localTempSpace})? (E: 35e3c8130608d991e8fb295807812826)`); } const { createdDnaAddrs, replayedDnaAddrs, createdDomainAddrs } = finalConflict; if (!createdDnaAddrs || createdDnaAddrs.length === 0) { throw new Error(`(UNEXPECTED) finalConflict.createdDnaAddrs falsy/empty? (E: 9689f8be5bd19650b8d4a058b65db826)`); } if (!replayedDnaAddrs || replayedDnaAddrs.length === 0) { if (logalot) { console.log(`${lc} finalConflict.replayedDnaAddrs falsy/empty (I: e88eb8a76b5815e07f10cbb2fa2ab826)`); } } if (!createdDomainAddrs || createdDomainAddrs.length === 0) { throw new Error(`(UNEXPECTED) finalConflict.createdDomainAddrs falsy/empty? (E: cc41251d1acfe91a48d1b6080259ed26)`); } /** throws if not all found */ const resGetCreated = await getIbGibsFromCache_fallbackToSpaces({ addrs: replayedDnaAddrs && replayedDnaAddrs.length > 0 ? [...createdDnaAddrs, ...replayedDnaAddrs, ...createdDomainAddrs] : [...createdDnaAddrs, ...createdDomainAddrs], space: localTempSpace, }); resGetCreated.forEach(x => createdFromConflictGraftsIbGibs.push(x)); } } const allTransferredOrCreatedFromGraftIbGibs: IbGib_V1[] = []; allPayloadIbGibsDomainTransferred.forEach(x => allTransferredOrCreatedFromGraftIbGibs.push(x)); createdFromConflictGraftsIbGibs.forEach(x => allTransferredOrCreatedFromGraftIbGibs.push(x)); // now we have all ibgibs transferred, first put them all in the domainSpace for (const item of allTransferredOrCreatedFromGraftIbGibs) { if (isKeystone(item)) { throw new Error(`Security violation: Cannot commit keystone (${getIbGibAddr({ ibGib: item })}) to domainSpace (${domainSpace.ib}). Keystones are strictly restricted to controlSpace. (E: b929108fcaef4919882b71948cf20826)`); } } if (allTransferredOrCreatedFromGraftIbGibs.length === 0) { // nothing was synced if (logalot) { console.log(`${lc}[${currentFrameOrigin}] no changes on this end (I: fa30d18e83a87ee9e8487fbb5d632b26)`); } } else { // we did have payloads synced, so store them and register them in domainSpace if (logalot) { console.log(`${lc}[${currentFrameOrigin}] ${allTransferredOrCreatedFromGraftIbGibs.length} changes detected (I: fa30d18e83a87ee9e8487fbb5d632b26)`); } // first store them in the durable domainSpace (they exist in temp space)... if (logalot) { console.log(`${lc} put all into domainSpace (${domainSpace.ib}) starting... (I: d5e0d9870e380b61e80c729660058826)`); } const { payload_Dnas, payload_NonDnas } = await putInSpace_dnasThenNonDnas({ ibGibs: allTransferredOrCreatedFromGraftIbGibs, space: domainSpace, }); if (logalot) { console.log(`${lc} put all into domainSpace (${domainSpace.ib}) complete. (I: d5e0d9870e380b61e80c729660058826)`); } commitTimer.mark(`putInSpace_dnasThenNonDnas (${allTransferredOrCreatedFromGraftIbGibs.length} items)`); const orphanedAddresses = await getAllOrphanedAddresses({ sagaHistory, /** * we're getting at the graft info, which will be in the temp space */ myTempSpace: localTempSpace, }); const orphanedAddressesSet = new Set(orphanedAddresses); const { mapWithTjp_NoDna, mapWithTjp_YesDna, mapWithoutTjps } = splitPerTjpAndOrDna({ ibGibs: payload_NonDnas, filterPrimitives: true }); // first register all non-tjp stones in domainSpace if (logalot) { console.log(`${lc} register mapWithoutTjps starting... (I: 2b84d8f8dda85adde88696d8419bf726)`); } const nonTjpIbGibs = Object.values(mapWithoutTjps); for (const nontjp of nonTjpIbGibs) { if (logalot) { console.log(`${lc} registering ${getIbGibAddr({ ibGib: nontjp })} (I: 4647b4f42d27cffe0fbfce8846755826)`); } await metaspace.registerNewIbGib({ ibGib: nontjp, space: domainSpace, }); } if (logalot) { console.log(`${lc} mapWithoutTjps complete. (I: 2b84d8f8dda85adde88696d8419bf726)`); } commitTimer.mark(`register mapWithoutTjps (${nonTjpIbGibs.length} items)`); // next register each timeline in order in domainSpace... // ...first the ones without dna... if (logalot) { console.log(`${lc} register mapWithTjp_NoDna starting... (I: 96e648e4db382499b8bfaa1b37c24826)`); } const timelinesByTjpAddr_NoDna = getTimelinesGroupedByTjp({ ibGibs: Object.values(mapWithTjp_NoDna) }); const tjpAddrs_NoDna = Object.keys(timelinesByTjpAddr_NoDna); for (const tjpAddr_NoDna of tjpAddrs_NoDna) { const timelineIbGibs = timelinesByTjpAddr_NoDna[tjpAddr_NoDna]; const tip = timelineIbGibs.at(-1); if (tip) { await metaspace.registerNewIbGib({ ibGib: tip, space: domainSpace, }); } } if (logalot) { console.log(`${lc} register mapWithTjp_NoDna complete. (I: 96e648e4db382499b8bfaa1b37c24826)`); } commitTimer.mark(`register mapWithTjp_NoDna (${tjpAddrs_NoDna.length} TJPs)`); // ...then the ones WITH dna. if (logalot) { console.log(`${lc} register mapWithTjp_YesDna starting... (I: d54a820e9442dee4681f6228a6795926)`); } const timelinesByTjpAddr_YesDna = getTimelinesGroupedByTjp({ ibGibs: Object.values(mapWithTjp_YesDna) }); const tjpAddrs_YesDna = Object.keys(timelinesByTjpAddr_YesDna); for (const tjpAddr_YesDna of tjpAddrs_YesDna) { const timelineIbGibs = timelinesByTjpAddr_YesDna[tjpAddr_YesDna]; const nonOrphaned = timelineIbGibs.filter(ibGib => !orphanedAddressesSet.has(getIbGibAddr({ ibGib }))); const tip = nonOrphaned.at(-1); if (tip) { await metaspace.registerNewIbGib({ ibGib: tip, space: domainSpace, }); } } if (logalot) { console.log(`${lc} register mapWithTjp_YesDna complete. (I: d54a820e9442dee4681f6228a6795926)`); } commitTimer.mark(`register mapWithTjp_YesDna (${tjpAddrs_YesDna.length} TJPs)`); } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { commitTimer.stop(); if (logalot) { console.log(`${lc} complete.`); } } } private async createCommitFrame({ sagaIbGib, errors, metaspace, controlSpace, }: { sagaIbGib: SyncIbGib_V1, /** * if truthy and non-empty, will create an errored commit frame (data * has `success: false`) */ errors?: string[], metaspace: MetaspaceService, controlSpace: IbGibSpaceAny, }): Promise { const lc = `[${this.createCommitFrame.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 48fc57c023f80122135a284855757526)`); } const commitData: SyncSagaMessageCommitData_V1 = errors && errors.length > 0 ? { // errored sagaId: sagaIbGib.data!.uuid, stage: SyncStage.commit, success: false, errors, } : { // not errored sagaId: sagaIbGib.data!.uuid, stage: SyncStage.commit, success: true, }; const commitStone = await this.createSyncMsgStone({ data: commitData, controlSpace, metaspace }); const commitFrame = await this.evolveSyncSagaIbGib({ prevSagaIbGib: sagaIbGib, msgStones: [commitStone], controlSpace, metaspace, }); return commitFrame; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } private async handleCommitFrame({ sagaIbGib, controlSpace, domainSpace, myTempSpace, metaspace, }: { sagaIbGib: SyncIbGib_V1, controlSpace: IbGibSpaceAny, domainSpace: IbGibSpaceAny, myTempSpace: IbGibSpaceAny, metaspace: MetaspaceService, }): Promise { const lc = `${this.lc}[${this.handleCommitFrame.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: e179573bdd881202f8ba3168da1c3826)`); } if (!sagaIbGib.data) { throw new Error(`(UNEXPECTED) sagaIbGib.data falsy? (E: cbc31dbb7d28b5b8c8cddb510d7d2826)`); } if (sagaIbGib.data.errors && sagaIbGib.data.errors.length > 0) { // our saga errored out but we already committed the darn // changes previously throw new Error(`not implemented...saga errored out on other end but we've already committed our changes. we need to implement undoing our changes, i.e., rollback commit, which basically is deleting all the payloads that we already put in in our previous commit. (E: e8eb789e0c08f0b3cf93607cb73e9f26)`); } else { // Sender Logic (Finalizing): // If we are here, we received a Commit frame from the Peer. // This implies the Peer has successfully committed. // We should now: // 1. Validate (implicitly done by receiving valid frame) // 2. Perform our own cleanup (Temp -> Dest, if applicable) // 3. Return saga completion. // one last validate entire history in controlSpace const history = await getFullSyncSagaHistory({ sagaIbGib, controlSpace, }); const validationErrors = await validateFullSyncSagaHistory({ history, }); if (validationErrors.length > 0) { const errorCommitFrame = await this.createCommitFrame({ sagaIbGib, metaspace, controlSpace, errors: validationErrors, }); return { frame: errorCommitFrame, }; /* <<<< returns early */ } await this.executeLocalCommit({ commitFrame: sagaIbGib, sagaHistory: history, domainSpace, localTempSpace: myTempSpace, metaspace, }); // todo: implement explicit cleanup logic here and in peer console.error(`${lc} NAG ERROR (NOT THROWN): implement cleanup logic, including add a cleanup method to the peer (E: 3a9a24befb98a981a88fbdbf52920e26)`); if (logalot) { console.log(`${lc} Peer committed. Finalizing saga locally. Saga Complete.`); } // the holy grail! return { sagaComplete: true }; } } catch (error) { const emsg = `${lc} ${extractErrorMsg(error)}`; console.error(emsg); const errorCommitFrame = await this.createCommitFrame({ sagaIbGib, errors: [emsg], metaspace, controlSpace, }); return { frame: errorCommitFrame } } finally { if (logalot) { console.log(`${lc} complete.`); } } } // #endregion Handlers private async createSyncMsgStone({ data, rel8ns, controlSpace, metaspace, }: { data: TStoneData, rel8ns?: SyncSagaMessageRel8ns_V1, controlSpace: IbGibSpaceAny, metaspace: MetaspaceService, }): Promise> { const lc = `${this.lc}[${this.createSyncMsgStone.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 5f7f98e8ff980364f7191fcee4531e26)`); } const ib = await getSyncSagaMessageIb({ data }); const stone = await Factory_V1.stone({ ib, parentPrimitiveIb: SYNC_SAGA_MSG_ATOM, data, rel8ns, uuid: true, // we want the stone to have its own uniqueness }); if (logalot) { console.log(`${lc} Created stone: ${getIbGibAddr({ ibGib: stone })}`); } await metaspace.put({ ibGib: stone, space: controlSpace }); await metaspace.registerNewIbGib({ ibGib: stone, space: controlSpace }); return stone as IbGib_V1; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } private async getPayloadsForRequestedInfos({ deltaRequestAddrInfos, domainSpace, }: { deltaRequestAddrInfos: SyncSagaRequestAddrInfo[]; domainSpace: IbGibSpaceAny; }): Promise { const lc = `${this.lc}[${this.getPayloadsForRequestedInfos.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 4fe13d0d80050f20a8b74ba80cee5826)`); } /** * graph of ibgibs we will send to the receiver. addr-based, so will * already be unique (no need to call `unique` on the domains * ibgibs) */ const outgoingPayloadIbGibsDomainGraph: FlatIbGibGraph = {}; for (const { addr, latestAddrAlreadyHave } of deltaRequestAddrInfos) { let deltaDepGraph: FlatIbGibGraph; if (latestAddrAlreadyHave) { // already has some, so only get the delta // remember: if we didn't have the other's latest addr, then // this would be in the conflicts not requested addrs deltaDepGraph = await getDeltaDependencyGraph({ ibGibAddr: addr, latestCommonFrameAddr: latestAddrAlreadyHave, space: domainSpace, live: false, skipRel8nNames: [B2TFS_CHILD_ITEM_REL8N_NAME], }); } else { // doesn't have anything, so get the entire dependency graph deltaDepGraph = await getDependencyGraph({ ibGibAddr: addr, space: domainSpace, live: false, skipRel8nNames: [B2TFS_CHILD_ITEM_REL8N_NAME], }); } const depGraphSize = Object.keys(deltaDepGraph).length; if (depGraphSize === 0) { throw new Error(`(UNEXPECTED) couldn't get requested addrs in domainSpace (${domainSpace.ib})? How did the receiver know to ask for these addrs if they weren't in our original graph? (E: 281eaebcdf77dd73e8245b2872100826)`); } else { // we have dependencies! Object.values(deltaDepGraph).forEach(x => { outgoingPayloadIbGibsDomainGraph[getIbGibAddr({ ibGib: x })] = x; }); } } const result = Object.values(outgoingPayloadIbGibsDomainGraph); return result; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Evolves the saga timeline with a new frame in controlSpace. */ private async evolveSyncSagaIbGib({ prevSagaIbGib, conflictStrategy, graftPreference, targetSpaceInfo, msgStones, controlSpace, metaspace, sessionIdentity, }: { prevSagaIbGib?: SyncIbGib_V1, conflictStrategy?: SyncConflictStrategy, graftPreference?: GraftPreference, targetSpaceInfo?: SyncData_V1['targetSpaceInfo'], msgStones: IbGib_V1[], controlSpace: IbGibSpaceAny, metaspace: MetaspaceService, /** * this is only used on the init frame ({@link prevSagaIbGib}). * otherwise, the sessionIdentityTjpAddr for the next sync saga ibgib * frame will be driven by the {@link prevSagaIbGib}. */ sessionIdentity?: KeystoneIbGib_V1 | undefined, }): Promise { const lc = `${this.lc}[${this.evolveSyncSagaIbGib.name}]`; try { // Validation if (!msgStones || msgStones.length === 0) { throw new Error(`${lc} msgStones required (E: d13f8afcfb8816aeb26baae7df3ef726)`); } const firstStoneData = msgStones[0].data as SyncSagaMessageData_V1; if (!firstStoneData?.sagaId || !firstStoneData?.stage) { throw new Error(`${lc} Invalid stone data (missing sagaId or stage) (E: c004f85ce8f8958b11839f8d68c38826)`); } const sagaId = firstStoneData.sagaId; const stage = firstStoneData.stage; // Ensure all stones match sagaId and stage for (const stone of msgStones) { const d = stone.data as SyncSagaMessageData_V1; if (d.sagaId !== sagaId) { throw new Error(`${lc} Mismatched sagaId in stones. Expected ${sagaId}, got ${d.sagaId} (E: 29e02719e426ecbbf8ee66887a2be226)`); } if (d.stage !== stage) { throw new Error(`${lc} Mismatched stage in stones. Expected ${stage}, got ${d.stage} (E: d12c6571b0882f762921b60880c3f826)`); } } if (prevSagaIbGib) { /** * rel8ns always include the new msg stone(s) */ const rel8nInfos: Rel8nInfo[] = [ { rel8nName: SYNC_MSG_REL8N_NAME, ibGibs: msgStones, } ]; // remove the existing sync msg stones' addrs if (!prevSagaIbGib.rel8ns) { throw new Error(`(UNEXPECTED) prevSagaIbGib.rel8ns falsy? (E: 81375841aff85b1e48ea42ca218e6826)`); } if (!prevSagaIbGib.rel8ns[SYNC_MSG_REL8N_NAME] || prevSagaIbGib.rel8ns[SYNC_MSG_REL8N_NAME].length === 0) { throw new Error(`(UNEXPECTED) prevSagaIbGib.rel8ns[SYNC_MSG_REL8N_NAME] falsy/empty? (E: 15156baad26fcccda80aa3a31718c726)`); } const rel8nRemovalInfos: Rel8nRemovalInfo[] = [ { rel8nName: SYNC_MSG_REL8N_NAME, ibGibAddrs: prevSagaIbGib.rel8ns[SYNC_MSG_REL8N_NAME], } ]; // Append to existing timeline in controlSpace const resAppend = await appendToTimeline({ timeline: prevSagaIbGib, rel8nInfos, rel8nRemovalInfos, metaspace, space: controlSpace, noDna: true, // Explicitly no DNA for sync frames }); const newFrame = resAppend as SyncIbGib_V1; return newFrame; } else { // Create New Timeline (Root Frame) in controlSpace // data const data: SyncData_V1 = { uuid: sagaId, n: 0, isTjp: true, conflictStrategy, graftPreference, }; if (targetSpaceInfo) { data.targetSpaceInfo = targetSpaceInfo; } if (sessionIdentity) { const sessionIdentityTjpAddr = getTjpAddr({ ibGib: sessionIdentity }); if (!sessionIdentityTjpAddr) { throw new Error(`(UNEXPECTED) sessionIdentity is truthy but sessionIdentityTjpAddr falsy? (E: f52004c10288987a6886f4e8fdf90826)`); } data.sessionIdentityTjpAddr = sessionIdentityTjpAddr; } // ib const ib = await getSyncIb({ data }); // rel8ns const stoneAddrs = msgStones.map(s => getIbGibAddr({ ibGib: s })); const rel8ns: SyncRel8ns_V1 = { [SYNC_MSG_REL8N_NAME]: stoneAddrs, }; const resNew = await createTimeline({ space: controlSpace, metaspace, ib, data, rel8ns, parentIb: SYNC_ATOM, // "sync" /** * this will squash the result into a single frame */ noDna: true, }); if (!!resNew.intermediateIbGibs) { throw new Error(`(UNEXPECTED) resNew.intermediateIbGibs? we were assuming we were creating a single frame. (E: 456818147235d991ccb4d10d0bbe4826)`); } return resNew.newIbGib as SyncIbGib_V1; } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } } private async getStageAndPayloadFromFrame({ sagaFrame, controlSpace }: { sagaFrame: IbGib_V1, controlSpace: IbGibSpaceAny }): Promise<{ stage: SyncStage, messageData: unknown }> { const lc = `${this.lc}[${this.getStageAndPayloadFromFrame.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: fddc287bd4d55253dc50e519fd352226)`); } if (!sagaFrame.rel8ns) { throw new Error(`(UNEXPECTED) sagaFrame.rel8ns falsy? (E: 725bc8eb5dfe5c7058907ad8e3063826)`); } const stoneAddrs = sagaFrame.rel8ns?.[SYNC_MSG_REL8N_NAME]; if (stoneAddrs && stoneAddrs.length > 0) { const stoneAddr = stoneAddrs[0]; const res = await getFromSpace({ addr: stoneAddr, space: controlSpace }); if (res.ibGibs && res.ibGibs.length > 0) { const stone = res.ibGibs[0]; if (!stone.data) { throw new Error(`(UNEXPECTED) message stone.data falsy? (E: 4d4abcea90d87ba1328434e83d0d0826)`); } if (!stone.data.stage) { throw new Error(`(UNEXPECTED) message stone.data.stage falsy? (E: 72c8d22310996644ecdd2b5fdb288c26)`); } return { stage: stone.data.stage, messageData: stone.data }; } else { throw new Error(`couldn't get stoneAddr (${stoneAddr}) from controlSpace (${controlSpace.ib}) (E: f3c826e756f8a5c358beb88aa4a65e26)`); } } else { throw new Error(`(UNEXPECTED) no stone addrs rel8d to sync saga ibgib frame? sagaFrame addr: ${getIbGibAddr(sagaFrame)} (E: 43eae8579e289d016741b5526052f226)`); } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } private sortTimelinesTopologically(timelines: { [tjp: string]: IbGib_V1[] }): string[] { const lc = `${this.lc}[${this.sortTimelinesTopologically.name}]`; const tjps = Object.keys(timelines); if (tjps.length === 0) { return []; } // 1. Build a reverse lookup: ibGibAddr -> tjpAddr const addrToTjp: { [addr: string]: string } = {}; tjps.forEach(tjp => { timelines[tjp].forEach(ibGib => { const addr = getIbGibAddr({ ibGib }); addrToTjp[addr] = tjp; }); }); // 2. Build adjacency list for timelines: tjp -> Set // Edge direction: T1 -> T2 means T1 depends on T2. const adj: { [tjp: string]: Set } = {}; tjps.forEach(tjp => adj[tjp] = new Set()); tjps.forEach(tjp => { timelines[tjp].forEach(ibGib => { if (ibGib.rel8ns) { Object.values(ibGib.rel8ns).flat().forEach(relAddr => { if (!relAddr) { return; } const depTjp = addrToTjp[relAddr]; // If dependency is in our scope and is a different timeline if (depTjp && depTjp !== tjp) { adj[tjp].add(depTjp); } }); } }); }); // 3. Topological Sort (DFS) const visited = new Set(); const temp = new Set(); // for cycle detection const sorted: string[] = []; const visit = (node: string) => { if (temp.has(node)) { console.warn(`${lc} Cycle detected involving ${node}. Ignoring edge to break cycle. (W: 7e7352347102431aa5318db962459929)`); return; } if (visited.has(node)) return; temp.add(node); // Visit dependencies first adj[node].forEach(dep => visit(dep)); visited.add(node); temp.delete(node); sorted.push(node); }; tjps.forEach(node => { if (!visited.has(node)) visit(node); }); return sorted; } }