Files
tiny-worlds/server/fork.mjs
T

44 lines
2.2 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 window 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 { latestSession, lastHousekept, loadSession } from './session.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const RUNS_DIR = path.join(ROOT, 'runs');
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
// an open, unhousekept window in the source is an open window in the
// fork — its transcript reaches the fork's rings only after the fork
// housekeeps it, same rule as the original
const latest = latestSession(id);
if (latest && latest !== lastHousekept(id)) ctx.sessions.set(id, loadSession(id, latest));
return { run: id };
}