/** * Durable list of checkpoints for one document. * * Local copy under data/versions// (snapshots + index.json), mirrored * to the HF dataset under versions// with one commit per checkpoint. * The dataset is the durable copy on Spaces, where the container disk is * wiped on every restart. */ import { existsSync, mkdirSync, readFileSync } from "fs"; import { join } from "path"; import { atomicWriteFileSync, getDataDir, sanitizeName } from "../utils.js"; import { commitDatasetFiles, getDatasetId, isHfStorageEnabled, readDatasetFile } from "../hf-storage.js"; export type CheckpointReason = "auto" | "manual" | "agent-before" | "agent-after" | "publish" | "restore"; export interface Contributor { name: string; agent?: boolean; avatarUrl?: string; /** HF account an agent acted for. */ onBehalfOf?: string; } export interface VersionMeta { id: string; createdAt: number; reason: CheckpointReason; label?: string; createdBy?: Contributor; /** Who changed the document since the previous checkpoint. */ contributors: Contributor[]; fingerprint: string; words: number; bytes: number; /** Restores record which version they came from. */ restoredFrom?: string; } function newId(at: number): string { const stamp = new Date(at).toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15); return `${stamp}-${Math.random().toString(36).slice(2, 6)}`; } function mergeIndexes(a: VersionMeta[], b: VersionMeta[]): VersionMeta[] { const byId = new Map(); for (const v of [...a, ...b]) byId.set(v.id, v); return [...byId.values()].sort((x, y) => x.createdAt - y.createdAt); } export class VersionStore { private index: VersionMeta[] | null = null; private remoteLoaded = false; private loading: Promise | null = null; /** Snapshot ids written locally but not yet committed to the dataset. */ private unsynced = new Set(); private syncChain: Promise = Promise.resolve(); lastSyncError: string | null = null; constructor(readonly docName: string) {} private get dir(): string { return join(getDataDir(), "versions", sanitizeName(this.docName)); } private get remoteDir(): string { return `versions/${sanitizeName(this.docName)}`; } private writeLocalIndex(): void { mkdirSync(this.dir, { recursive: true }); atomicWriteFileSync(join(this.dir, "index.json"), Buffer.from(JSON.stringify(this.index, null, 2))); } private async readRemoteIndex(): Promise { const raw = await readDatasetFile(`${this.remoteDir}/index.json`); return raw ? (JSON.parse(Buffer.from(raw).toString("utf8")) as VersionMeta[]) : []; } /** Throws when the dataset can't be read: an empty list would be a lie. */ async list(): Promise { const remoteReadable = Boolean(getDatasetId()) && isHfStorageEnabled(); if (this.index && (this.remoteLoaded || !remoteReadable)) return this.index; if (!this.loading) { this.loading = (async () => { if (!this.index) { const localPath = join(this.dir, "index.json"); this.index = existsSync(localPath) ? (JSON.parse(readFileSync(localPath, "utf8")) as VersionMeta[]) : []; } if (remoteReadable) { // Credentials arrive with the first login; until then the list is local only. this.index = mergeIndexes(await this.readRemoteIndex(), this.index); this.remoteLoaded = true; } return this.index; })().finally(() => { this.loading = null; }); } return this.loading; } async add( state: Uint8Array, meta: Omit, ): Promise { const index = await this.list(); const createdAt = Date.now(); const version: VersionMeta = { ...meta, id: newId(createdAt), createdAt, bytes: state.byteLength }; mkdirSync(this.dir, { recursive: true }); atomicWriteFileSync(join(this.dir, `${version.id}.yjs`), Buffer.from(state)); index.push(version); this.writeLocalIndex(); this.unsynced.add(version.id); void this.sync().catch(() => {}); return version; } async read(id: string): Promise { if (!/^[\w-]{1,64}$/.test(id)) return null; const localPath = join(this.dir, `${id}.yjs`); if (existsSync(localPath)) return new Uint8Array(readFileSync(localPath)); if (!getDatasetId()) return null; const remote = await readDatasetFile(`${this.remoteDir}/${id}.yjs`); if (remote) { mkdirSync(this.dir, { recursive: true }); atomicWriteFileSync(localPath, Buffer.from(remote)); } return remote; } /** * Commit unsynced snapshots plus the index. The remote index is re-read * first and merged, so another server writing to the same dataset (a * local dev run, a duplicated Space) never drops entries. */ sync(): Promise { const run = async () => { if (!this.unsynced.size || !getDatasetId() || !isHfStorageEnabled()) return; const ids = [...this.unsynced]; try { const remote = await this.readRemoteIndex(); this.index = mergeIndexes(remote, this.index ?? []); this.writeLocalIndex(); const files: { path: string; content: Uint8Array | string }[] = []; for (const id of ids) { const localPath = join(this.dir, `${id}.yjs`); if (existsSync(localPath)) files.push({ path: `${this.remoteDir}/${id}.yjs`, content: readFileSync(localPath) }); } files.push({ path: `${this.remoteDir}/index.json`, content: JSON.stringify(this.index, null, 2) + "\n" }); const latest = this.index.find((v) => v.id === ids[ids.length - 1]); await commitDatasetFiles(files, `version ${sanitizeName(this.docName)}: ${latest?.label || latest?.reason || "checkpoint"}`); for (const id of ids) this.unsynced.delete(id); this.lastSyncError = null; console.log(`[versions] committed ${ids.length} checkpoint(s) for "${this.docName}"`); } catch (err) { this.lastSyncError = (err as Error).message; console.error(`[versions] dataset commit failed for "${this.docName}":`, this.lastSyncError); throw err; } }; const next = this.syncChain.then(run, run); this.syncChain = next.catch(() => {}); return next; } get pendingSync(): number { return this.unsynced.size; } }