165 lines
6.4 KiB
TypeScript
165 lines
6.4 KiB
TypeScript
import { spawn } from "node:child_process";
|
|
import { randomUUID } from "node:crypto";
|
|
import { promises as fs } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { environment } from "@raycast/api";
|
|
import { getPreferences } from "../preferences";
|
|
import { canonicalProjectPath, projectDataRoot } from "./velum-project";
|
|
import type { applyProject, prepareProject, Preview, ProjectOutput } from "./project-work";
|
|
|
|
export type AnalysisInput = {
|
|
root: string;
|
|
files: Parameters<typeof prepareProject>[2];
|
|
rules: Parameters<typeof prepareProject>[3];
|
|
whitelist: Parameters<typeof prepareProject>[4];
|
|
entityTypes: Parameters<typeof prepareProject>[5];
|
|
skipped: Parameters<typeof prepareProject>[6];
|
|
reanalyzeUnchanged: boolean;
|
|
imagePolicy: Parameters<typeof prepareProject>[9];
|
|
fileSelectionChanged: boolean;
|
|
};
|
|
export type Decision = Parameters<typeof applyProject>[5];
|
|
export type JobPhase = "analysis" | "apply";
|
|
export type ProjectJobState =
|
|
| { phase: JobPhase; pid: number; message: string }
|
|
| { phase: "review" }
|
|
| { phase: "complete"; output?: ProjectOutput; reused?: number }
|
|
| { phase: "error"; message: string };
|
|
|
|
export function projectJobDirectory(root: string, support = environment.supportPath): string {
|
|
return join(projectDataRoot(root, support), "active-job");
|
|
}
|
|
|
|
export async function writeJobJson(directory: string, file: string, value: unknown): Promise<void> {
|
|
const target = join(directory, file);
|
|
const temporary = target + "." + randomUUID();
|
|
try {
|
|
await fs.writeFile(temporary, JSON.stringify(value), { flag: "wx", mode: 0o600 });
|
|
await fs.rename(temporary, target);
|
|
} finally {
|
|
await fs.rm(temporary, { force: true });
|
|
}
|
|
}
|
|
|
|
export async function readJobJson<T>(directory: string, file: string): Promise<T> {
|
|
return JSON.parse(await fs.readFile(join(directory, file), "utf8")) as T;
|
|
}
|
|
|
|
export async function readProjectJob(root: string): Promise<ProjectJobState | undefined> {
|
|
const directory = projectJobDirectory(root);
|
|
let state: ProjectJobState;
|
|
try {
|
|
state = await readJobJson<ProjectJobState>(directory, "state.json");
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
const info = await fs.stat(directory).catch((statError: NodeJS.ErrnoException) => {
|
|
if (statError.code !== "ENOENT") throw statError;
|
|
});
|
|
if (info && Date.now() - info.mtimeMs > 10_000) {
|
|
return { phase: "error", message: "Der Projektauftrag wurde beim Start unterbrochen." };
|
|
}
|
|
return undefined;
|
|
}
|
|
if (state.phase === "analysis" || state.phase === "apply") {
|
|
try {
|
|
process.kill(state.pid, 0);
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
|
|
// The worker writes its terminal state before exiting.
|
|
const last = await readJobJson<ProjectJobState>(directory, "state.json");
|
|
if (last.phase !== "analysis" && last.phase !== "apply") return last;
|
|
return { phase: "error", message: "Der lokale Hintergrundprozess wurde beendet." };
|
|
}
|
|
}
|
|
return state;
|
|
}
|
|
|
|
export async function loadProjectReview(root: string): Promise<{ input: AnalysisInput; preview: Preview }> {
|
|
const directory = projectJobDirectory(root);
|
|
const [input, preview] = await Promise.all([
|
|
readJobJson<AnalysisInput>(directory, "input.json"),
|
|
readJobJson<Preview>(directory, "preview.json"),
|
|
]);
|
|
return { input, preview };
|
|
}
|
|
|
|
async function launch(directory: string, phase: JobPhase): Promise<void> {
|
|
const config = JSON.stringify({
|
|
assets: environment.assetsPath,
|
|
support: environment.supportPath,
|
|
preferences: getPreferences(),
|
|
});
|
|
const child = spawn(process.execPath, [join(environment.assetsPath, "velum-project-worker.cjs"), directory, phase], {
|
|
detached: true,
|
|
stdio: ["pipe", "ignore", "ignore"],
|
|
cwd: directory,
|
|
});
|
|
// Register a handler immediately, before doing any asynchronous filesystem IO.
|
|
const started = new Promise<void>((resolve, reject) => {
|
|
child.once("error", reject);
|
|
child.once("spawn", resolve);
|
|
});
|
|
child.stdin.on("error", () => undefined);
|
|
try {
|
|
await started;
|
|
await writeJobJson(directory, "state.json", { phase, pid: child.pid,
|
|
message: phase === "analysis" ? "Analyse startet" : "Ausgabe wird vorbereitet" });
|
|
// Only the pipe receives credentials. Job metadata, logs and arguments are
|
|
// safe to retain even after the window or worker closes.
|
|
await new Promise<void>((resolve, reject) => {
|
|
child.stdin.once("error", reject);
|
|
child.stdin.end(config, resolve);
|
|
});
|
|
} catch (error) {
|
|
child.stdin.destroy();
|
|
child.kill();
|
|
throw error;
|
|
} finally {
|
|
child.unref();
|
|
}
|
|
}
|
|
|
|
export async function startProjectAnalysis(input: AnalysisInput): Promise<void> {
|
|
const root = canonicalProjectPath(input.root);
|
|
const directory = projectJobDirectory(root);
|
|
await fs.mkdir(projectDataRoot(root), { recursive: true, mode: 0o700 });
|
|
await fs.mkdir(directory, { mode: 0o700 });
|
|
try {
|
|
await writeJobJson(directory, "input.json", { ...input, root });
|
|
await launch(directory, "analysis");
|
|
} catch (error) {
|
|
await writeJobJson(directory, "state.json", { phase: "error",
|
|
message: "Der lokale Hintergrundprozess konnte nicht gestartet werden." });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function startProjectApply(root: string, decision: Decision): Promise<void> {
|
|
const directory = projectJobDirectory(root);
|
|
if ((await readProjectJob(root))?.phase !== "review") {
|
|
throw new Error("Dieser Projektauftrag steht nicht mehr zur Prüfung bereit.");
|
|
}
|
|
// Exclusive creation prevents two windows from publishing the same review.
|
|
await fs.writeFile(join(directory, "decision.json"), JSON.stringify(decision), { flag: "wx", mode: 0o600 });
|
|
try {
|
|
await launch(directory, "apply");
|
|
} catch (error) {
|
|
await fs.rm(join(directory, "decision.json"), { force: true });
|
|
await writeJobJson(directory, "state.json", { phase: "review" });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function discardProjectJob(root: string): Promise<void> {
|
|
const state = await readProjectJob(root);
|
|
if (!state || state.phase === "analysis" || state.phase === "apply") {
|
|
throw new Error("Der Hintergrundauftrag läuft noch.");
|
|
}
|
|
const directory = projectJobDirectory(root);
|
|
if (state.phase === "review") {
|
|
// Mutual exclusion with the review's Apply action.
|
|
await fs.writeFile(join(directory, "decision.json"), "", { flag: "wx", mode: 0o600 });
|
|
}
|
|
await fs.rm(directory, { recursive: true, force: true });
|
|
}
|