import { extractErrorMsg } from "@ibgib/helper-gib/dist/helpers/utils-helper.mjs"; import { IbGibAddr } from "@ibgib/ts-gib/dist/types.mjs"; import { GLOBAL_LOG_A_LOT } from "../../core-constants.mjs"; import { GraftContext, GraftPreference, GraftStrategy, GraftTimelinesResult } from "./graft-info-types.mjs"; import { DefaultDnaReplayGraftStrategy } from "./strategies/default-dna-replay-graft-strategy.mjs"; import { SyncConflictStrategy } from "../sync-constants.mjs"; import { FlatIbGibGraph } from "../../common/other/graph-types.mjs"; import { IbGibSpaceAny } from "../../witness/space/space-base-v1.mjs"; const logalot = GLOBAL_LOG_A_LOT; const lcFile = `[graft-strategy-service]`; /** * Singleton registry for Graft Strategies. * * used by `graftTimelines` * Evaluates strategies in order of registration, falling back to * DefaultDnaReplayGraftStrategy if no custom strategy matches. */ export class GraftStrategyService { private static _instance: GraftStrategyService; public static get instance(): GraftStrategyService { if (!this._instance) { this._instance = new GraftStrategyService(); } return this._instance; } private _registeredStrategies: GraftStrategy[] = []; private _fallbackStrategy: GraftStrategy = new DefaultDnaReplayGraftStrategy(); /** * Registers a graft strategy. Registered strategies are evaluated **IN * REGISTRATION ORDER** before using the fallback strategy. */ public registerStrategy(strategy: GraftStrategy): void { const lc = `${lcFile}[${this.registerStrategy.name}]`; if (!strategy) { throw new Error(`(UNEXPECTED) strategy falsy (E: 777b77f4cf48e0c2b83159f8dbd06226)`); } if (!this._registeredStrategies.some(s => s.strategyId === strategy.strategyId)) { if (logalot) { console.log(`${lc} registering strategy ${strategy.strategyId} (I: ad6a7f678526d2991684cc2c1c16cd26)`); } this._registeredStrategies.push(strategy); } } /** * Replaces the default fallback strategy. */ public setFallbackStrategy(strategy: GraftStrategy): void { const lc = `${lcFile}[${this.setFallbackStrategy.name}]`; if (!strategy) { throw new Error(`(UNEXPECTED) fallback strategy falsy (E: 09819876bb2ad7b788432518ce727826)`); } if (logalot) { console.log(`${lc} setting fallback strategy ${strategy.strategyId} (I: e7e4d88de1d8a7fbc8dfa021f2900826)`); } this._fallbackStrategy = strategy; } public getFallbackStrategy(): GraftStrategy { return this._fallbackStrategy; } public getRegisteredStrategies(): GraftStrategy[] { return this._registeredStrategies.slice(); } /** * Resets registered strategies and restores DefaultDnaReplayGraftStrategy as fallback. */ public reset(): void { const lc = `${lcFile}[${this.reset.name}]`; if (logalot) { console.log(`${lc} resetting strategies to default fallback... (I: edc9e8c23808995ade1cc3c8da474f26)`); } this._registeredStrategies = []; this._fallbackStrategy = new DefaultDnaReplayGraftStrategy(); } /** * Grafts two divergent timelines by executing a pipeline of registered * concrete {@link GraftStrategy} implementations. * * Uses the fallback strategy {@link getFallbackStrategy} if no registered * strategies are able to perform the graft to completion. */ public async graftTimelines({ timelineAddrsA, timelineAddrsB, latestCommonFrameAddr, conflictStrategy, ibGibReadCache, space, graftPreference, }: { conflictStrategy: SyncConflictStrategy, timelineAddrsA: IbGibAddr[], timelineAddrsB: IbGibAddr[], latestCommonFrameAddr?: IbGibAddr, ibGibReadCache: FlatIbGibGraph, space: IbGibSpaceAny, graftPreference?: GraftPreference, }): Promise { const lc = `[${this.graftTimelines.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 3b4c3e8e59c883d9d3c352efd6380826)`); } if (timelineAddrsA.length === 0) { throw new Error(`timelineAddrsA empty (E: 93a78cd1cd2a4a16ba99bd4820468f26)`); } if (timelineAddrsB.length === 0) { throw new Error(`timelineAddrsB empty (E: 76d53848152a66971b734068c3316826)`); } if (latestCommonFrameAddr) { if (!timelineAddrsA.includes(latestCommonFrameAddr)) { throw new Error(`timelineAddrsA does not include latestCommonFrameAddr (${latestCommonFrameAddr}). timelineAddrsA: ${timelineAddrsA} (E: c5a9afe371888da2a79963983426e826)`); } if (!timelineAddrsB.includes(latestCommonFrameAddr)) { throw new Error(`timelineAddrsB does not include latestCommonFrameAddr (${latestCommonFrameAddr}). timelineAddrsB: ${timelineAddrsB} (E: 7e641f67c452b67d582d78484a88c826)`); } } else { latestCommonFrameAddr = timelineAddrsA.findLast(addrA => timelineAddrsB.includes(addrA)); if (!latestCommonFrameAddr) { throw new Error(`timelines do not share a common frame. A: ${timelineAddrsA}. B: ${timelineAddrsB} (E: 4c0e78a88a375d8588736668573f1e26)`); } } if (timelineAddrsA.at(-1) === latestCommonFrameAddr) { throw new Error(`timelineAddrsA.at(-1) === latestCommonFrameAddr. Graft requires a branch BEYOND the LCA (E: 3796fc4074a8c5899d549bb8c2e68826)`); } if (timelineAddrsB.at(-1) === latestCommonFrameAddr) { throw new Error(`timelineAddrsB.at(-1) === latestCommonFrameAddr. Graft requires a branch BEYOND the LCA (E: 66fbb86e9e98531549888bf10a344f26)`); } const context: GraftContext = { conflictStrategy, timelineAddrsA, timelineAddrsB, latestCommonFrameAddr, ibGibReadCache, space, graftPreference, }; /** * because this is now a pipeline, strategy's are responsible for NOT * persisting/registering any ibgibs to spaces until it KNOWS it will * complete (or throw). */ const strategyPipeline: GraftStrategy[] = []; const strategies = this.getRegisteredStrategies(); if (strategies && strategies.length > 0) { for (const strat of strategies) { const canGraft = await strat.canGraft(context); if (canGraft) { strategyPipeline.push(strat); } } } strategyPipeline.push(GraftStrategyService.instance.getFallbackStrategy()); if (strategyPipeline.length === 0) { throw new Error(`(UNEXPECTED) strategyPipeline.length === 0? We should at least have the fallback strategy. (E: 1d9bef958b54f8d0d9498bc7fd597226)`); } let resGraft: GraftTimelinesResult | undefined = undefined; for (const strategy of strategyPipeline) { if (logalot) { console.log(`${lc} executing graft strategy ${strategy.strategyId} (I: 066466905d08792d480c5f285fe4f826)`); } resGraft = await strategy.graft(context); if (resGraft) { break; } } if (!resGraft) { throw new Error(`(UNEXPECTED) resGraft falsy? Our fallback strategy should have at least replayed the dna. (E: 6b2d78b52b39a7ff9853c0d8f8628826)`); } return resGraft; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: 05ed0ae869b6658d278fe1480fe19826)`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } }