Adds prettier 3.9.8 (exact) with a shared config (single quotes, 120 columns, trailing commas), .prettierignore, .editorconfig and the `format` / `format:check` scripts, then formats all TypeScript, JavaScript, CSS, JSON and YAML sources. Purely mechanical: no behaviour change. Typecheck passes, the vitest suite and the 74 IDE node tests produce the same results as before (socket-binding tests still cannot run inside this sandbox). Previously the longest source line was ~3000 characters; reviewing the following semantic changes now produces readable diffs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
670 lines
27 KiB
JavaScript
670 lines
27 KiB
JavaScript
'use strict';
|
|
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const { createHash, randomBytes } = require('node:crypto');
|
|
const { fileURLToPath } = require('node:url');
|
|
|
|
const EXCLUDED = new Set([
|
|
'.git',
|
|
'node_modules',
|
|
'dist',
|
|
'build',
|
|
'coverage',
|
|
'.next',
|
|
'.cache',
|
|
'src-gen',
|
|
'.wishforge',
|
|
'.wishforge-runtime',
|
|
'.runtime',
|
|
'.coordination',
|
|
]);
|
|
const CLIENT_TTL_MS = 30_000;
|
|
const BARRIER_TTL_MS = 30_000;
|
|
const DEBUG_LEASE_MS = 30_000;
|
|
const DEFAULT_SNAPSHOT_LIMITS = Object.freeze({
|
|
maxFileBytes: 32 * 1024 * 1024,
|
|
maxTotalBytes: 256 * 1024 * 1024,
|
|
maxFiles: 20_000,
|
|
});
|
|
|
|
class CoordinationError extends Error {
|
|
constructor(code, message) {
|
|
super(message);
|
|
this.name = 'CoordinationError';
|
|
this.code = code;
|
|
}
|
|
}
|
|
function fail(code, message) {
|
|
throw new CoordinationError(code, message);
|
|
}
|
|
function sha(value) {
|
|
return createHash('sha256').update(value).digest('hex');
|
|
}
|
|
function clone(value) {
|
|
return JSON.parse(JSON.stringify(value));
|
|
}
|
|
function inside(root, target) {
|
|
return target === root || target.startsWith(root + path.sep);
|
|
}
|
|
function identifier(value, name) {
|
|
if (typeof value !== 'string' || value.length < 1 || value.length > 256 || /[\u0000-\u001f]/.test(value))
|
|
fail('INVALID_INPUT', `Invalid ${name}`);
|
|
return value;
|
|
}
|
|
function directorySync(directory) {
|
|
const fd = fs.openSync(directory, fs.constants.O_RDONLY);
|
|
try {
|
|
fs.fsyncSync(fd);
|
|
} finally {
|
|
fs.closeSync(fd);
|
|
}
|
|
}
|
|
function atomicFile(destination, value, immutable = false) {
|
|
const temporary = destination + '.' + randomBytes(16).toString('hex') + '.tmp';
|
|
const fd = fs.openSync(temporary, 'wx', 0o600);
|
|
try {
|
|
fs.writeFileSync(fd, value);
|
|
fs.fsyncSync(fd);
|
|
} finally {
|
|
fs.closeSync(fd);
|
|
}
|
|
try {
|
|
if (immutable) {
|
|
fs.chmodSync(temporary, 0o400);
|
|
fs.linkSync(temporary, destination); // Unlike rename, this must never replace a committed object.
|
|
fs.unlinkSync(temporary);
|
|
} else fs.renameSync(temporary, destination);
|
|
directorySync(path.dirname(destination));
|
|
} finally {
|
|
if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
|
|
}
|
|
}
|
|
function ensurePrivateDirectory(directory) {
|
|
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
if (fs.lstatSync(directory).isSymbolicLink() || !fs.statSync(directory).isDirectory())
|
|
fail('UNSAFE_STATE_PATH', 'State path must be a real directory');
|
|
fs.chmodSync(directory, 0o700);
|
|
}
|
|
function prospectiveRealPath(directory) {
|
|
let existing = directory;
|
|
const missing = [];
|
|
while (!fs.existsSync(existing)) {
|
|
const parent = path.dirname(existing);
|
|
if (parent === existing) fail('UNSAFE_STATE_PATH', 'State directory has no existing ancestor');
|
|
missing.unshift(path.basename(existing));
|
|
existing = parent;
|
|
}
|
|
return path.join(fs.realpathSync(existing), ...missing);
|
|
}
|
|
|
|
class Coordinator {
|
|
constructor({ workspaceRoot, stateDirectory, now = Date.now, limits = {} }) {
|
|
if (typeof workspaceRoot !== 'string' || typeof stateDirectory !== 'string' || typeof now !== 'function')
|
|
fail('INVALID_INPUT', 'Workspace, state directory and clock are required');
|
|
if (
|
|
!limits ||
|
|
typeof limits !== 'object' ||
|
|
Array.isArray(limits) ||
|
|
Object.keys(limits).some(key => !Object.hasOwn(DEFAULT_SNAPSHOT_LIMITS, key))
|
|
)
|
|
fail('INVALID_INPUT', 'Invalid snapshot limits');
|
|
this.limits = Object.freeze({ ...DEFAULT_SNAPSHOT_LIMITS, ...limits });
|
|
for (const [key, value] of Object.entries(this.limits))
|
|
if (!Number.isSafeInteger(value) || value <= 0) fail('INVALID_INPUT', `${key} must be a positive safe integer`);
|
|
this.requestedWorkspaceRoot = path.resolve(workspaceRoot);
|
|
this.workspaceRoot = fs.realpathSync(workspaceRoot);
|
|
if (!fs.statSync(this.workspaceRoot).isDirectory()) fail('INVALID_INPUT', 'Workspace root must be a directory');
|
|
const requested = path.resolve(stateDirectory);
|
|
if (inside(this.workspaceRoot, requested) || inside(requested, this.workspaceRoot))
|
|
fail('UNSAFE_STATE_PATH', 'State directory must be separate from the source workspace');
|
|
if (fs.existsSync(requested) && fs.lstatSync(requested).isSymbolicLink())
|
|
fail('UNSAFE_STATE_PATH', 'State directory must not be a symlink');
|
|
this.stateDirectory = prospectiveRealPath(requested);
|
|
if (inside(this.workspaceRoot, this.stateDirectory) || inside(this.stateDirectory, this.workspaceRoot))
|
|
fail('UNSAFE_STATE_PATH', 'State directory must be separate from the source workspace');
|
|
ensurePrivateDirectory(this.stateDirectory);
|
|
this.objectsDirectory = path.join(this.stateDirectory, 'objects');
|
|
this.snapshotsDirectory = path.join(this.stateDirectory, 'snapshots');
|
|
ensurePrivateDirectory(this.objectsDirectory);
|
|
ensurePrivateDirectory(this.snapshotsDirectory);
|
|
this.now = now;
|
|
this.clients = new Map();
|
|
this.barriers = new Map();
|
|
this.debugLease = null;
|
|
this._withLock(() => this._recover());
|
|
}
|
|
|
|
_withLock(action) {
|
|
const lock = path.join(this.stateDirectory, 'writer.lock');
|
|
let fd;
|
|
try {
|
|
fd = fs.openSync(lock, 'wx', 0o600);
|
|
} catch (error) {
|
|
if (error.code !== 'EEXIST') throw error;
|
|
// A crashed writer leaves a lock. Never steal a live or undecodable lock.
|
|
let previous;
|
|
try {
|
|
previous = JSON.parse(fs.readFileSync(lock, 'utf8'));
|
|
} catch {
|
|
fail('STATE_BUSY', 'State writer lock requires operator inspection');
|
|
}
|
|
if (!Number.isSafeInteger(previous.pid) || previous.pid <= 0) fail('STATE_BUSY', 'State writer lock is invalid');
|
|
try {
|
|
process.kill(previous.pid, 0);
|
|
fail('STATE_BUSY', 'Another coordinator is writing state');
|
|
} catch (probe) {
|
|
if (probe.code !== 'ESRCH') throw probe;
|
|
}
|
|
fs.unlinkSync(lock);
|
|
try {
|
|
fd = fs.openSync(lock, 'wx', 0o600);
|
|
} catch {
|
|
fail('STATE_BUSY', 'Another coordinator is writing state');
|
|
}
|
|
}
|
|
try {
|
|
fs.writeFileSync(fd, JSON.stringify({ pid: process.pid }));
|
|
fs.fsyncSync(fd);
|
|
return action();
|
|
} finally {
|
|
fs.closeSync(fd);
|
|
fs.unlinkSync(lock);
|
|
}
|
|
}
|
|
|
|
_recover() {
|
|
const snapshots = fs
|
|
.readdirSync(this.snapshotsDirectory)
|
|
.filter(name => /^\d{12}\.json$/.test(name))
|
|
.sort();
|
|
let revision = 0;
|
|
let latest = null;
|
|
const commits = new Map();
|
|
for (const name of snapshots) {
|
|
const file = path.join(this.snapshotsDirectory, name);
|
|
if (!fs.lstatSync(file).isFile()) fail('STATE_CORRUPT', 'Snapshot is not a regular file');
|
|
const snapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
const { id, ...body } = snapshot;
|
|
if (
|
|
snapshot.schemaVersion !== 1 ||
|
|
snapshot.workspace !== this.workspaceRoot ||
|
|
snapshot.revision !== revision + 1 ||
|
|
snapshot.previousId !== (latest?.id ?? null) ||
|
|
id !== sha(JSON.stringify(body)) ||
|
|
name !== `${String(snapshot.revision).padStart(12, '0')}.json`
|
|
)
|
|
fail('STATE_CORRUPT', 'Snapshot chain failed integrity verification');
|
|
if (!Array.isArray(snapshot.files) || snapshot.digest !== sha(JSON.stringify(snapshot.files)))
|
|
fail('STATE_CORRUPT', 'Snapshot manifest failed integrity verification');
|
|
for (const item of snapshot.files) {
|
|
if (
|
|
typeof item.path !== 'string' ||
|
|
path.posix.isAbsolute(item.path) ||
|
|
item.path.split('/').some(part => part === '..' || part === '' || part === '.') ||
|
|
!/^[a-f0-9]{64}$/.test(item.sha256)
|
|
)
|
|
fail('STATE_CORRUPT', 'Snapshot contains an unsafe file entry');
|
|
const object = path.join(this.objectsDirectory, item.sha256);
|
|
if (!fs.lstatSync(object).isFile()) fail('STATE_CORRUPT', 'Snapshot object is not a regular file');
|
|
const bytes = fs.readFileSync(object);
|
|
if (bytes.length !== item.size || sha(bytes) !== item.sha256)
|
|
fail('STATE_CORRUPT', 'Snapshot content failed integrity verification');
|
|
}
|
|
revision = snapshot.revision;
|
|
latest = snapshot;
|
|
if (commits.has(snapshot.barrierId)) fail('STATE_CORRUPT', 'Save barrier has multiple committed revisions');
|
|
commits.set(snapshot.barrierId, snapshot);
|
|
}
|
|
const journalPath = path.join(this.stateDirectory, 'journal.json');
|
|
if (fs.existsSync(journalPath)) {
|
|
if (!fs.lstatSync(journalPath).isFile()) fail('STATE_CORRUPT', 'Journal is not a regular file');
|
|
const journal = JSON.parse(fs.readFileSync(journalPath, 'utf8'));
|
|
if (
|
|
journal.schemaVersion !== 1 ||
|
|
journal.workspace !== this.workspaceRoot ||
|
|
!Number.isSafeInteger(journal.revision) ||
|
|
journal.revision > revision ||
|
|
journal.revision < 0 ||
|
|
(journal.revision === revision && journal.latestId !== (latest?.id ?? null))
|
|
)
|
|
fail('STATE_CORRUPT', 'Journal does not match committed snapshots');
|
|
}
|
|
this.revision = revision;
|
|
this.latestSnapshot = latest;
|
|
this.commits = commits;
|
|
// A committed immutable manifest is the transaction record. Repair a stale/missing head after crash.
|
|
atomicFile(
|
|
journalPath,
|
|
JSON.stringify({ schemaVersion: 1, workspace: this.workspaceRoot, revision, latestId: latest?.id ?? null }),
|
|
);
|
|
}
|
|
|
|
_documents(payload) {
|
|
if (
|
|
!payload ||
|
|
!Array.isArray(payload.documents) ||
|
|
payload.documents.length > 10_000 ||
|
|
(payload.dirty !== undefined && typeof payload.dirty !== 'boolean')
|
|
)
|
|
fail('INVALID_INPUT', 'A document version vector is required');
|
|
const seen = new Set();
|
|
const documents = payload.documents
|
|
.map(document => {
|
|
if (
|
|
!document ||
|
|
typeof document.uri !== 'string' ||
|
|
document.uri.length < 1 ||
|
|
document.uri.length > 8192 ||
|
|
/[\u0000-\u001f]/.test(document.uri) ||
|
|
!Number.isSafeInteger(document.version) ||
|
|
document.version < 0 ||
|
|
typeof document.dirty !== 'boolean'
|
|
)
|
|
fail('INVALID_INPUT', 'Invalid document version');
|
|
let uri = document.uri;
|
|
if (uri.startsWith('file:')) {
|
|
let target;
|
|
try {
|
|
target = fileURLToPath(uri);
|
|
} catch {
|
|
fail('INVALID_INPUT', 'Invalid file URI');
|
|
}
|
|
// macOS /var and /tmp aliases, or a provisioned root alias, refer to the same configured workspace.
|
|
if (inside(this.requestedWorkspaceRoot, path.resolve(target)))
|
|
target = path.resolve(this.workspaceRoot, path.relative(this.requestedWorkspaceRoot, target));
|
|
if (!inside(this.workspaceRoot, path.resolve(target)))
|
|
fail('OUTSIDE_WORKSPACE', 'Document is outside this workspace');
|
|
uri = path.relative(this.workspaceRoot, target).split(path.sep).join('/');
|
|
} else if (!/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(uri)) {
|
|
const target = path.resolve(this.workspaceRoot, uri);
|
|
if (!inside(this.workspaceRoot, target)) fail('OUTSIDE_WORKSPACE', 'Document is outside this workspace');
|
|
uri = path.relative(this.workspaceRoot, target).split(path.sep).join('/');
|
|
}
|
|
// Non-file editor URIs (including collaboration and untitled documents) are opaque IDs, never paths to read.
|
|
if (seen.has(uri)) fail('INVALID_INPUT', 'Duplicate document URI');
|
|
seen.add(uri);
|
|
return { uri, version: document.version, dirty: document.dirty };
|
|
})
|
|
.sort((left, right) => left.uri.localeCompare(right.uri));
|
|
return { documents, dirty: payload.dirty === true || documents.some(document => document.dirty) };
|
|
}
|
|
|
|
_versions(documents) {
|
|
return JSON.stringify(documents.map(({ uri, version }) => ({ uri, version })));
|
|
}
|
|
_invalidate(reason) {
|
|
for (const barrier of this.barriers.values())
|
|
if (barrier.status === 'pending') {
|
|
barrier.status = 'invalid';
|
|
barrier.reason = reason;
|
|
}
|
|
}
|
|
_activeClients() {
|
|
return [...this.clients.values()].filter(client => this.now() - client.lastSeen < CLIENT_TTL_MS);
|
|
}
|
|
|
|
register(actorId, clientId, payload) {
|
|
identifier(actorId, 'actor ID');
|
|
identifier(clientId, 'client ID');
|
|
const existing = this.clients.get(clientId);
|
|
if (existing && existing.actorId !== actorId) fail('CLIENT_OWNERSHIP', 'Client belongs to another actor');
|
|
const normalized = this._documents(payload);
|
|
for (const barrier of this.barriers.values()) {
|
|
if (barrier.status !== 'pending') continue;
|
|
const participant = barrier.participants.find(item => item.clientId === clientId);
|
|
if (
|
|
!participant ||
|
|
this._versions(normalized.documents) !== this._versions(participant.documents) ||
|
|
normalized.dirty
|
|
) {
|
|
barrier.status = 'invalid';
|
|
barrier.reason = 'Client membership or document version changed';
|
|
}
|
|
}
|
|
const client = { actorId, clientId, ...normalized, lastSeen: this.now() };
|
|
this.clients.set(clientId, client);
|
|
return clone(client);
|
|
}
|
|
|
|
unregister(actorId, clientId) {
|
|
identifier(actorId, 'actor ID');
|
|
identifier(clientId, 'client ID');
|
|
const client = this.clients.get(clientId);
|
|
if (!client) return { unregistered: true };
|
|
if (client.actorId !== actorId) fail('CLIENT_OWNERSHIP', 'Client belongs to another actor');
|
|
this.clients.delete(clientId);
|
|
for (const barrier of this.barriers.values())
|
|
if (barrier.status === 'pending' && barrier.participants.some(item => item.clientId === clientId)) {
|
|
barrier.status = 'invalid';
|
|
barrier.reason = 'Participant disconnected';
|
|
}
|
|
return { unregistered: true };
|
|
}
|
|
|
|
_capture(retainBlobs = true) {
|
|
const files = [];
|
|
const blobs = new Map();
|
|
let totalBytes = 0;
|
|
const checkSize = size => {
|
|
if (size > BigInt(this.limits.maxFileBytes)) fail('SNAPSHOT_LIMIT', 'Snapshot file exceeds maxFileBytes');
|
|
if (size + BigInt(totalBytes) > BigInt(this.limits.maxTotalBytes))
|
|
fail('SNAPSHOT_LIMIT', 'Snapshot exceeds maxTotalBytes');
|
|
};
|
|
const walk = (directory, relative = '') => {
|
|
for (const name of fs.readdirSync(directory).sort()) {
|
|
if (EXCLUDED.has(name)) continue;
|
|
const absolute = path.join(directory, name);
|
|
const entry = fs.lstatSync(absolute);
|
|
if (entry.isSymbolicLink()) fail('UNSAFE_WORKSPACE_PATH', 'Snapshots reject symbolic links');
|
|
const logical = relative ? relative + '/' + name : name;
|
|
if (entry.isDirectory()) {
|
|
if (!inside(this.workspaceRoot, fs.realpathSync(absolute)))
|
|
fail('UNSAFE_WORKSPACE_PATH', 'Directory escaped the workspace');
|
|
walk(absolute, logical);
|
|
} else if (entry.isFile()) {
|
|
if (files.length >= this.limits.maxFiles) fail('SNAPSHOT_LIMIT', 'Snapshot exceeds maxFiles');
|
|
if (!Number.isSafeInteger(entry.size) || entry.size < 0)
|
|
fail('SNAPSHOT_LIMIT', 'Snapshot file has unsupported size');
|
|
checkSize(BigInt(entry.size));
|
|
// Check both the path and open descriptor; O_NOFOLLOW rejects last-component symlink races.
|
|
if (!inside(this.workspaceRoot, fs.realpathSync(absolute)))
|
|
fail('UNSAFE_WORKSPACE_PATH', 'File escaped the workspace');
|
|
const fd = fs.openSync(absolute, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
let bytes;
|
|
try {
|
|
const before = fs.fstatSync(fd, { bigint: true });
|
|
if (!before.isFile() || before.ino !== BigInt(entry.ino) || before.dev !== BigInt(entry.dev))
|
|
fail('DISK_CHANGED', 'File changed while reading');
|
|
checkSize(before.size);
|
|
// A file may grow after fstat. Never let readFileSync allocate from
|
|
// that mutable size; read only the already-validated bounded length.
|
|
bytes = Buffer.alloc(Number(before.size));
|
|
let read = 0;
|
|
while (read < bytes.length) {
|
|
const count = fs.readSync(fd, bytes, read, bytes.length - read, null);
|
|
if (!count) break;
|
|
read += count;
|
|
}
|
|
const extra = fs.readSync(fd, Buffer.alloc(1), 0, 1, null);
|
|
const after = fs.fstatSync(fd, { bigint: true });
|
|
checkSize(after.size);
|
|
if (
|
|
read !== bytes.length ||
|
|
extra !== 0 ||
|
|
before.ino !== after.ino ||
|
|
before.size !== after.size ||
|
|
before.mtimeNs !== after.mtimeNs ||
|
|
before.ctimeNs !== after.ctimeNs ||
|
|
after.size !== BigInt(bytes.length)
|
|
)
|
|
fail('DISK_CHANGED', 'File changed while reading');
|
|
} finally {
|
|
fs.closeSync(fd);
|
|
}
|
|
totalBytes += bytes.length;
|
|
const digest = sha(bytes);
|
|
if (retainBlobs) blobs.set(digest, bytes);
|
|
files.push({ path: logical, sha256: digest, size: bytes.length, mode: entry.mode & 0o777 });
|
|
} else fail('UNSAFE_WORKSPACE_PATH', 'Snapshots support regular files and directories only');
|
|
}
|
|
};
|
|
walk(this.workspaceRoot);
|
|
return { files, digest: sha(JSON.stringify(files)), blobs };
|
|
}
|
|
|
|
beginBarrier(actorId) {
|
|
identifier(actorId, 'actor ID');
|
|
for (const barrier of this.barriers.values())
|
|
if (barrier.status === 'pending' && this.now() < barrier.expiresAt)
|
|
fail('BARRIER_BUSY', 'A save barrier is already pending');
|
|
const active = this._activeClients();
|
|
if (!active.some(client => client.actorId === actorId))
|
|
fail('CLIENT_REQUIRED', 'Register an active client before starting a barrier');
|
|
const disk = this._capture(false);
|
|
const barrier = {
|
|
id: randomBytes(24).toString('hex'),
|
|
actorId,
|
|
status: 'pending',
|
|
createdAt: this.now(),
|
|
expiresAt: this.now() + BARRIER_TTL_MS,
|
|
diskDigest: disk.digest,
|
|
participants: active.map(client => ({
|
|
actorId: client.actorId,
|
|
clientId: client.clientId,
|
|
documents: clone(client.documents),
|
|
acknowledged: false,
|
|
})),
|
|
};
|
|
this.barriers.set(barrier.id, barrier);
|
|
// Bound ephemeral metadata without discarding an in-flight barrier.
|
|
if (this.barriers.size > 100)
|
|
for (const [id, previous] of this.barriers)
|
|
if (previous.status !== 'pending' || previous.expiresAt <= this.now()) {
|
|
this.barriers.delete(id);
|
|
break;
|
|
}
|
|
return clone(barrier);
|
|
}
|
|
|
|
_barrier(id) {
|
|
const barrier = this.barriers.get(id);
|
|
if (!barrier) fail('BARRIER_NOT_FOUND', 'Save barrier does not exist');
|
|
if (barrier.status !== 'pending') fail('BARRIER_INVALID', barrier.reason || 'Save barrier is no longer pending');
|
|
if (this.now() >= barrier.expiresAt) {
|
|
barrier.status = 'expired';
|
|
fail('BARRIER_EXPIRED', 'Save barrier expired');
|
|
}
|
|
return barrier;
|
|
}
|
|
|
|
acknowledge(actorId, barrierId, clientId, payload) {
|
|
identifier(actorId, 'actor ID');
|
|
identifier(clientId, 'client ID');
|
|
const barrier = this._barrier(barrierId);
|
|
const participant = barrier.participants.find(item => item.clientId === clientId);
|
|
const client = this.clients.get(clientId);
|
|
if (!participant || !client || participant.actorId !== actorId || client.actorId !== actorId)
|
|
fail('CLIENT_OWNERSHIP', 'Only the participant may acknowledge its own saved documents');
|
|
const normalized = this._documents(payload);
|
|
if (normalized.dirty || client.dirty)
|
|
fail('DIRTY_DOCUMENTS', 'All documents must be saved and registered clean before acknowledgement');
|
|
if (
|
|
this._versions(normalized.documents) !== this._versions(participant.documents) ||
|
|
this._versions(client.documents) !== this._versions(participant.documents)
|
|
) {
|
|
barrier.status = 'invalid';
|
|
barrier.reason = 'Document version changed';
|
|
fail('VERSION_CHANGED', barrier.reason);
|
|
}
|
|
if (this.now() - client.lastSeen >= CLIENT_TTL_MS) fail('CLIENT_EXPIRED', 'Client heartbeat expired');
|
|
participant.acknowledged = true;
|
|
return clone(barrier);
|
|
}
|
|
|
|
_assertParticipants(barrier) {
|
|
for (const participant of barrier.participants) {
|
|
const client = this.clients.get(participant.clientId);
|
|
if (!participant.acknowledged) fail('ACK_REQUIRED', 'Every frozen participant must acknowledge saving');
|
|
if (!client || client.actorId !== participant.actorId || this.now() - client.lastSeen >= CLIENT_TTL_MS)
|
|
fail('CLIENT_EXPIRED', 'A participant disconnected or expired');
|
|
if (client.dirty) fail('DIRTY_DOCUMENTS', 'A participant has unsaved documents');
|
|
if (this._versions(client.documents) !== this._versions(participant.documents))
|
|
fail('VERSION_CHANGED', 'A participant changed document versions');
|
|
}
|
|
}
|
|
|
|
async commitBarrier(actorId, barrierId) {
|
|
identifier(actorId, 'actor ID');
|
|
const committed = this.commits.get(barrierId);
|
|
if (committed) {
|
|
if (committed.actorId !== actorId)
|
|
fail('BARRIER_OWNERSHIP', 'Only the barrier creator may retrieve its committed result');
|
|
return clone(committed);
|
|
}
|
|
const barrier = this._barrier(barrierId);
|
|
if (barrier.actorId !== actorId) fail('BARRIER_OWNERSHIP', 'Only the barrier creator may commit it');
|
|
this._assertParticipants(barrier);
|
|
return this._withLock(() => {
|
|
this._recover();
|
|
const recovered = this.commits.get(barrierId);
|
|
if (recovered) {
|
|
if (recovered.actorId !== actorId)
|
|
fail('BARRIER_OWNERSHIP', 'Only the barrier creator may retrieve its committed result');
|
|
barrier.status = 'committed';
|
|
barrier.snapshotId = recovered.id;
|
|
barrier.revision = recovered.revision;
|
|
return clone(recovered);
|
|
}
|
|
const disk = this._capture();
|
|
if (disk.digest !== barrier.diskDigest) {
|
|
barrier.status = 'invalid';
|
|
barrier.reason = 'Disk changed during save barrier';
|
|
fail('DISK_CHANGED', barrier.reason);
|
|
}
|
|
for (const [digest, bytes] of disk.blobs) {
|
|
const object = path.join(this.objectsDirectory, digest);
|
|
if (fs.existsSync(object)) {
|
|
if (!fs.lstatSync(object).isFile() || sha(fs.readFileSync(object)) !== digest)
|
|
fail('STATE_CORRUPT', 'Existing content-addressed object is invalid');
|
|
} else atomicFile(object, bytes, true);
|
|
}
|
|
// Re-read immediately before committing; saved snapshot content is never read from mutable source later.
|
|
if (this._capture(false).digest !== disk.digest) {
|
|
barrier.status = 'invalid';
|
|
barrier.reason = 'Disk changed while materializing snapshot';
|
|
fail('DISK_CHANGED', barrier.reason);
|
|
}
|
|
this._barrier(barrierId);
|
|
this._assertParticipants(barrier);
|
|
const body = {
|
|
schemaVersion: 1,
|
|
workspace: this.workspaceRoot,
|
|
revision: this.revision + 1,
|
|
previousId: this.latestSnapshot?.id ?? null,
|
|
digest: disk.digest,
|
|
files: disk.files,
|
|
createdAt: this.now(),
|
|
actorId,
|
|
barrierId,
|
|
};
|
|
const snapshot = { id: sha(JSON.stringify(body)), ...body };
|
|
atomicFile(
|
|
path.join(this.snapshotsDirectory, `${String(snapshot.revision).padStart(12, '0')}.json`),
|
|
JSON.stringify(snapshot),
|
|
true,
|
|
);
|
|
this.revision = snapshot.revision;
|
|
this.latestSnapshot = snapshot;
|
|
atomicFile(
|
|
path.join(this.stateDirectory, 'journal.json'),
|
|
JSON.stringify({
|
|
schemaVersion: 1,
|
|
workspace: this.workspaceRoot,
|
|
revision: this.revision,
|
|
latestId: snapshot.id,
|
|
}),
|
|
);
|
|
this.commits.set(barrierId, snapshot);
|
|
barrier.status = 'committed';
|
|
barrier.snapshotId = snapshot.id;
|
|
barrier.revision = snapshot.revision;
|
|
return clone(snapshot);
|
|
});
|
|
}
|
|
|
|
_liveDebugLease() {
|
|
if (this.debugLease && this.now() >= this.debugLease.expiresAt) this.debugLease = null;
|
|
return this.debugLease;
|
|
}
|
|
debugAcquire(actorId, token) {
|
|
identifier(actorId, 'actor ID');
|
|
const current = this._liveDebugLease();
|
|
if (current) {
|
|
if (current.actorId !== actorId || current.token !== token)
|
|
fail('DEBUG_BUSY', 'Debug control is held by a live lease');
|
|
current.expiresAt = this.now() + DEBUG_LEASE_MS;
|
|
return clone(current);
|
|
}
|
|
this.debugLease = { actorId, token: randomBytes(32).toString('hex'), expiresAt: this.now() + DEBUG_LEASE_MS };
|
|
return clone(this.debugLease);
|
|
}
|
|
assertDebugController(actorId, token) {
|
|
const lease = this._liveDebugLease();
|
|
if (!lease || lease.actorId !== actorId || typeof token !== 'string' || token !== lease.token)
|
|
fail('DEBUG_FORBIDDEN', 'An active debug controller lease is required');
|
|
return { actorId, expiresAt: lease.expiresAt };
|
|
}
|
|
debugTransfer(actorId, token, targetActorId) {
|
|
identifier(targetActorId, 'target actor ID');
|
|
this.assertDebugController(actorId, token);
|
|
if (!this._activeClients().some(client => client.actorId === targetActorId))
|
|
fail('CLIENT_REQUIRED', 'Target controller must have an active registered client');
|
|
this.debugLease = {
|
|
actorId: targetActorId,
|
|
token: randomBytes(32).toString('hex'),
|
|
expiresAt: this.now() + DEBUG_LEASE_MS,
|
|
};
|
|
return clone(this.debugLease);
|
|
}
|
|
debugRelease(actorId, token) {
|
|
this.assertDebugController(actorId, token);
|
|
this.debugLease = null;
|
|
return { released: true };
|
|
}
|
|
revoke(actorId) {
|
|
identifier(actorId, 'actor ID');
|
|
for (const [id, client] of this.clients) if (client.actorId === actorId) this.clients.delete(id);
|
|
for (const barrier of this.barriers.values())
|
|
if (
|
|
barrier.status === 'pending' &&
|
|
(barrier.actorId === actorId || barrier.participants.some(item => item.actorId === actorId))
|
|
) {
|
|
barrier.status = 'invalid';
|
|
barrier.reason = 'Participant access revoked';
|
|
}
|
|
if (this.debugLease?.actorId === actorId) this.debugLease = null;
|
|
return { revoked: true };
|
|
}
|
|
state() {
|
|
const lease = this._liveDebugLease();
|
|
return clone({
|
|
schemaVersion: 1,
|
|
revision: this.revision,
|
|
latestSnapshot: this.latestSnapshot,
|
|
clients: this._activeClients(),
|
|
barriers: [...this.barriers.values()].map(barrier => ({
|
|
...barrier,
|
|
status: barrier.status === 'pending' && this.now() >= barrier.expiresAt ? 'expired' : barrier.status,
|
|
})),
|
|
debugController: lease ? { actorId: lease.actorId, expiresAt: lease.expiresAt } : null,
|
|
});
|
|
}
|
|
inputState() {
|
|
const state = this.state();
|
|
const clients = state.clients
|
|
.map(({ actorId, clientId, documents, dirty }) => ({ actorId, clientId, documents, dirty }))
|
|
.sort((a, b) => a.clientId.localeCompare(b.clientId));
|
|
const snapshot = state.latestSnapshot;
|
|
return {
|
|
latestSnapshot: snapshot
|
|
? { id: snapshot.id, revision: snapshot.revision, digest: snapshot.digest, files: snapshot.files }
|
|
: null,
|
|
currentDiskDigest: this._capture(false).digest,
|
|
activityDigest: sha(JSON.stringify(clients)),
|
|
dirty: clients.some(client => client.dirty),
|
|
activeClients: clients.length,
|
|
};
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
Coordinator,
|
|
CoordinationError,
|
|
EXCLUDED: Object.freeze([...EXCLUDED]),
|
|
CLIENT_TTL_MS,
|
|
BARRIER_TTL_MS,
|
|
DEBUG_LEASE_MS,
|
|
DEFAULT_SNAPSHOT_LIMITS,
|
|
};
|