110 lines
6.1 KiB
JavaScript
110 lines
6.1 KiB
JavaScript
// Fixed client executed inside the released core; protected input arrives only through stdin.
|
|
const stopped = (code, runId) => Object.assign(new Error(code), { code, ...(runId ? { runId } : {}) });
|
|
const jsonResponse = async (response, code) => {
|
|
if (!response.ok) throw stopped(code);
|
|
return response.json();
|
|
};
|
|
|
|
export async function prepareWorkspace(request, workspaceId, revision, pause = () => new Promise(resolve => setTimeout(resolve, 2000))) {
|
|
const databases = await jsonResponse(await request("/catalog/databases"), "workspace_preparation_failed");
|
|
const database = databases.find(item => item.workspaceId === workspaceId);
|
|
if (!database || database.workspaceRevision?.commit !== revision) throw stopped("workspace_reconciliation_required");
|
|
if (database.binding.transport === "ssh_tunnel") throw stopped("session_transport_unsupported");
|
|
const runs = await jsonResponse(await request(`/catalog/databases/${database.id}/sync-runs`), "schema_sync_failed");
|
|
let active = runs.find(run => ["queued", "running", "awaiting_confirmation", "applying"].includes(run.state));
|
|
const waitForSync = async run => {
|
|
for (let attempt = 0; attempt < 900; attempt++) {
|
|
if (run.state === "awaiting_confirmation") throw stopped("schema_review_required", run.id);
|
|
if (run.state === "succeeded") return;
|
|
if (!["queued", "running", "applying"].includes(run.state)) throw stopped("schema_sync_failed", run.id);
|
|
await pause();
|
|
run = await jsonResponse(await request(`/catalog/sync-runs/${run.id}`), "schema_sync_failed");
|
|
}
|
|
throw stopped("schema_sync_pending", run.id);
|
|
};
|
|
if (active) await waitForSync(active);
|
|
let current = active
|
|
? await jsonResponse(await request(`/catalog/databases/${database.id}`), "schema_sync_failed") : database;
|
|
if (current.version !== database.version) throw stopped("workspace_reconciliation_required");
|
|
if (current.schemaSyncedVersion !== current.version) {
|
|
active = await jsonResponse(await request(`/catalog/databases/${database.id}/sync-runs`, {
|
|
version: database.version, scope: "all", tableIds: [],
|
|
}), "schema_sync_failed");
|
|
await waitForSync(active);
|
|
current = await jsonResponse(await request(`/catalog/databases/${database.id}`), "schema_sync_failed");
|
|
if (current.version !== database.version || current.schemaSyncedVersion !== current.version) throw stopped("workspace_reconciliation_required");
|
|
}
|
|
const path = `/workspaces/${encodeURIComponent(workspaceId)}/preprocessing`;
|
|
let state = await jsonResponse(await request(path), "preprocessing_failed");
|
|
let started = false;
|
|
for (let attempt = 0; attempt < 900; attempt++) {
|
|
if (state.state === "ready") return { workspaceId, state: "ready" };
|
|
if (state.state === "blocked") throw stopped("preprocessing_blocked");
|
|
if (["required", "failed"].includes(state.state) && !started) {
|
|
started = true;
|
|
await jsonResponse(await request(path, {}), "preprocessing_failed");
|
|
} else if (state.state !== "running") throw stopped("preprocessing_failed");
|
|
await pause();
|
|
state = await jsonResponse(await request(path), "preprocessing_failed");
|
|
}
|
|
throw stopped("preprocessing_pending");
|
|
}
|
|
|
|
const readinessCodes = new Set(["workspace_preparation_failed", "workspace_reconciliation_required", "session_transport_unsupported",
|
|
"schema_review_required", "schema_sync_failed", "schema_sync_pending", "preprocessing_failed", "preprocessing_blocked", "preprocessing_pending"]);
|
|
|
|
export async function importPreparedBindings(base = "http://core:8787", mode = "bindings") {
|
|
let cookie = "", csrf = "", origin = "", completed = 0, code = "authentication_required";
|
|
let workspaceId, runId;
|
|
const request = async (path, body) => fetch(base + path, {
|
|
method: body === undefined ? "GET" : "POST", redirect: "error", signal: AbortSignal.timeout(mode === "workspaces" ? 1800000 : 180000),
|
|
headers: { "content-type": "application/json", origin, ...(cookie ? { cookie } : {}), ...(csrf ? { "x-thothii-csrf": csrf } : {}) },
|
|
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
});
|
|
try {
|
|
let input = "";
|
|
for await (const chunk of process.stdin) { input += chunk; if (Buffer.byteLength(input) > 16 * 1024 * 1024) throw Error(); }
|
|
const prepared = JSON.parse(input); input = ""; origin = prepared.origin;
|
|
const login = await request("/auth/local/login", { username: prepared.username, password: prepared.password, remember: false });
|
|
prepared.password = "";
|
|
if (!login.ok) throw Error();
|
|
cookie = login.headers.get("set-cookie")?.split(";")[0] ?? "";
|
|
if (!cookie) throw Error();
|
|
const me = await request("/me"); if (!me.ok) throw Error();
|
|
csrf = (await me.json()).csrfToken; if (!csrf) throw Error();
|
|
code = "workspace_reconciliation_required";
|
|
const source = await request("/installation/workspace-source", prepared.source);
|
|
if (!source.ok) throw Error();
|
|
const { revision } = await source.json();
|
|
for (const entry of prepared.databases) {
|
|
if (mode === "workspaces") {
|
|
workspaceId = entry.configuration.workspaceId;
|
|
code = "workspace_preparation_failed";
|
|
await prepareWorkspace(request, workspaceId, revision);
|
|
completed++;
|
|
continue;
|
|
}
|
|
code = "binding_import_failed";
|
|
const response = await request("/installation/bindings", { ...entry, revision });
|
|
if (response.status === 409) code = "binding_reconciliation_required";
|
|
if (response.status === 422) code = "container_connection_failed";
|
|
if (!response.ok) throw Error();
|
|
const value = await response.json();
|
|
if (value.connectionStatus !== "reachable" || !["applied", "unchanged"].includes(value.status)) throw Error();
|
|
completed++;
|
|
}
|
|
workspaceId = undefined;
|
|
code = mode === "workspaces" ? "workspaces_prepared" : "bindings_ready";
|
|
} catch (error) {
|
|
if (readinessCodes.has(error?.code)) {
|
|
code = error.code;
|
|
if (/^[a-f0-9-]{36}$/.test(error.runId ?? "")) runId = error.runId;
|
|
}
|
|
process.exitCode = 1;
|
|
}
|
|
finally {
|
|
if (cookie && csrf) { try { await request("/auth/logout", {}); } catch {} }
|
|
process.stdout.write(JSON.stringify({ ok: ["bindings_ready", "workspaces_prepared"].includes(code), code, completed, workspaceId, runId }));
|
|
}
|
|
}
|