@sema-agent/core
Version:
Stateless, task-oriented AI agent core
119 lines (118 loc) • 6.73 kB
JavaScript
import { existsSync } from "node:fs";
import { renameSync } from "./descriptor-seat.js";
import { join } from "node:path";
import { writerOf } from "../../core/permission-rule-store.js";
import { readRecordedRuleOwner, ruleOwnerText, sameRuleOwner } from "../../core/rule-owner.js";
import { holdsUnpairedSurrogate, judgePrincipalName, unpairedSurrogateRefusal } from "../../core/principal-name.js";
import { createPermissionRuleStoreProvider } from "../../core/permission-rule-provider.js";
import { syncPermissionRules } from "../../core/permission-rule-sync.js";
import { thrownText } from "../../core/thrown-value.js";
import { optionKeys, receiveMembers } from "../../core/own-property-receipt.js";
import { FileStoreLockError, rewordedLockRefusal } from "./fs-atomic.js";
import { lockRefusalClause } from "./lock-reading.js";
import { FileDurableRulePartitionProvider, LOCAL_OWNER_FILE, principalRuleFileName, readRuleAdoptionFile, writeRuleAdoptionFile, } from "./permission-rule-store.js";
const ADOPT_OPTION_KEYS = optionKeys()({ dir: 0, from: 0, toPrincipal: 0, transport: 0, now: 0, onError: 0 });
export async function adoptFilePermissionRuleStore(opts) {
return adoptRuleBucket(opts, "caller");
}
export async function adoptRuleBucket(opts, source) {
const o = receiveMembers(opts, { subject: "adoptFilePermissionRuleStore options", unit: "option", moment: "at adoptFilePermissionRuleStore" }, ADOPT_OPTION_KEYS);
const target = judgePrincipalName(o.toPrincipal);
if (!target.ok) {
throw new Error(`adoptFilePermissionRuleStore requires the adopting principal, a principal name — adoption is the act of giving this bucket an identity — got ${target.fault}`);
}
const from = readRecordedRuleOwner(o.from);
if (from === undefined) {
throw new Error("adoptFilePermissionRuleStore requires a source owner — a principal owner whose principal is a principal name, or the local owner");
}
if (from.kind === "principal" && from.principal === o.toPrincipal) {
throw new Error(`the bucket already belongs to "${o.toPrincipal}" — there is nothing to adopt`);
}
const sourceFile = join(o.dir, from.kind === "local-owner" ? LOCAL_OWNER_FILE : principalRuleFileName(from.principal));
const targetFile = join(o.dir, principalRuleFileName(o.toPrincipal));
const existing = readRuleAdoptionFile(o.dir);
if (existing !== undefined) {
if ("adopted" in existing) {
if (existing.adopted.toPrincipal === o.toPrincipal && sameRuleOwner(existing.adopted.from, from))
return { status: "adopted" };
throw new Error(`this directory already carries a completed adoption (${ruleOwnerText(existing.adopted.from)} → "${existing.adopted.toPrincipal}") — a second adoption of the same directory is not a shape this helper supports`);
}
if (existing.marker.toPrincipal !== o.toPrincipal || !sameRuleOwner(existing.marker.from, from)) {
throw new Error(`an adoption toward "${existing.marker.toPrincipal}" is already in flight in this directory — refusing to start a different one (resume the original, or repair the marker by hand)`);
}
}
else if (source === "caller" && from.kind === "principal" && holdsUnpairedSurrogate(from.principal)) {
throw new Error(unpairedSurrogateRefusal("adoptFilePermissionRuleStore: the source principal (from.principal)"));
}
else if (existsSync(targetFile)) {
throw new Error(`the target bucket for "${o.toPrincipal}" already exists — merging two existing buckets goes through an explicit sync join, not a rename`);
}
const provider = new FileDurableRulePartitionProvider(o.dir, o.onError);
try {
let lockProbe;
try {
lockProbe = writerOf(provider.forPrincipal(o.toPrincipal));
}
catch (err) {
if (!(err instanceof FileStoreLockError))
throw err;
throw rewordedLockRefusal(err, `the adoption cannot take the permission-rule writer lock (${err.code}): ${lockRefusalClause(err, `the lock ${err.lockPath}`)}; then run the adoption again`, err.lockPath);
}
if (lockProbe === undefined)
throw new Error("the target store refused a write face");
let phase = existing !== undefined && "marker" in existing ? existing.marker.phase : 2;
if (existing === undefined) {
writeRuleAdoptionFile(o.dir, marker(from, o.toPrincipal, 2));
phase = 2;
}
if (phase < 3) {
const sourcePresent = existsSync(sourceFile);
const targetPresent = existsSync(targetFile);
if (sourcePresent && targetPresent) {
throw new Error(`both the source and the target bucket exist — merging two existing buckets goes through an explicit sync join, not a rename; the adoption marker is left in place for inspection`);
}
if (sourcePresent)
renameSync(sourceFile, targetFile);
writeRuleAdoptionFile(o.dir, marker(from, o.toPrincipal, 3));
phase = 3;
}
if (phase < 4) {
writeRuleAdoptionFile(o.dir, marker(from, o.toPrincipal, 4));
phase = 4;
}
let syncResult;
if (phase < 5) {
try {
syncResult = await syncPermissionRules({
provider: createPermissionRuleStoreProvider({ durable: provider }),
principal: o.toPrincipal,
transport: o.transport,
...(o.now !== undefined ? { now: o.now } : {}),
});
}
catch (err) {
return { status: "stalled", phase: 4, error: `the first sync round failed: ${thrownText(err)}` };
}
if (!syncResult.ok) {
return {
status: "stalled",
phase: 4,
error: `the first sync round did not land clean (${(syncResult.warnings ?? []).join("; ") || `${syncResult.dropped.length} drop(s)`}) — resume when the endpoint is healthy`,
};
}
writeRuleAdoptionFile(o.dir, marker(from, o.toPrincipal, 5));
phase = 5;
}
writeRuleAdoptionFile(o.dir, {
schemaVersion: 1,
adopted: { from, toPrincipal: o.toPrincipal, atMs: (o.now ?? Date.now)() },
});
return { status: "adopted", ...(syncResult !== undefined ? { syncResult } : {}) };
}
finally {
provider.dispose();
}
}
function marker(from, toPrincipal, phase) {
return { schemaVersion: 1, marker: { from, toPrincipal, phase } };
}