/** * @module snapshot-helpers * * Creation, validation, and retrieval helpers for immutable B2tFS Snapshot Stones. */ import { extractErrorMsg, getSaferSubstring } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { IbGibAddr } from '@ibgib/ts-gib/dist/types.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { getGib, getGibInfo } from '@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs'; import { IbGibSpaceAny } from '../../../witness/space/space-base-v1.mjs'; import { KeystoneIbGib_V1 } from '../../../keystone/keystone-types.mjs'; import { KEYSTONE_VERB_AUTHOR } from '../../../keystone/keystone-constants.mjs'; import { KeystoneService_V1 } from '../../../keystone/keystone-service-v1.mjs'; import { CommentIbGib_V1 } from '../../../common/comment/comment-types.mjs'; import { getIbGibFromSpace, getIbGibsFromSpace, getTjpAddr } from '../../../common/other/ibgib-helper.mjs'; import { B2tFSItemIbGib_V1, B2TFS_CHILD_ITEM_REL8N_NAME, BINARY_REL8N_NAME } from '../item/item-types.mjs'; import { getProjectedItemFilename } from '../item/item-helpers.mjs'; import { B2tFSBranchIbGib_V1 } from '../branch/branch-types.mjs'; import { B2TFS_SNAPSHOT_ATOM } from './snapshot-constants.mjs'; import { B2tFSSnapshotData_V1, B2tFSSnapshotIbGib_V1, OriginSnapshotInfo, } from './snapshot-types.mjs'; const lcFile = `[snapshot-helpers]`; const logalot = GLOBAL_LOG_A_LOT; export interface CreateBranchSnapshotIbGibOpts { /** Concrete branch stone immediately preceding this snapshot */ branchIbGib: B2tFSBranchIbGib_V1; /** Reified root folder item stone */ rootItem: B2tFSItemIbGib_V1; /** Optional commit comment stone */ commitComment?: CommentIbGib_V1 | any; /** Optional commit message address (if comment already reified) */ commitMessageAddr?: IbGibAddr; /** Cosmos coordinates */ cosmosInfo?: { name?: string; addr?: string; tjpAddr?: string }; /** Galaxy coordinates */ galaxyInfo?: { name?: string; addr?: string; tjpAddr?: string }; /** Origin snapshot provenance records (e.g. from branching, cloning, or merging) */ originSnapshotInfos?: OriginSnapshotInfo[]; /** Primary Keystone identity (tjp address) authorizing this snapshot */ primaryIdentityTjpAddr: IbGibAddr; /** Device author delegate keystone and secret for cryptographic signing */ deviceDelegate: { delegateKeystone: KeystoneIbGib_V1; delegateSecret: string; }; /** Branch space where stones reside */ space: IbGibSpaceAny; /** Control space (localSpace) where identity and author keystones reside and evolve */ controlSpace?: IbGibSpaceAny; /** Metaspace service */ metaspace: any; /** Optional in-memory item lookup cache to avoid unnecessary space reads */ inMemoryItems?: Map; } export interface CreateBranchSnapshotResult { /** Generated immutable snapshot stone */ snapshotIbGib: B2tFSSnapshotIbGib_V1; /** Concrete address of the snapshot stone */ snapshotAddr: IbGibAddr; /** Evolved author delegate keystone after signing */ evolvedAuthorDelegateKeystone: KeystoneIbGib_V1; } /** * Creates, signs, and persists an immutable B2tFS Snapshot Manifest Stone. * * Guarantees: * 1. Zero hard links in rel8ns (`rel8ns: {}`). * 2. Fail-fast if author delegate keystone or primaryIdentityTjpAddr is omitted. * 3. Pre-computes recursive item lookup map and file/folder counts. * 4. Signs author delegate keystone claiming `{ verb: KEYSTONE_VERB_AUTHOR, target: snapshotAddr }`. */ export async function createBranchSnapshotIbGib({ branchIbGib, rootItem, commitComment, commitMessageAddr, cosmosInfo, galaxyInfo, originSnapshotInfos, primaryIdentityTjpAddr, deviceDelegate, space, controlSpace, metaspace, inMemoryItems, }: CreateBranchSnapshotIbGibOpts): Promise { const lc = `${lcFile}[${createBranchSnapshotIbGib.name}]`; try { if (logalot) { console.log(`${lc} starting...`); } // 1. Fail-fast validations if (!primaryIdentityTjpAddr) { throw new Error(`primaryIdentityTjpAddr is required for snapshot genesis (E: snapshot_missing_primary_identity)`); } if (!deviceDelegate || !deviceDelegate.delegateKeystone || !deviceDelegate.delegateSecret) { throw new Error(`deviceDelegate with delegateKeystone and delegateSecret is required for author signature (E: snapshot_missing_author_keystone)`); } if (!branchIbGib) { throw new Error(`branchIbGib is required for snapshot genesis (E: snapshot_missing_branch)`); } if (!rootItem) { throw new Error(`rootItem is required for snapshot genesis (E: snapshot_missing_root_item)`); } if (!space) { throw new Error(`space is required for snapshot genesis (E: snapshot_missing_space)`); } // 2. Resolve cosmology coordinates const prevBranchAddr = getIbGibAddr({ ibGib: branchIbGib }); const branchTjpAddr = branchIbGib.rel8ns?.tjp?.[0] || getGibInfo({ ibGibAddr: prevBranchAddr }).tjpGib || prevBranchAddr; const branchName = branchIbGib.data?.name || 'branch'; const rootItemAddr = getIbGibAddr({ ibGib: rootItem }); let resolvedCommitMessageAddr: IbGibAddr | undefined = commitMessageAddr; if (!resolvedCommitMessageAddr && commitComment) { resolvedCommitMessageAddr = getIbGibAddr({ ibGib: commitComment }); } // 3. Pre-compute path items map and metrics const items: Record = {}; const stats = { fileCount: 0, folderCount: 1 }; items[''] = [rootItemAddr, undefined]; const visited = new Set(); const walkFolder = async (folderItem: B2tFSItemIbGib_V1, currentRelPath: string): Promise => { const folderAddr = getIbGibAddr({ ibGib: folderItem }); if (visited.has(folderAddr)) { return; } visited.add(folderAddr); const childAddrs = folderItem.rel8ns?.[B2TFS_CHILD_ITEM_REL8N_NAME] || []; if (childAddrs.length === 0) { return; } const childIbGibs: B2tFSItemIbGib_V1[] = []; const missingAddrs: IbGibAddr[] = []; for (const addr of childAddrs) { const inMemory = inMemoryItems?.get(addr); if (inMemory) { childIbGibs.push(inMemory); } else { missingAddrs.push(addr); } } if (missingAddrs.length > 0) { const fetched = await getIbGibsFromSpace({ addrs: missingAddrs, space, }); childIbGibs.push(...fetched); } for (const childItem of childIbGibs) { const childName = getProjectedItemFilename(childItem) || childItem.data?.name; if (!childName) { continue; } const childAddr = getIbGibAddr({ ibGib: childItem }); const childPath = currentRelPath ? `${currentRelPath}/${childName}` : childName; if (childItem.data?.fsType === 'file') { stats.fileCount++; const binAddrs = childItem.rel8ns?.[BINARY_REL8N_NAME] || []; const binAddr = binAddrs.at(-1) || undefined; items[childPath] = [childAddr, binAddr]; } else if (childItem.data?.fsType === 'folder') { stats.folderCount++; items[childPath] = [childAddr, undefined]; await walkFolder(childItem, childPath); } } }; await walkFolder(rootItem, ''); // 4. Assemble immutable Snapshot Data const snapshotData: B2tFSSnapshotData_V1 = { cosmosName: cosmosInfo?.name, cosmosAddr: cosmosInfo?.addr, cosmosTjpAddr: cosmosInfo?.tjpAddr, galaxyName: galaxyInfo?.name, galaxyAddr: galaxyInfo?.addr, galaxyTjpAddr: galaxyInfo?.tjpAddr, branchName, prevBranchAddr, branchTjpAddr, rootItemAddr, commitMessageAddr: resolvedCommitMessageAddr, primaryIdentityTjpAddr, authorDelegateTjpAddr: getTjpAddr({ ibGib: deviceDelegate.delegateKeystone }), originSnapshotInfos: originSnapshotInfos && originSnapshotInfos.length > 0 ? originSnapshotInfos : undefined, items, fileCount: stats.fileCount, folderCount: stats.folderCount, }; // 5. Construct Snapshot Stone with ZERO rel8ns const safeBranchName = getSaferSubstring({ text: branchName, length: 64, replaceMap: { ['/']: '_' }, }); const ib = `${B2TFS_SNAPSHOT_ATOM} ${safeBranchName}`; const snapshotIbGib: B2tFSSnapshotIbGib_V1 = { ib, data: snapshotData, rel8ns: {}, }; snapshotIbGib.gib = await getGib({ ibGib: snapshotIbGib, hasTjp: false }); const snapshotAddr = getIbGibAddr({ ibGib: snapshotIbGib }); // 6. Cryptographically sign author delegate keystone const keystoneService = new KeystoneService_V1(); const authorKeystoneSpace = controlSpace ?? space; const evolvedAuthorDelegateKeystone = await keystoneService.sign({ latestKeystone: deviceDelegate.delegateKeystone, masterSecret: deviceDelegate.delegateSecret, claim: { verb: KEYSTONE_VERB_AUTHOR, target: snapshotAddr, }, metaspace, space: authorKeystoneSpace, }); // 7. Persist snapshot stone to space if (metaspace?.put) { await metaspace.put({ ibGibs: [snapshotIbGib], space }); } else if ((space as any).put) { await (space as any).put({ ibGibs: [snapshotIbGib] }); } if (metaspace?.registerNewIbGib) { try { await metaspace.registerNewIbGib({ ibGib: snapshotIbGib, space }); } catch { // Non-fatal if test environment does not implement registerNewIbGib for non-tjp stones } } if (logalot) { console.log(`${lc} Snapshot generated successfully: ${snapshotAddr} (files: ${stats.fileCount}, folders: ${stats.folderCount})`); } return { snapshotIbGib, snapshotAddr, evolvedAuthorDelegateKeystone, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Validates the cryptographic and architectural integrity of a B2tFS Snapshot Stone. */ export async function validateSnapshotIbGib({ snapshotIbGib, }: { snapshotIbGib: B2tFSSnapshotIbGib_V1; }): Promise<{ isValid: boolean; errors: string[] }> { const errors: string[] = []; if (!snapshotIbGib) { return { isValid: false, errors: ['Snapshot IbGib is falsy'] }; } if (!snapshotIbGib.ib?.startsWith(B2TFS_SNAPSHOT_ATOM)) { errors.push(`Snapshot ib does not start with '${B2TFS_SNAPSHOT_ATOM}': '${snapshotIbGib.ib}'`); } // Zero hard links check const rel8nKeys = Object.keys(snapshotIbGib.rel8ns || {}); if (rel8nKeys.length > 0) { errors.push(`Snapshot stone must have zero hard links in rel8ns, found: ${rel8nKeys.join(', ')}`); } // Hash check const recalculatedGib = await getGib({ ibGib: snapshotIbGib, hasTjp: false }); if (recalculatedGib !== snapshotIbGib.gib) { errors.push(`Snapshot gib hash mismatch. Expected ${recalculatedGib}, got ${snapshotIbGib.gib}`); } // Data payload check const data = snapshotIbGib.data; if (!data) { errors.push('Snapshot data is missing'); } else { if (!data.branchName) { errors.push('data.branchName is missing'); } if (!data.prevBranchAddr) { errors.push('data.prevBranchAddr is missing'); } if (!data.branchTjpAddr) { errors.push('data.branchTjpAddr is missing'); } if (!data.rootItemAddr) { errors.push('data.rootItemAddr is missing'); } if (!data.primaryIdentityTjpAddr) { errors.push('data.primaryIdentityTjpAddr is missing'); } if (!data.items) { errors.push('data.items is missing'); } if (typeof data.fileCount !== 'number') { errors.push('data.fileCount is not a number'); } if (typeof data.folderCount !== 'number') { errors.push('data.folderCount is not a number'); } } return { isValid: errors.length === 0, errors, }; } /** * Retrieves the latest snapshot stone recorded on a branch stone, or undefined if no snapshot exists. */ export async function getLatestBranchSnapshot({ branchIbGib, space, }: { branchIbGib: B2tFSBranchIbGib_V1; space: IbGibSpaceAny; }): Promise { const snapshotAddrs = branchIbGib.data?.['@snapshot']; if (!snapshotAddrs || snapshotAddrs.length === 0) { return undefined; } const latestAddr = snapshotAddrs[snapshotAddrs.length - 1]; const snapshot = await getIbGibFromSpace({ addr: latestAddr, space, }); return snapshot || undefined; } /** * Retrieves the entire chronological sequence of snapshot stones recorded on a branch stone. */ export async function getBranchSnapshotHistory({ branchIbGib, space, }: { branchIbGib: B2tFSBranchIbGib_V1; space: IbGibSpaceAny; }): Promise { const snapshotAddrs = branchIbGib.data?.['@snapshot'] || []; if (snapshotAddrs.length === 0) { return []; } return await getIbGibsFromSpace({ addrs: snapshotAddrs, space, }); } export { diffSnapshotTrees, type DiffSnapshotTreesOpts, type DiffSnapshotTreesResult, } from './diff-snapshot-trees.mjs';