Files

52 lines
2.4 KiB
JavaScript

// server/fork.mjs -- fork: a run copied whole, the owner replaced.
//
// Runs are entirely independent: no lineage is recorded, and the only
// mark a fork bears is `forked: unixtime` in run.json (its `created`
// carries over unchanged -- the story's start date is a fact of the
// contents). No inconsistent state on disk at any point: the copy
// lands staged under a dot-name and is swapped in by a same-volume
// rename, which is atomic -- no reader ever sees a half-run. The
// caller holds the source run's activity lock, so the copy is never
// taken mid-turn; a copied open session reopens honestly in the fork
// (the log is the truth, same as boot-rebuild).
import fs from 'node:fs';
import path from 'node:path';
import { randomBytes } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { requireRun } from './bundle.mjs';
import { liveSession, loadSession } from './session.mjs';
/** @typedef {import('./shapes.mjs').LiveSession} LiveSession */
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const RUNS_DIR = path.join(ROOT, 'runs');
/**
* @param {{ sessions: Map<string, LiveSession> }} ctx
* @param {string} srcId @param {{ id: string }} user
* @returns {{ run: string }}
*/
export function forkRun(ctx, srcId, user) {
requireRun(srcId);
let id;
for (;;) {
id = randomBytes(4).toString('hex'); // anonymous, same alphabet as create
if (!fs.existsSync(path.join(RUNS_DIR, id)) && !fs.existsSync(path.join(RUNS_DIR, `.staging-${id}`))) break;
}
const staging = path.join(RUNS_DIR, `.staging-${id}`);
fs.cpSync(path.join(RUNS_DIR, srcId), staging, { recursive: true }); // sync: atomic wrt the event loop
const metaPath = path.join(staging, 'run.json');
const meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
meta.owner = user.id;
meta.forked = Math.floor(Date.now() / 1000); // unixtime, UTC by definition
fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2) + '\n');
fs.renameSync(staging, path.join(RUNS_DIR, id)); // same-volume rename: the atomic swap-in
// a live session in the source is a live session in the fork -- the
// log is the truth, same as boot-rebuild; a dormant run forks
// dormant (the review window copies honestly, unhousekept guard
// included)
const live = liveSession(id);
if (live != null) ctx.sessions.set(id, loadSession(id, live));
return { run: id };
}