/** * @module witness/space/proxy-readonly-space/proxy-readonly-space-v1 * * Implements ProxyReadonlySpace_V1 for Mode 3: Remote Server Browsing. * * An isomorphic IbGibSpaceAny witness that proxies read calls ('get', 'canGet', * 'getLatestAddrs') over HTTP to identity+cosmos scoped endpoints, validates all * incoming ibGib records with validateIbGibIntrinsically, and caches them in memory. * * Rejects any write or mutation attempt ('put', 'delete') with ReadOnlySpaceError. */ import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { getGib, getGibInfo } from '@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs'; import { getIbGibAddr, getIbAndGib } from '@ibgib/ts-gib/dist/helper.mjs'; import { validateIbGibIntrinsically } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs'; import { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs'; import { SpaceBase_V1, IbGibSpaceAny } from '../space-base-v1.mjs'; import { getSpaceIb, getFromSpace, putInSpace } from '../space-helper.mjs'; import { ReadOnlySpaceError, AnySpaceOptionsIbGib, AnySpaceResultIbGib } from '../readonly-space-wrapper.mjs'; import { IbGibSpaceOptionsCmd } from '../space-types.mjs'; import { B2tFSSnapshotIbGib_V1 } from '../../../cosmology/branching/snapshot/snapshot-types.mjs'; import { PROXY_READONLY_SPACE_CLASSNAME, ProxyReadonlyFetchFn, ProxyReadonlySpaceConstructorOpts, ProxyReadonlySpaceData_V1, } from './proxy-readonly-space-types.mjs'; const lcFile = `[${PROXY_READONLY_SPACE_CLASSNAME}]`; const logalot = GLOBAL_LOG_A_LOT; interface QueuedFetchWaiter { addr: string; resolve: (ibGib: IbGib_V1 | undefined) => void; reject: (err: any) => void; } function getTjpGibFromAddr(addr: string): string { try { const gibInfo = getGibInfo({ ibGibAddr: addr }); return gibInfo?.tjpGib || getIbAndGib({ ibGibAddr: addr }).gib; } catch { return addr; } } export class ProxyReadonlySpace_V1 extends SpaceBase_V1 implements IbGibSpaceAny { protected override lc: string = lcFile; private _serverBaseUrl: string; private _identityHandle: string; private _cosmosName: string; private _galaxyName?: string; private _branchName?: string; private _cacheSpace?: IbGibSpaceAny; private _fetchFn: ProxyReadonlyFetchFn; private _snapshotIbGib?: B2tFSSnapshotIbGib_V1; private _snapshotTjpMap: Map = new Map(); private _fetchQueue: QueuedFetchWaiter[] = []; private _isProcessingQueue: boolean = false; constructor( initialData?: ProxyReadonlySpaceData_V1, initialRel8ns?: any, opts?: ProxyReadonlySpaceConstructorOpts, ) { const serverBaseUrl = opts?.serverBaseUrl || initialData?.serverBaseUrl || ''; const identityHandle = opts?.identityHandle || initialData?.identityHandle || ''; const cosmosName = opts?.cosmosName || initialData?.cosmosName || ''; const cleanHandle = identityHandle.replace(/^@/, ''); const cleanServer = serverBaseUrl.replace(/\/+$/, ''); const defaultName = `proxy_${cleanHandle || 'anon'}_${cosmosName || 'root'}`.replace(/[\s\/@]/g, '_'); const uuid = opts?.uuid || initialData?.uuid || defaultName; const name = opts?.name || initialData?.name || defaultName; super( { ...(initialData ?? {}), uuid, classname: PROXY_READONLY_SPACE_CLASSNAME, name, serverBaseUrl: cleanServer, identityHandle: cleanHandle, cosmosName, galaxyName: opts?.galaxyName || initialData?.galaxyName, branchName: opts?.branchName || initialData?.branchName, isReadOnly: true, catchAllErrors: false, }, initialRel8ns ? { ...initialRel8ns } : undefined ); this._serverBaseUrl = cleanServer; this._identityHandle = cleanHandle; this._cosmosName = cosmosName; this._galaxyName = opts?.galaxyName || initialData?.galaxyName; this._branchName = opts?.branchName || initialData?.branchName; this._cacheSpace = opts?.cacheSpace; this._fetchFn = opts?.customFetch || (typeof fetch !== 'undefined' ? fetch.bind(globalThis) : async () => { throw new Error(`fetch is not defined in this runtime (E: a61f125f87d0680eb145dac3b9e77201)`); }); if (opts?.snapshotIbGib) { this.snapshotIbGib = opts.snapshotIbGib; } this.initialized = (async () => { this.ib = getSpaceIb({ space: this, classname: PROXY_READONLY_SPACE_CLASSNAME }); this.gib = await getGib({ ibGib: this }); })(); } protected override async initialize(): Promise { // True initialization chaining in constructor } public get serverBaseUrl(): string { return this._serverBaseUrl; } public get identityHandle(): string { return this._identityHandle; } public get cosmosName(): string { return this._cosmosName; } public get galaxyName(): string | undefined { return this._galaxyName; } public get branchName(): string | undefined { return this._branchName; } public get cacheSpace(): IbGibSpaceAny | undefined { return this._cacheSpace; } public get snapshotIbGib(): B2tFSSnapshotIbGib_V1 | undefined { return this._snapshotIbGib; } public set snapshotIbGib(snapshot: B2tFSSnapshotIbGib_V1 | undefined) { this._snapshotIbGib = snapshot; this.updateSnapshotIndex(snapshot); } private updateSnapshotIndex(snapshot?: B2tFSSnapshotIbGib_V1): void { if (!snapshot?.data) return; const indexAddr = (addr?: string) => { if (!addr) return; const tjpGib = getTjpGibFromAddr(addr); if (tjpGib) { this._snapshotTjpMap.set(tjpGib, addr); } }; if (snapshot.data.items) { for (const [_, itemTuple] of Object.entries(snapshot.data.items)) { if (Array.isArray(itemTuple)) { indexAddr(itemTuple[0]); if (itemTuple[1]) indexAddr(itemTuple[1]); } } } indexAddr(snapshot.data.rootItemAddr); indexAddr(snapshot.data.prevBranchAddr); indexAddr(snapshot.data.galaxyAddr); indexAddr(snapshot.data.cosmosAddr); indexAddr(snapshot.data.commitMessageAddr); } public setGalaxyAndBranch(galaxyName?: string, branchName?: string): void { this._galaxyName = galaxyName; if (branchName !== undefined) { this._branchName = branchName; } } /** * Resolves a scoped URL for this tenant and cosmos. */ private buildScopedUrl(endpointPath: string, queryParams?: Record): string { const cleanHandle = encodeURIComponent(this._identityHandle); const cleanCosmos = encodeURIComponent(this._cosmosName); const subPath = endpointPath.replace(/^\/+/, ''); let url = `${this._serverBaseUrl}/api/${cleanHandle}/${cleanCosmos}/${subPath}`; const params = new URLSearchParams(); if (this._galaxyName) { params.set('galaxy', this._galaxyName); } if (this._branchName) { params.set('branch', this._branchName); } if (queryParams) { for (const [k, v] of Object.entries(queryParams)) { params.set(k, v); } } const qs = params.toString(); if (qs) { url += (url.includes('?') ? '&' : '?') + qs; } return url; } /** * Raw fetch of a single ibGib node over HTTP with intrinsic verification. */ private async doRawFetchRemoteIbGib(addr: string): Promise { const lc = `${this.lc}[${this.doRawFetchRemoteIbGib.name}]`; if (!addr) { return undefined; } const encodedAddr = encodeURIComponent(addr); const url = this.buildScopedUrl(`ibgib/${encodedAddr}`); const response = await this._fetchFn(url); if (!response.ok) { if (response.status === 404) { return undefined; } throw new Error(`HTTP ${response.status} fetching ibGib [${addr}]: ${response.statusText} (E: ba868de9c43c5e6a577a0b113481b6b2)`); } const json = await response.json(); const ibGib = json?.ibGib || json; if (!ibGib || !ibGib.ib || !ibGib.gib) { throw new Error(`Server returned invalid ibGib payload for [${addr}] (E: e475fe5622ca799197b0a43e42d1a55f)`); } // Rehydrate Node Buffer JSON serialization to Uint8Array for intrinsic validation & binary decoding if (ibGib.data && (ibGib.data as any).type === 'Buffer' && Array.isArray((ibGib.data as any).data)) { ibGib.data = new Uint8Array((ibGib.data as any).data); } // Rigorous Intrinsic Security Validation const validationErrors = await validateIbGibIntrinsically({ ibGib }); if (validationErrors && validationErrors.length > 0) { throw new Error(`Security validation failed for remote ibGib [${addr}]: ${validationErrors.join(', ')} (E: ff4b80ec4dcae4a5eb6d3d91e37a9f31)`); } const computedAddr = getIbGibAddr({ ibGib }); if (computedAddr !== addr) { throw new Error(`Intrinsic address mismatch: expected [${addr}], computed [${computedAddr}] (E: 3ac3039e007d1e15a6065ca188e59ef8)`); } return ibGib; } /** * Processes the serialized fetch queue in a single critical section: * 1. Quickly filters all addrs in queue against cache space, resolving cached items immediately. * 2. Fetches the next non-cached ibGib, verifies intrinsically, and puts into cache space. * 3. Re-filters remaining queue against cache space and repeats until queue is drained. */ private async processFetchQueue(): Promise { if (this._isProcessingQueue) { return; } this._isProcessingQueue = true; try { while (this._fetchQueue.length > 0) { // Step 1: Quick/cheap filter for all addrs in the queue that are in the cache if (this._cacheSpace) { const remainingQueue: QueuedFetchWaiter[] = []; for (const waiter of this._fetchQueue) { try { const cacheRes = await getFromSpace({ addr: waiter.addr, space: this._cacheSpace }); const cached = cacheRes?.ibGibs?.[0]; if (cached) { waiter.resolve(cached); } else { remainingQueue.push(waiter); } } catch { remainingQueue.push(waiter); } } this._fetchQueue = remainingQueue; } if (this._fetchQueue.length === 0) { break; } // Step 2: Proceed to fetch the next non-cached ibgib in the queue const nextItem = this._fetchQueue[0]; const targetAddr = nextItem.addr; const waitersForTarget = this._fetchQueue.filter(w => w.addr === targetAddr); this._fetchQueue = this._fetchQueue.filter(w => w.addr !== targetAddr); try { const remoteIbGib = await this.doRawFetchRemoteIbGib(targetAddr); if (remoteIbGib && this._cacheSpace) { try { const check = await getFromSpace({ addr: targetAddr, space: this._cacheSpace }); if (!check?.ibGibs?.[0]) { await putInSpace({ ibGib: remoteIbGib, space: this._cacheSpace }); } } catch (cacheErr) { if (logalot) { console.warn(`${this.lc} Failed to write ibGib to cache space: ${extractErrorMsg(cacheErr)}`); } } } for (const waiter of waitersForTarget) { waiter.resolve(remoteIbGib); } } catch (fetchErr) { for (const waiter of waitersForTarget) { waiter.reject(fetchErr); } } } } finally { this._isProcessingQueue = false; if (this._fetchQueue.length > 0) { void this.processFetchQueue(); } } } /** * Enqueues an address for serialized remote fetching with dynamic cache filtering. */ private async fetchRemoteIbGib(addr: string): Promise { if (!addr) return undefined; // Quick check before enqueuing if (this._cacheSpace) { const getRes = await getFromSpace({ addr, space: this._cacheSpace }); const cachedItem = getRes?.ibGibs?.[0]; if (cachedItem) { return cachedItem; } } return new Promise((resolve, reject) => { this._fetchQueue.push({ addr, resolve, reject }); void this.processFetchQueue(); }); } protected override async witnessImpl(arg: AnySpaceOptionsIbGib): Promise { const lc = `${this.lc}[${this.witnessImpl.name}]`; const cmd = arg.data?.cmd; const cmdModifiers = arg.data?.cmdModifiers ?? []; if (logalot) { console.log(`${lc} handling cmd: ${cmd}`); } if (cmd === IbGibSpaceOptionsCmd.put) { if (cmdModifiers.includes('can')) { return await this.canPut(arg); } throw new ReadOnlySpaceError(`${lc} Command 'put' is forbidden on read-only proxy space (E: 129c5325b8f6cd88675aa49a60a9c78e)`); } if (cmd === IbGibSpaceOptionsCmd.delete) { if (cmdModifiers.includes('can')) { return await this.canDelete(arg); } throw new ReadOnlySpaceError(`${lc} Command 'delete' is forbidden on read-only proxy space (E: 0da1244b6f8ae1294b35c89700bac320)`); } if (cmd === IbGibSpaceOptionsCmd.get) { if (cmdModifiers.includes('can')) { return await this.canGetImpl(arg); } if (cmdModifiers.includes('latest')) { return await this.getLatestAddrsImpl(arg); } return await this.getImpl(arg); } throw new Error(`${lc} Unsupported space command: '${cmd}' (E: c7f98af48f809e18ff8d0f03b0a2887e)`); } protected async canPut(arg: AnySpaceOptionsIbGib): Promise { const resultData: any = { optsAddr: getIbGibAddr({ ibGib: arg }), success: true, can: false, }; return await this.resulty({ resultData }); } protected async canDelete(arg: AnySpaceOptionsIbGib): Promise { const resultData: any = { optsAddr: getIbGibAddr({ ibGib: arg }), success: true, can: false, }; return await this.resulty({ resultData }); } protected override async getImpl(arg: AnySpaceOptionsIbGib): Promise { const addrs = arg.data?.ibGibAddrs || []; const ibGibs: IbGib_V1[] = []; for (const addr of addrs) { const item = await this.fetchRemoteIbGib(addr); if (item) { ibGibs.push(item); } } const resultData: any = { optsAddr: getIbGibAddr({ ibGib: arg }), success: true, }; return await this.resulty({ resultData, ibGibs }); } protected override async canGetImpl(arg: AnySpaceOptionsIbGib): Promise { const addrs = arg.data?.ibGibAddrs || []; const canGetAddrs: string[] = []; for (const addr of addrs) { try { if (this._cacheSpace) { const getRes = await getFromSpace({ addr, space: this._cacheSpace }); if (getRes?.success && (getRes?.ibGibs?.length || 0) > 0) { canGetAddrs.push(addr); continue; } } const remoteItem = await this.fetchRemoteIbGib(addr); if (remoteItem) { canGetAddrs.push(addr); } } catch { // Ignore cannot get } } const resultData: any = { optsAddr: getIbGibAddr({ ibGib: arg }), success: true, can: canGetAddrs.length === addrs.length, canGetAddrs, }; return await this.resulty({ resultData }); } /** * Loads the snapshot manifest stone for this galaxy and branch from the server if not already loaded. */ public async loadSnapshot(): Promise { const lc = `${this.lc}[${this.loadSnapshot.name}]`; if (this._snapshotIbGib) return this._snapshotIbGib; if (!this._galaxyName) return undefined; try { const url = this.buildScopedUrl('snapshot'); const res = await this._fetchFn(url); if (res.ok) { const json = await res.json(); const snapshot = json?.snapshot || json; if (snapshot?.data) { this.snapshotIbGib = snapshot; if (this._cacheSpace) { try { const check = await getFromSpace({ addr: getIbGibAddr({ ibGib: snapshot }), space: this._cacheSpace }); if (!check?.ibGibs?.[0]) { await putInSpace({ ibGib: snapshot, space: this._cacheSpace }); } } catch { // ignore cache write error } } return snapshot; } } } catch (err) { if (logalot) { console.warn(`${lc} Failed to load snapshot: ${extractErrorMsg(err)}`); } } return undefined; } protected override async getLatestAddrsImpl(arg: AnySpaceOptionsIbGib): Promise { const addrs = arg.data?.ibGibAddrs || []; const latestAddrs: string[] = []; const latestAddrsMap: Record = {}; if (!this._snapshotIbGib && this._galaxyName) { await this.loadSnapshot(); } for (const addr of addrs) { const tjpGib = getTjpGibFromAddr(addr); const snapshotMatch = this._snapshotTjpMap.get(tjpGib); if (snapshotMatch) { latestAddrs.push(snapshotMatch); latestAddrsMap[addr] = snapshotMatch; continue; } // Fallback for keystones, cosmos, or items outside snapshot: query server const encodedAddr = encodeURIComponent(addr); const url = this.buildScopedUrl(`ibgib/${encodedAddr}`, { getLatest: 'true', addrOnly: 'true' }); try { const res = await this._fetchFn(url); if (res.ok) { const body = await res.json(); const resolved = body?.addr || addr; latestAddrs.push(resolved); latestAddrsMap[addr] = resolved; } else { latestAddrs.push(addr); latestAddrsMap[addr] = addr; } } catch { latestAddrs.push(addr); latestAddrsMap[addr] = addr; } } const resultData: any = { optsAddr: getIbGibAddr({ ibGib: arg }), success: true, addrs: latestAddrs, latestAddrs, latestAddrsMap, }; return await this.resulty({ resultData }); } protected override async putImpl(_arg: AnySpaceOptionsIbGib): Promise { throw new ReadOnlySpaceError(`Command 'put' is forbidden on read-only proxy space (E: 7271fb70e0799b68de798f0fcb1ca773)`); } protected override async deleteImpl(_arg: AnySpaceOptionsIbGib): Promise { throw new ReadOnlySpaceError(`Command 'delete' is forbidden on read-only proxy space (E: 2f788b2e7e5b02dd4ca1c049432b101a)`); } protected override async persistOptsAndResultIbGibs(_arg: any): Promise { // Zero persistence for options/results in proxy space } }