// 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 importBinding(request, entry, revision, pause = () => new Promise(resolve => setTimeout(resolve, 2000))) { for (let attempt = 0; attempt < 300; attempt++) { const response = await request("/installation/bindings", { ...entry, revision }); if (response.status === 409) { const value = await response.json(); if (value.code !== "installation_operation_pending") throw stopped("binding_reconciliation_required"); const databases = await jsonResponse(await request("/catalog/databases"), "binding_import_failed"); const active = databases.find(item => item.workspaceId === entry.configuration.workspaceId)?.activeSyncRun; if (active?.state === "awaiting_confirmation") throw stopped("schema_review_required", active.id); await pause(); continue; } if (response.status === 422) throw stopped("container_connection_failed"); const value = await jsonResponse(response, "binding_import_failed"); if (value.connectionStatus !== "reachable" || !["applied", "unchanged"].includes(value.status)) throw stopped("binding_import_failed"); return; } throw stopped("binding_operation_pending"); } 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 interrupted = runs.find(run => ["interrupted", "failed"].includes(run.state) && run.requestedDatabaseVersion === database.version && run.scope === "all" && (database.schemaSyncedVersion !== database.version || run.phase === "memory_cleanup")); if (!active && interrupted) { active = await jsonResponse(await request(`/catalog/sync-runs/${interrupted.id}/retry`, {}), "schema_sync_failed"); } 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 (state.state === "running" && attempt % 15 === 0) { const response = await request(path, { recoverInterrupted: true }); if (response.status !== 409) await jsonResponse(response, "preprocessing_failed"); started = true; } else 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", "binding_reconciliation_required", "container_connection_failed", "binding_import_failed", "binding_operation_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) { workspaceId = entry.configuration.workspaceId; if (mode === "workspaces") { workspaceId = entry.configuration.workspaceId; code = "workspace_preparation_failed"; await prepareWorkspace(request, workspaceId, revision); completed++; continue; } code = "binding_import_failed"; await importBinding(request, entry, revision); 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 })); } }