/** * @module core-push-cmd * * Isomorphic engine implementation for `vcs push`. * Authenticates via Sync Delegate Keystone and transmits the branch DAG, * Merkle item tree, binary stones, and signed snapshot stone(s) to a remote * Space-Gib server via WebSocket sync. */ import { extractErrorMsg, getUUID } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs'; import { putInSpace } from '../../../witness/space/space-helper.mjs'; import { getIbGibFromSpace } from '../../../common/other/ibgib-helper.mjs'; import { SyncPeerWebSocketSender_V1 } from '../../../sync/sync-peer/sync-peer-websocket/sync-peer-websocket-sender/sync-peer-websocket-sender-v1.mjs'; import { SyncSagaCoordinator } from '../../../sync/sync-saga-coordinator.mjs'; import { SyncConflictStrategy } from '../../../sync/sync-constants.mjs'; import { B2tFSBranchIbGib_V1 } from '../branch/branch-types.mjs'; import { B2TFS_BRANCH_DEFAULT_NAME } from '../branch/branch-constants.mjs'; import { getBranchInfoFromGalaxy, parseBranchIb, } from '../branch/branch-helpers.mjs'; import { getSpaceIdFromIb } from '../../../witness/space/metaspace/metaspace-innerspace/metaspace-innerspace-helper.mjs'; import { getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib, } from '../item/item-helpers.mjs'; import { getLatestBranchSnapshot, diffSnapshotTrees } from '../snapshot/snapshot-helpers.mjs'; import { B2tFSSnapshotIbGib_V1 } from '../snapshot/snapshot-types.mjs'; import { SnapshotSyncManifest } from '../../../sync/sync-types.mjs'; import { B2tFSSnapshotSyncAdapter } from '../sync/b2tfs-snapshot-sync-adapter.mjs'; import { VcsPushOpts, VcsPushResult } from './command-types.mjs'; const lcFile = `[core-push-cmd]`; const logalot = GLOBAL_LOG_A_LOT; /** * Polyfill WebSocket in Node.js environment if not natively present. */ async function ensureWebSocketSupport(): Promise { if (typeof (globalThis as any).WebSocket === 'undefined') { try { const wsModule = await import('ws'); (globalThis as any).WebSocket = wsModule.default || wsModule; } catch { // Already present or running in browser } } } /** * Executes isomorphic VCS push operation. */ export async function executeVcsPush({ metaspace, localSpace, activeBranchSpace, galaxyIbGib, cosmosIbGib, branchName, remoteUrl, senderIdentityInfo, fnSenderSecret, conflictStrategy, onProgress, }: VcsPushOpts): Promise { const lc = `${lcFile}[${executeVcsPush.name}]`; let senderPeerPhase1: SyncPeerWebSocketSender_V1 | undefined; let senderPeerPhase2: SyncPeerWebSocketSender_V1 | undefined; try { if (logalot) { console.log(`${lc} starting push to ${remoteUrl}...`); } if (!branchName) { throw new Error(`branchName required (E: 1d66f8c31b48f9e62c2159ab98ca5226)`); } if (!activeBranchSpace) { throw new Error(`activeBranchSpace required (E: 1125584639f484892816ecf8ab2ad826)`); } await ensureWebSocketSupport(); // 1. Normalize remote URL & endpoints let parsedUrl: URL; try { parsedUrl = new URL(remoteUrl.startsWith('http') ? remoteUrl : `https://${remoteUrl}`); } catch { parsedUrl = new URL(`https://${remoteUrl}`); } const host = parsedUrl.host; const isSecure = parsedUrl.protocol === 'https:' || parsedUrl.protocol === 'wss:'; const httpProtocol = isSecure ? 'https:' : 'http:'; const wsProtocol = isSecure ? 'wss:' : 'ws:'; // In Node development against localhost / .localhost, tolerate self-signed certs if (typeof process !== 'undefined' && process.env && (host.includes('localhost') || host.includes('127.0.0.1'))) { process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; } const domainAddrEncoded = encodeURIComponent(senderIdentityInfo.senderDomainAddr); const httpEvolveUrl = `${httpProtocol}//${host}/api/keystone/evolve/${domainAddrEncoded}`; const wsUrl = `${wsProtocol}//${host}/api/sync/ws/${domainAddrEncoded}`; onProgress?.({ stage: 'connecting', message: `Connecting to ${host}...` }); // 2. Identify target branch and space using standard helpers const targetBranch = branchName; let branchIbGib: B2tFSBranchIbGib_V1 | undefined; let branchSpace = activeBranchSpace; try { const res = await getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib({ galaxyIbGib, branchName: targetBranch, metaspace, }); branchIbGib = res.branchIbGib; branchSpace = branchSpace; } catch (lookupErr) { // Fallback: resolve via getBranchInfoFromGalaxy directly try { const branchInfo = await getBranchInfoFromGalaxy({ galaxyIbGib, branchName: targetBranch, metaspace, }); const spaceToUse = branchSpace ?? localSpace; const latestAddr = await metaspace.getLatestAddr({ addr: branchInfo.branchAddr, space: spaceToUse }) || branchInfo.branchAddr; branchIbGib = await getIbGibFromSpace({ addr: latestAddr, space: spaceToUse }); } catch { // Ignore fallback failure and throw uniform error below } } if (!branchIbGib) { throw new Error(`Branch '${targetBranch}' not found in repository (E: 702c8881c8b84b9f38e6c51b122ea826)`); } const effectiveBranchSpace = branchSpace; // 3. Assemble domain ibgibs for synchronization const domainIbGibs: IbGib_V1[] = [branchIbGib]; // Retrieve latest snapshot stone if present and include in domainIbGibs let latestSnapshotAddr: string | undefined; let snapshotIbGib: B2tFSSnapshotIbGib_V1 | undefined; try { snapshotIbGib = await getLatestBranchSnapshot({ branchIbGib, space: effectiveBranchSpace, }); if (snapshotIbGib) { domainIbGibs.push(snapshotIbGib); latestSnapshotAddr = getIbGibAddr({ ibGib: snapshotIbGib }); } } catch (snapErr) { console.warn(`${lc} Could not load latest snapshot: ${extractErrorMsg(snapErr)} (W: df3c88e8fdd33a9411187a08166db826)`); } // Calculate intermediate SnapshotSyncManifest for gap acceleration let accelerationHint: SnapshotSyncManifest | undefined; let previousSnapshot: B2tFSSnapshotIbGib_V1 | undefined; if (snapshotIbGib) { try { const snapshotAddrs = branchIbGib.data?.['@snapshot'] || []; if (snapshotAddrs.length >= 2) { const prevAddr = snapshotAddrs[snapshotAddrs.length - 2]; previousSnapshot = await getIbGibFromSpace({ addr: prevAddr, space: effectiveBranchSpace, }); } const diffRes = await diffSnapshotTrees({ latestSnapshot: snapshotIbGib, previousSnapshot, branchIbGib, space: effectiveBranchSpace, }); accelerationHint = diffRes.manifest; if (logalot) { console.log(`${lc} accelerationHint generated (${accelerationHint.changedAddrs.length} changed addrs)`); } } catch (diffErr) { if (logalot) { console.warn(`${lc} Could not calculate snapshot delta manifest: ${extractErrorMsg(diffErr)}`); } } } // 3. Assemble domain ibgibs for Phase 1: Branch & Snapshot const phase1DomainIbGibs: IbGib_V1[] = [branchIbGib]; if (snapshotIbGib) { phase1DomainIbGibs.push(snapshotIbGib); } const cosmosAddr = getIbGibAddr({ ibGib: cosmosIbGib }); const actualBranchAddr = getIbGibAddr({ ibGib: branchIbGib }); if (!latestSnapshotAddr) { latestSnapshotAddr = branchIbGib.data['@snapshot']?.at(-1) || branchIbGib.data.latestSnapshotAddr; } const cosmosName = cosmosIbGib.data.cosmosName; if (!cosmosName) { throw new Error(`(UNEXPECTED) cosmosIbGib.data.cosmosName falsy? (E: 6f6ab207eb61c7ae58652efd1a85c826)`); } const galaxyName = galaxyIbGib.data.galaxyName; if (!galaxyName) { throw new Error(`(UNEXPECTED) galaxyIbGib.data.galaxyName falsy? (E: 6bccb8e818453b915820f87b9a50d726)`); } // Extract branchId / spaceId from branchIbGib const branchSpaceId = parseBranchIb({ ib: branchIbGib.ib }).uuid; const destinationSpaceCoords = { cosmosName, galaxyName, branchName: targetBranch, spaceId: branchSpaceId, }; const coordsPath = `/${encodeURIComponent(cosmosName)}/${encodeURIComponent(galaxyName)}/${encodeURIComponent(targetBranch)}`; const wsUrlWithCoords = `${wsUrl}${coordsPath}`; // 4. Phase 1: Branch Sync (into dedicated remote branch space) onProgress?.({ stage: 'syncing', message: `Syncing branch '${targetBranch}' and snapshots to remote branch space...` }); senderPeerPhase1 = new SyncPeerWebSocketSender_V1({ classname: 'SyncPeerWebSocketSender_V1', httpEvolveUrl, wsUrl: wsUrlWithCoords, destinationSpaceCoords, }); const coordinatorPhase1 = new SyncSagaCoordinator(); const sagaIdPhase1 = await getUUID(); await senderPeerPhase1.initializeOpts({ localMetaspace: metaspace, controlSpace: localSpace, domainSpace: effectiveBranchSpace, senderIdentity: senderIdentityInfo.senderIdentity, fnSenderSecret, sagaId: sagaIdPhase1, targetAddrs: [senderIdentityInfo.senderDomainAddr], destinationSpaceCoords, }); const isShadowOnly = typeof process !== 'undefined' && process.env?.SYNC_ACCELERATION_SHADOW_ONLY === 'true'; const adapter = new B2tFSSnapshotSyncAdapter({ branchIbGib, latestSnapshot: snapshotIbGib, previousSnapshot, cosmosIbGib: undefined, galaxyIbGib: undefined, accelerationHint, shadowOnly: isShadowOnly, }); const syncSagaPhase1 = await coordinatorPhase1.sync({ domainIbGibs: phase1DomainIbGibs, senderIdentityInfo, fnSenderSecret, peer: senderPeerPhase1, controlSpace: localSpace, domainSpace: effectiveBranchSpace, metaspace, conflictStrategy: conflictStrategy ?? SyncConflictStrategy.optimisticWithLCS, targetSpaceInfo: { cosmosName, galaxyName, branchName: targetBranch, url: wsUrlWithCoords, }, accelerationHint, adapter, }); await syncSagaPhase1.done; if (senderPeerPhase1.currentSenderIdentity) { senderIdentityInfo.senderIdentity = senderPeerPhase1.currentSenderIdentity; } senderPeerPhase1.disconnect(); senderPeerPhase1 = undefined; // 5. Phase 2: Galaxy & Cosmos Sync (into remote localSpace) const phase2DomainIbGibs: IbGib_V1[] = [cosmosIbGib, galaxyIbGib].filter(Boolean) as IbGib_V1[]; if (phase2DomainIbGibs.length > 0) { onProgress?.({ stage: 'syncing', message: `Syncing repository galaxy and cosmos to remote...` }); senderPeerPhase2 = new SyncPeerWebSocketSender_V1({ classname: 'SyncPeerWebSocketSender_V1', httpEvolveUrl, wsUrl, }); const coordinatorPhase2 = new SyncSagaCoordinator(); const sagaIdPhase2 = await getUUID(); await senderPeerPhase2.initializeOpts({ localMetaspace: metaspace, controlSpace: localSpace, domainSpace: localSpace, senderIdentity: senderIdentityInfo.senderIdentity, fnSenderSecret, sagaId: sagaIdPhase2, targetAddrs: [senderIdentityInfo.senderDomainAddr], }); const syncSagaPhase2 = await coordinatorPhase2.sync({ domainIbGibs: phase2DomainIbGibs, senderIdentityInfo, fnSenderSecret, peer: senderPeerPhase2, controlSpace: localSpace, domainSpace: localSpace, metaspace, conflictStrategy: conflictStrategy ?? SyncConflictStrategy.optimisticWithLCS, targetSpaceInfo: { url: wsUrl, }, }); await syncSagaPhase2.done; if (senderPeerPhase2?.currentSenderIdentity) { senderIdentityInfo.senderIdentity = senderPeerPhase2.currentSenderIdentity; } senderPeerPhase2.disconnect(); senderPeerPhase2 = undefined; } onProgress?.({ stage: 'complete', message: `Push completed successfully.` }); const allDomainIbGibs = [...phase1DomainIbGibs, ...phase2DomainIbGibs]; const syncedAddrs = allDomainIbGibs.map(ibg => getIbGibAddr({ ibGib: ibg })); return { success: true, remoteUrl, branchName: targetBranch, syncedAddrs, cosmosAddr, branchAddr: actualBranchAddr, latestSnapshotAddr, newSenderIdentity: senderIdentityInfo.senderIdentity, }; } catch (error) { console.error(`${lc} push failed: ${extractErrorMsg(error)}`); throw error; } finally { senderPeerPhase1?.disconnect(); senderPeerPhase2?.disconnect(); } }