import { readFile, writeFile } from "node:fs/promises"; import type { PonyCommitMessage } from "./commit-message.js"; import { throwRejectedResults } from "./promise-results.js"; import type { PonyProject } from "./project.js"; import { applyWritePolicy, type WritePolicyResult } from "./write-policy.js"; export interface PendingWrite { apply: () => Promise; rollback: () => Promise; } export interface PendingFileWrite extends PendingWrite { absolutePath: string; } export async function createPendingFileWrite( absolutePath: string, apply: () => Promise, ): Promise { const previousContent = await readFile(absolutePath, "utf8"); return { absolutePath, apply, rollback: () => writeFile(absolutePath, previousContent, "utf8"), }; } /** * Multi-record domain mutations must never leave successfully written files * ahead of a later failed write, even in working-tree delivery mode. */ export async function applyWritesAtomically( writes: PendingWrite[], ): Promise { const completed: PendingWrite[] = []; try { for (const write of writes) { await write.apply(); completed.push(write); } } catch (error) { for (const write of completed.reverse()) { await write.rollback().catch(() => undefined); } throw error; } } export async function rollbackWrites(writes: PendingWrite[]): Promise { const results = await Promise.allSettled( [...writes].reverse().map((write) => write.rollback()), ); throwRejectedResults(results, "Failed to restore Pony mutation files."); } export interface ConfigAndRecordMutation { project: PonyProject; recordWrites: PendingFileWrite[]; previousConfigContent: string; nextConfigContent: string; commitMessage: PonyCommitMessage; } /** * Config migrations share one transaction boundary: all record writes and the * config marker are delivered or restored together under the project policy. */ export async function applyConfigAndRecordMutation({ project, recordWrites, previousConfigContent, nextConfigContent, commitMessage, }: ConfigAndRecordMutation): Promise { const configWrite: PendingWrite = { apply: () => writeFile(project.configPath, nextConfigContent, "utf8"), rollback: () => writeFile(project.configPath, previousConfigContent, "utf8"), }; const writes = [...recordWrites, configWrite]; return applyWritePolicy(project, { targets: [ ...recordWrites.map(({ absolutePath }) => ({ absolutePath, existed: true, })), { absolutePath: project.configPath, existed: true }, ], commitMessage, apply: () => applyWritesAtomically(writes), rollback: () => rollbackWrites(writes), }); }