/** * @module sync-conflict.respec * * Verifies Conflict Resolution strategies in SyncSagaCoordinator. * Reproduces divergence scenarios and asserts resolution behavior. */ import { respecfully, lastOfAll, ifWe, ifWeMight, iReckon } from '@ibgib/helper-gib/dist/respec-gib/respec-gib.mjs'; const maam = `[${import.meta.url}]`, sir = maam; import { clone, delay, extractErrorMsg, pretty } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { IbGibData_V1, IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs'; import { SyncSagaCoordinator } from './sync-saga-coordinator.mjs'; import { getFromSpace } from '../witness/space/space-helper.mjs'; import { Metaspace_Innerspace } from '../witness/space/metaspace/metaspace-innerspace/metaspace-innerspace.mjs'; import { InnerSpace_V1 } from '../witness/space/inner-space/inner-space-v1.mjs'; import { createTimelineRootTestHelper } from '../test-helpers.mjs'; import { appendToTimeline, createTimeline, mut8Timeline } from '../timeline/timeline-api.mjs'; import { SyncPeerInnerspace_V1 } from './sync-peer/sync-peer-innerspace/sync-peer-innerspace-v1.mjs'; import { DEFAULT_INNER_SPACE_DATA_V1 } from '../witness/space/inner-space/inner-space-types.mjs'; import { getIbGibsFromCache_fallbackToSpaces, getTjpAddr, toDto } from '../common/other/ibgib-helper.mjs'; import { SyncSagaInfo } from './sync-types.mjs'; import { fnObs } from '../common/pubsub/observer/observer-helper.mjs'; import { getDependencyGraph, graphsAreEquivalent } from '../common/other/graph-helper.mjs'; import { ErrorIbGib_V1 } from '../common/error/error-types.mjs'; import { SYNC_PEER_INNERSPACE_DEFAULT_DATA_V1 } from './sync-peer/sync-peer-innerspace/sync-peer-innerspace-constants.mjs'; import { SyncConflictStrategy } from './sync-constants.mjs'; import { GRAFT_BASE_REL8N_NAME, GRAFT_INFO_REL8N_NAME, GRAFT_ORPHAN_REL8N_NAME } from './graft-info/graft-info-constants.mjs'; import { SYNC_SPACE_MODES, createSyncTestSpaces, verifySyncControlAndDomainSpaces } from './sync-respec-helper.mjs'; const logalot = false; const lc = sir; interface TestData extends IbGibData_V1 { type?: string; /** * field that is made in a common (pre-sync) ibgib */ commonField?: string; fieldA?: string; fieldB?: string; } const TEST_REL8N_NAME = 'testrel8n'; await respecfully(sir, `Two different fields and rel8d`, async () => { for (const mode of SYNC_SPACE_MODES) { await respecfully(sir, `[mode: ${mode}] Two different fields and rel8d`, async () => { // 1. Setup Spaces const metaspace = new Metaspace_Innerspace(undefined); await metaspace.initialize({ getFnAlert: () => async ({ title, msg }) => { console.log(`[Alert] ${title}: ${msg}`); }, getFnPrompt: () => async ({ title, msg }) => { console.log(`[Prompt] ${title}: ${msg}`); return ''; }, getFnPromptPassword: () => async (title, msg) => { console.log(`[PromptPwd] ${title}: ${msg}`); return null; }, }); while (!metaspace.initialized) { await delay(10); } const defaultLocalUserSpace = await metaspace.getLocalUserSpace({ lock: false }); await defaultLocalUserSpace!.initialized; const { senderControlSpace, senderDomainSpace, receiverControlSpace, receiverDomainSpace, } = await createSyncTestSpaces({ mode, prefix: `conflict_basic_multi_${mode}` }); const sourceSpace = senderDomainSpace; const destSpace = receiverDomainSpace; // 2. Seed common History (v0 -> v1) console.log(`${lc} Creating common History...`); const alpha_v0 = await createTimelineRootTestHelper({ ib: 'alpha', data: { type: 'alpha', }, space: sourceSpace, }); // Create v1 (common) const alpha_v1_common_onSource = await mut8Timeline({ timeline: alpha_v0, mut8Opts: { mut8Ib: alpha_v0.ib + '_common', dataToAddOrPatch: { commonField: 'common yo' } }, metaspace, space: sourceSpace, }); const tjpAddr = getTjpAddr({ ibGib: alpha_v0, defaultIfNone: 'incomingAddr' }) ?? getIbGibAddr({ ibGib: alpha_v0 }); // Sync alpha to dest immediately so they start synced const depGraph_alpha_v1Andcommon = await getDependencyGraph({ ibGibAddrs: [tjpAddr], space: sourceSpace, live: true, }) ?? {}; if (Object.keys(depGraph_alpha_v1Andcommon).length === 0) { throw new Error(`(UNEXPECTED) depGraph_testRootAndV1Common empty? (E: 39b4d855ffa65476084b4123786da826)`); } await metaspace.put({ ibGibs: Object.values(depGraph_alpha_v1Andcommon), space: destSpace }); const resGetDest = await getFromSpace({ space: destSpace, addr: getIbGibAddr({ ibGib: alpha_v1_common_onSource }) }); if (!resGetDest.success || !resGetDest.ibGibs || resGetDest.ibGibs.length === 0) { throw new Error(`Failed to retrieve v1_Common_onDest from destSpace. (E: 40c67811eba14f729880a46dcbb65126)`); } const alpha_v1_common_onDest = resGetDest.ibGibs[0]; await metaspace.registerNewIbGib({ ibGib: alpha_v0, space: destSpace }); await metaspace.registerNewIbGib({ ibGib: alpha_v1_common_onDest, space: destSpace }); // 3. Create Divergence(s) (v2source vs v2dest) console.log(`${lc} Creating Divergence...`); // #region edit on source const beta_v0_source = await createTimelineRootTestHelper({ ib: 'beta', data: { fieldA: 'beta field A created on source', }, space: sourceSpace, }); const betaAddr_v0 = getIbGibAddr({ ibGib: beta_v0_source }); const alpha_v2_source_sansBeta = await mut8Timeline({ timeline: alpha_v1_common_onSource, mut8Opts: { mut8Ib: alpha_v0.ib + '_v2source', dataToAddOrPatch: { fieldA: 'source_edit' } }, metaspace, space: sourceSpace, }); const alpha_v3_source_rel8beta = await appendToTimeline({ timeline: alpha_v2_source_sansBeta, metaspace, space: sourceSpace, rel8nInfos: [ { rel8nName: TEST_REL8N_NAME, ibGibs: [beta_v0_source] } ], }); const baseAddr = getIbGibAddr({ ibGib: alpha_v3_source_rel8beta }); // #endregion edit on source await delay(16); // #region edit on dest const alpha_v2_dest = await mut8Timeline({ timeline: alpha_v1_common_onDest, mut8Opts: { mut8Ib: alpha_v0.ib + '_v2dest', dataToAddOrPatch: { fieldB: 'dest_edit' } }, metaspace, space: destSpace, }); const orphanAddr = getIbGibAddr({ ibGib: alpha_v2_dest }); console.log(`${lc} Divergence created.`); // 4. Run Sync (Optimistic) console.log(`${lc} Setting up Coordinators...`); const senderCoordinator = new SyncSagaCoordinator(); const receiverCoordinator = new SyncSagaCoordinator(); const peer = new SyncPeerInnerspace_V1(clone(SYNC_PEER_INNERSPACE_DEFAULT_DATA_V1)); await peer.initialized; await peer.initializeOpts({ localMetaspace: metaspace, controlSpace: senderControlSpace, domainSpace: senderDomainSpace, receiverControlSpace, receiverDomainSpace, receiverCoordinator, receiverMetaspace: metaspace, }); // Verify Receiver has correct KV (Pre-Sync Check) await ifWe(sir, 'verify receiver KV pre-sync', async () => { try { const destKV = await receiverCoordinator.getKnowledgeMap({ space: destSpace, metaspace, domainIbGibs: [alpha_v1_common_onDest] }); const v1TjpAddr = getTjpAddr({ ibGib: alpha_v1_common_onDest, defaultIfNone: 'incomingAddr' }) ?? getIbGibAddr({ ibGib: alpha_v1_common_onDest }); const destTip = destKV[v1TjpAddr]; iReckon(sir, !!destTip).asTo(`Dest KV has timeline tip for ${v1TjpAddr}`).isGonnaBeTruthy(); if (!destTip) { throw new Error(`Test Setup Fail: Dest Space does not have index for timeline ${v1TjpAddr}. Seeding failed. (E: c194a80b4e4877b77826c37a1753b826)`); } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); iReckon(sir, true).asTo('getKnowledgeMap errored out').isGonnaBeFalse(); } }); console.log(`${lc} Running Sync (ConflictStrategy: optimistic)...`); let resSync: SyncSagaInfo | undefined; try { resSync = await senderCoordinator.sync({ peer, controlSpace: senderControlSpace, domainSpace: senderDomainSpace, metaspace, domainIbGibs: [alpha_v3_source_rel8beta], conflictStrategy: SyncConflictStrategy.optimisticWithLCS, }); const sublc = `${lc}[updates$]`; await resSync.updates$.subscribe(fnObs({ next: async (_ctxIbGib) => { console.log(`${sublc} next fired. (I: e68d8894bac8800f9f3430e8a38d6626)`); }, error: async (e: ErrorIbGib_V1) => { if (e.data) { console.error(`${sublc} error fired. error: ${JSON.stringify(e.data)} (E: eddf17f76a486b9c5a2f4ee86ed38b26)`); } else { console.dir(e); console.error(`${sublc} error fired. error: ${extractErrorMsg(e)} (E: af9c3b6f1c88befeff77ca46111b3826)`); } }, complete: async () => { console.log(`${sublc} complete fired`); }, })); await resSync.done; console.log(`${lc} Sync Complete.`); } catch (e) { console.error(`${lc} Sync Failed with Error:`, e); iReckon(sir, false).asTo(`Sync failed with error: ${e}`).isGonnaBeTruthy(); return; } // 5. Verification let newTipIbGib: IbGib_V1 | undefined; await respecfully(sir, `verify merge`, async () => { try { const sourceKV_afterSync = await senderCoordinator.getKnowledgeMap({ space: sourceSpace, metaspace, domainIbGibs: [alpha_v0] }); const tjpAddr = getTjpAddr({ ibGib: alpha_v0, defaultIfNone: 'incomingAddr' }) ?? getIbGibAddr({ ibGib: alpha_v0 }); const sourceTipAddr = sourceKV_afterSync[tjpAddr]; if (!sourceTipAddr) { throw new Error(`Source Space missing timeline tip for ${tjpAddr} (E: ec95980b9c980c5c5870812e15e43826)`); } const resTip = await getFromSpace({ space: sourceSpace, addr: sourceTipAddr }); const newTip = resTip.ibGibs![0] as IbGib_V1; newTipIbGib = newTip; await ifWe(sir, 'basics of alpha merge', async () => { iReckon(sir, sourceTipAddr).asTo(`Source Tip (${sourceTipAddr}) should NOT be alpha_v3_source_rel8beta`).not.isGonnaBe(getIbGibAddr({ ibGib: alpha_v3_source_rel8beta })); iReckon(sir, sourceTipAddr).asTo(`Source Tip (${sourceTipAddr}) should NOT be v2dest`).not.isGonnaBe(getIbGibAddr({ ibGib: alpha_v2_dest })); iReckon(sir, newTip.data!.fieldA).asTo('New Tip Data Field A').isGonnaBe('source_edit'); iReckon(sir, newTip.data!.fieldB).asTo('New Tip Data Field B').isGonnaBe('dest_edit'); }); await ifWe(sir, 'graft info is valid', async () => { if (!newTip.rel8ns) { throw new Error(`(UNEXPECTED) newTip.rel8ns falsy? (E: eb4078712ea2f02c7ee84b983ed77826)`); } const graftInfoRel = newTip.rel8ns[GRAFT_INFO_REL8N_NAME]; iReckon(sir, graftInfoRel).asTo('New Tip should have graftinfo rel8n').isGonnaBeTruthy(); if (!graftInfoRel) { return; } iReckon(sir, graftInfoRel!.length).asTo('Only 1 graftinfo').isGonnaBe(1); const resGraft = await getFromSpace({ space: sourceSpace, addr: graftInfoRel![0] }); const graftInfo = resGraft.ibGibs![0]; if (!graftInfo.rel8ns) { throw new Error(`(UNEXPECTED) graftInfo.rel8ns falsy? (E: 8e39e84e9e0813e09e8f6788ce488926)`); } const baseRel = graftInfo.rel8ns[GRAFT_BASE_REL8N_NAME]; const orphanRel = graftInfo.rel8ns[GRAFT_ORPHAN_REL8N_NAME]; iReckon(sir, baseRel).asTo('Graft Base exists').isGonnaBeTruthy(); iReckon(sir, baseRel!.length).asTo('Graft Base length is 2').isGonnaBe(2); iReckon(sir, orphanRel).asTo('Graft Orphan exists').isGonnaBeTruthy(); iReckon(sir, orphanRel!.length).asTo('Graft Orphan length is 1').isGonnaBe(1); iReckon(sir, baseRel!.at(-1)).asTo('base rel8ns final addr will be baseAddr').isGonnaBe(baseAddr); iReckon(sir, orphanRel![0]).asTo('orphan rel8ns will be later addr').isGonnaBe(orphanAddr); }); await ifWe(sir, 'alpha and deps synced', async () => { const [beta_dest] = await getIbGibsFromCache_fallbackToSpaces({ addrs: [betaAddr_v0], space: destSpace, }); iReckon(sir, beta_dest).asTo('beta exists in dest').isGonnaBeTruthy(); if (beta_dest) { const depGraph_beta_source = await getDependencyGraph({ ibGib: beta_v0_source, space: sourceSpace }); const depGraph_beta_dest = await getDependencyGraph({ ibGib: beta_dest, space: destSpace }); const betaDepsAreEqual = graphsAreEquivalent({ graphA: depGraph_beta_source, graphB: depGraph_beta_dest }); iReckon(sir, betaDepsAreEqual).asTo('beta got synced and graphs are equal').isGonnaBeTrue(); } }); await ifWe(sir, 'beta and deps synced', async () => { const [beta_dest] = await getIbGibsFromCache_fallbackToSpaces({ addrs: [betaAddr_v0], space: destSpace, }); iReckon(sir, beta_dest).asTo('beta exists in dest').isGonnaBeTruthy(); if (beta_dest) { const depGraph_beta_source = await getDependencyGraph({ ibGib: beta_v0_source, space: sourceSpace }); const depGraph_beta_dest = await getDependencyGraph({ ibGib: beta_dest, space: destSpace }); const betaDepsAreEqual = graphsAreEquivalent({ graphA: depGraph_beta_source, graphB: depGraph_beta_dest, slowButThorough: true, }); iReckon(sir, betaDepsAreEqual).asTo('beta got synced and graphs are equal').isGonnaBeTrue(); } }); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); iReckon(sir, true).asTo('getKnowledgeMap errored out').isGonnaBeFalse(); } }); await verifySyncControlAndDomainSpaces({ sir, mode, senderCoordinator, receiverCoordinator, peer, senderControlSpace, senderDomainSpace, receiverControlSpace, receiverDomainSpace, syncedDomainIbGibs: newTipIbGib ? [newTipIbGib, beta_v0_source] : [alpha_v3_source_rel8beta, beta_v0_source], }); }); } });