// A project's binding: which database a directory works on, kept in
/.constructive/project.json. Only the tools
// write it. It names no endpoint and holds no secret, so the file of a cloned project can't send a token anywhere.
import { randomBytes } from 'node:crypto';
import { mkdir, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
import type { Result } from './failure';
/** The binding's file, relative to the project directory. */
export const PROJECT_FILE = path.join('.constructive', 'project.json');
/** The binding is the person's own, for their account and backend, so git leaves it out (other .constructive files stay). */
const GITIGNORE = path.join('.constructive', '.gitignore');
/** The bound database. A host that binds a work directory of its own may know only its id. */
export type BoundDatabase = { id: string; name?: string; ownerId?: string };
/**
* The provision request provision_database stopped waiting on: the next call with the same name resumes it. Only a
* ticket of this backend and account is followed.
*/
export type PendingTicket = {
ticketId: string;
databaseName: string;
apiEndpoint: string;
userId: string;
/** Pending results recorded for this ticket so far. */
attempts: number;
};
/** An earlier binding or request, kept readable when a new one replaced it. */
export type ArchivedEntry = { archivedOn: string; backend?: string; database?: BoundDatabase; pending?: PendingTicket };
export type ProjectFile = {
/** The api endpoint of the backend the database is on. It is compared with the session's backend, never sent to. */
backend?: string;
database?: BoundDatabase;
/** The agent `setup agent` set this project up for. A command still acts as the person unless it says which agent. */
agent?: string;
pending?: PendingTicket;
/** Tickets the host told provisioning to stop following: a lookup by name skips them. */
abandoned?: string[];
archived?: ArchivedEntry[];
};
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/** The backend's own check on a database name, which is 3 to 63 characters long. */
export const DATABASE_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
export const isDatabaseName = (value: unknown): value is string =>
typeof value === 'string' && value.length >= 3 && value.length <= 63 && DATABASE_NAME_PATTERN.test(value);
export const isUuid = (value: unknown): value is string => typeof value === 'string' && UUID.test(value);
export const isEndpoint = (value: unknown): value is string => {
if (typeof value !== 'string') return false;
try {
return ['http:', 'https:'].includes(new URL(value).protocol);
} catch {
return false;
}
};
const isObject = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value);
/** The keys of a parsed file whose value is not of its form; such a file is never used, and its values never shown. */
function invalidKeys(file: Record): string[] {
const invalid: string[] = [];
const check = (key: string, ok: boolean) => {
if (!ok) invalid.push(key);
};
if (file.backend !== undefined) check('backend', isEndpoint(file.backend));
if (file.database !== undefined) {
const database = file.database;
check('database', isObject(database));
if (isObject(database)) {
check('database.id', isUuid(database.id));
if (database.name !== undefined) check('database.name', isDatabaseName(database.name));
if (database.ownerId !== undefined) check('database.ownerId', isUuid(database.ownerId));
}
}
if (file.agent !== undefined) check('agent', typeof file.agent === 'string');
if (file.pending !== undefined) {
const pending = file.pending;
check('pending', isObject(pending));
if (isObject(pending)) {
check('pending.ticketId', isUuid(pending.ticketId));
check('pending.databaseName', isDatabaseName(pending.databaseName));
check('pending.apiEndpoint', isEndpoint(pending.apiEndpoint));
check('pending.userId', isUuid(pending.userId));
check('pending.attempts', Number.isInteger(pending.attempts) && (pending.attempts as number) >= 0);
}
}
if (file.abandoned !== undefined) check('abandoned', Array.isArray(file.abandoned) && file.abandoned.every(isUuid));
if (file.archived !== undefined) check('archived', Array.isArray(file.archived) && file.archived.every(isObject));
return invalid;
}
/**
* The binding of `cwd`: null when the directory has none, a failure when the file is not JSON or a value is not of its
* form. A cloned project's file is not the person's text, so a value that fails its check is never used, sent or shown.
*/
export async function readProjectFile(cwd: string): Promise> {
let text: string;
try {
text = await readFile(path.join(cwd, PROJECT_FILE), 'utf8');
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { kind: 'ok', value: null };
return { kind: 'failed', failure: { code: 'missing-credentials', message: `${PROJECT_FILE} could not be read (${(err as Error).message}).` } };
}
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
parsed = undefined;
}
if (!isObject(parsed)) {
return {
kind: 'failed',
failure: {
code: 'missing-credentials',
message: `${PROJECT_FILE} is not a JSON object, so this directory's binding can't be read.`,
hint: 'Remove the file and bind the directory again (the person approves it).',
},
};
}
const invalid = invalidKeys(parsed);
if (invalid.length) {
return {
kind: 'failed',
failure: {
code: 'missing-credentials',
message: `${PROJECT_FILE} has values that are not of their form (${invalid.join(', ')}), so none of it is used.`,
hint: 'Remove the file and bind the directory again (the person approves it).',
},
};
}
return { kind: 'ok', value: parsed as ProjectFile };
}
/**
* Change the binding of `cwd` from its current content, read right before the write, so a change another tool or the
* person made while this call waited on the backend is kept. The write replaces the file in one step. The first write
* also tells git to leave the file out. A file that can't be read is left as it is, and the edit throws, as it does
* when .constructive links outside the project.
*/
export async function updateProjectFile(cwd: string, edit: (file: ProjectFile) => ProjectFile): Promise {
const current = await readProjectFile(cwd);
if (current.kind === 'failed') throw new Error(current.failure.message);
const file = path.join(cwd, PROJECT_FILE);
await mkdir(path.dirname(file), { recursive: true });
const inside = path.relative(await realpath(cwd), await realpath(path.dirname(file)));
if (inside.startsWith('..') || path.isAbsolute(inside)) throw new Error(`${PROJECT_FILE} was not written: .constructive links outside the project.`);
if (current.value === null) await writeFile(path.join(cwd, GITIGNORE), 'project.json\n', { flag: 'wx' }).catch((): void => undefined);
const temporary = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
try {
await writeFile(temporary, `${JSON.stringify(edit(current.value ?? {}), null, 2)}\n`, { flag: 'wx' });
await rename(temporary, file);
} catch (err) {
await rm(temporary, { force: true });
throw err;
}
}
/** The newest abandoned ids kept; older ones are long finished or failed. */
const MAX_ABANDONED = 10;
const without = (file: ProjectFile, key: K): ProjectFile => {
const rest = { ...file };
delete rest[key];
return rest;
};
export const recordPendingTicket = (file: ProjectFile, ticket: PendingTicket): ProjectFile => ({ ...file, pending: ticket });
export const clearPendingTicket = (file: ProjectFile): ProjectFile => without(file, 'pending');
/** Keep the recorded request readable in the archive, and record no request. */
export const archivePendingTicket = (file: ProjectFile, archivedOn: string): ProjectFile =>
file.pending ? { ...without(file, 'pending'), archived: [...(file.archived ?? []), { archivedOn, pending: file.pending }] } : file;
export const abandonedTickets = (file: ProjectFile): Set => new Set(file.abandoned ?? []);
/** Add ticket ids to the abandoned list. */
export const recordAbandoned = (file: ProjectFile, ticketIds: readonly string[]): ProjectFile => ({
...file,
abandoned: [...new Set([...(file.abandoned ?? []), ...ticketIds])].slice(-MAX_ABANDONED),
});
/**
* Bind the directory to `database` on `backend`, with no recorded request. A binding it replaces is kept readable in
* the archive.
*/
export function bindProject(file: ProjectFile, binding: { database: BoundDatabase; backend: string; archivedOn: string }): ProjectFile {
const replaced = file.database && file.database.id !== binding.database.id;
const archived = replaced ? [...(file.archived ?? []), { archivedOn: binding.archivedOn, backend: file.backend, database: file.database }] : file.archived;
return { ...without(file, 'pending'), backend: binding.backend, database: binding.database, ...(archived ? { archived } : {}) };
}