feat: prepare installation workspaces through existing readiness services
This commit is contained in:
@@ -92,6 +92,9 @@ func installationApplyCommand(ctx context.Context, installationPath string, args
|
||||
result, err := installapply.Run(ctx, installapply.Request{PlanPath: planPath, InstallationPath: installationPath}, runner, check)
|
||||
write(result)
|
||||
if err != nil {
|
||||
if result.WorkspacePreparation != nil && result.WorkspacePreparation.Code == "schema_review_required" {
|
||||
return 3
|
||||
}
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
|
||||
@@ -112,6 +112,7 @@ container) :;;
|
||||
*) exit 1;;`, 1)
|
||||
script = strings.Replace(script, "else printf '%s\\n'", `elif case "$*" in *' ps '*) true;; *) false;; esac; then printf '%s\n' '[{"Service":"core","State":"running","Health":"healthy"},{"Service":"frontend","State":"running","Health":"healthy"},{"Service":"qdrant","State":"running","Health":"healthy"},{"Service":"embedding","State":"running","Health":"healthy"},{"Service":"embedding-model-init","State":"exited","ExitCode":0}]'; else printf '%s\n'`, 1)
|
||||
script = strings.Replace(script, "else printf '%s\\n'", `elif case "$*" in *'protected input arrives only through stdin'*) true;; *) false;; esac; then while IFS= read -r line; do :; done; printf '%s\n' '{"ok":true,"code":"bindings_ready","completed":1}'; else printf '%s\n'`, 1)
|
||||
script = strings.Replace(script, "elif case", `elif case "$*" in *"await importPreparedBindings(undefined, 'workspaces');"*) true;; *) false;; esac; then while IFS= read -r line; do :; done; printf '%s\n' '{"ok":true,"code":"workspaces_prepared","completed":1}'; elif case "$*" in *'/app/backend/dist/operator-command.js'*) true;; *) false;; esac; then printf '%s\n' '{"ready":true}'; elif case`, 1)
|
||||
write(filepath.Join(root, "docker"), []byte(script))
|
||||
_ = os.Chmod(filepath.Join(root, "docker"), 0o700)
|
||||
planPath := filepath.Join(installation, "plan.json")
|
||||
@@ -143,7 +144,7 @@ container) :;;
|
||||
PlatformReady bool `json:"platform_ready"`
|
||||
WorkspaceReady bool `json:"workspace_ready"`
|
||||
}
|
||||
if code != 0 || json.Unmarshal([]byte(text), &result) != nil || !result.PlatformReady || result.WorkspaceReady || strings.Contains(text, "PRIVATE_") {
|
||||
if code != 0 || json.Unmarshal([]byte(text), &result) != nil || !result.PlatformReady || !result.WorkspaceReady || strings.Contains(text, "PRIVATE_") {
|
||||
t.Fatalf("noninteractive apply attempt %d: %s", attempt, text)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,11 +24,14 @@ import (
|
||||
var bindingClientModule string
|
||||
|
||||
var bindingClient = bindingClientModule + "\nawait importPreparedBindings();\n"
|
||||
var readinessClient = bindingClientModule + "\nawait importPreparedBindings(undefined, 'workspaces');\n"
|
||||
|
||||
type BindingReport struct {
|
||||
OK bool `json:"ok"`
|
||||
Code string `json:"code"`
|
||||
Completed int `json:"completed"`
|
||||
OK bool `json:"ok"`
|
||||
Code string `json:"code"`
|
||||
Completed int `json:"completed"`
|
||||
WorkspaceID string `json:"workspaceId,omitempty"`
|
||||
RunID string `json:"runId,omitempty"`
|
||||
}
|
||||
|
||||
// Secrets travel only over the child pipe; they never enter argv, generated assets or journals.
|
||||
@@ -122,19 +125,29 @@ func bindingPayload(plan preflight.Plan) ([]byte, error) {
|
||||
}
|
||||
|
||||
func importBindings(ctx context.Context, plan preflight.Plan, runner compose.Runner, payload []byte) (BindingReport, error) {
|
||||
bound, cancel := context.WithTimeout(ctx, 15*time.Minute)
|
||||
return runPreparedClient(ctx, plan, runner, payload, false)
|
||||
}
|
||||
|
||||
func runPreparedClient(ctx context.Context, plan preflight.Plan, runner compose.Runner, payload []byte, prepare bool) (BindingReport, error) {
|
||||
client, success, timeout := bindingClient, "bindings_ready", 15*time.Minute
|
||||
codes := []string{"bindings_ready", "authentication_required", "workspace_reconciliation_required", "binding_reconciliation_required", "container_connection_failed", "binding_import_failed"}
|
||||
if prepare {
|
||||
client, success, timeout = readinessClient, "workspaces_prepared", 60*time.Minute
|
||||
codes = append(codes, "workspaces_prepared", "workspace_preparation_failed", "session_transport_unsupported", "schema_review_required", "schema_sync_failed", "schema_sync_pending", "preprocessing_failed", "preprocessing_blocked", "preprocessing_pending")
|
||||
}
|
||||
bound, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
name, err := compose.NewOneShotContainerName(plan.Installation.ProjectName() + "-bindings")
|
||||
if err != nil {
|
||||
return BindingReport{Code: "binding_import_failed"}, err
|
||||
}
|
||||
result, err := runner.Run(bound, plan.Installation.ComposeArgs("run", "--rm", "-T", "--no-deps", "--pull", "never", "--name", name,
|
||||
"--entrypoint", "node", "core", "--input-type=module", "-e", bindingClient), bytes.NewReader(payload))
|
||||
"--entrypoint", "node", "core", "--input-type=module", "-e", client), bytes.NewReader(payload))
|
||||
var report BindingReport
|
||||
if json.Unmarshal([]byte(result.Stdout), &report) != nil || !slices.Contains([]string{"bindings_ready", "authentication_required", "workspace_reconciliation_required", "binding_reconciliation_required", "container_connection_failed", "binding_import_failed"}, report.Code) {
|
||||
if json.Unmarshal([]byte(result.Stdout), &report) != nil || !slices.Contains(codes, report.Code) {
|
||||
return BindingReport{Code: "binding_import_failed"}, errors.New("Binding import did not return a valid report")
|
||||
}
|
||||
if err != nil || result.ExitCode != 0 || !report.OK || report.Code != "bindings_ready" || report.Completed < 1 {
|
||||
if err != nil || result.ExitCode != 0 || !report.OK || report.Code != success || report.Completed < 1 {
|
||||
return report, errors.New("Binding import stopped; reconcile the prepared documents with application administration and repeat planning")
|
||||
}
|
||||
return report, nil
|
||||
|
||||
@@ -1,8 +1,63 @@
|
||||
// Fixed client executed inside the released core; protected input arrives only through stdin.
|
||||
export async function importPreparedBindings(base = "http://core:8787") {
|
||||
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(180000),
|
||||
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) }),
|
||||
});
|
||||
@@ -22,6 +77,13 @@ try {
|
||||
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";
|
||||
@@ -31,10 +93,17 @@ try {
|
||||
if (value.connectionStatus !== "reachable" || !["applied", "unchanged"].includes(value.status)) throw Error();
|
||||
completed++;
|
||||
}
|
||||
code = "bindings_ready";
|
||||
} catch { process.exitCode = 1; }
|
||||
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: code === "bindings_ready", code, completed }));
|
||||
process.stdout.write(JSON.stringify({ ok: ["bindings_ready", "workspaces_prepared"].includes(code), code, completed, workspaceId, runId }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,15 +24,22 @@ import (
|
||||
)
|
||||
|
||||
type Request struct{ PlanPath, InstallationPath string }
|
||||
type RuntimeCheck struct {
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
type Result struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
PlatformReady bool `json:"platform_ready"`
|
||||
WorkspaceReady bool `json:"workspace_ready"`
|
||||
BindingsReady bool `json:"bindings_ready"`
|
||||
BindingImport *BindingReport `json:"binding_import,omitempty"`
|
||||
Stage string `json:"stage"`
|
||||
Action string `json:"action"`
|
||||
Journal string `json:"journal,omitempty"`
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
PlatformReady bool `json:"platform_ready"`
|
||||
WorkspaceReady bool `json:"workspace_ready"`
|
||||
BindingsReady bool `json:"bindings_ready"`
|
||||
BindingImport *BindingReport `json:"binding_import,omitempty"`
|
||||
WorkspacePreparation *BindingReport `json:"workspace_preparation,omitempty"`
|
||||
RuntimeChecks []RuntimeCheck `json:"runtime_checks"`
|
||||
FunctionalAcceptance bool `json:"functional_acceptance"`
|
||||
Stage string `json:"stage"`
|
||||
Action string `json:"action"`
|
||||
Journal string `json:"journal,omitempty"`
|
||||
}
|
||||
type journal struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
@@ -49,6 +56,9 @@ type Check func(context.Context, preflight.Plan) error
|
||||
|
||||
func Run(ctx context.Context, request Request, runner compose.Runner, check Check) (result Result, err error) {
|
||||
result = Result{SchemaVersion: 1, Stage: "plan", Action: "Produce a current plan from complete prepared documents."}
|
||||
for _, id := range []string{"workspace-test", "workflow-doctor", "pi-test"} {
|
||||
result.RuntimeChecks = append(result.RuntimeChecks, RuntimeCheck{ID: id, Status: "pending"})
|
||||
}
|
||||
fail := func(stage, action string) (Result, error) {
|
||||
result.Stage = stage
|
||||
result.Action = action
|
||||
@@ -208,20 +218,61 @@ func Run(ctx context.Context, request Request, runner compose.Runner, check Chec
|
||||
result.BindingsReady = err == nil
|
||||
return err
|
||||
}},
|
||||
{"workspace-preparation", func() error {
|
||||
report, err := runPreparedClient(ctx, plan, runner, payload, true)
|
||||
result.WorkspacePreparation = &report
|
||||
return err
|
||||
}},
|
||||
}
|
||||
for index, check := range result.RuntimeChecks {
|
||||
action := check.ID
|
||||
stages = append(stages, struct {
|
||||
name string
|
||||
run func() error
|
||||
}{action, func() error {
|
||||
err := runtimeDiagnostic(ctx, plan, runner, action)
|
||||
result.RuntimeChecks[index].Status = "passed"
|
||||
if err != nil {
|
||||
result.RuntimeChecks[index].Status = "failed"
|
||||
}
|
||||
return err
|
||||
}})
|
||||
}
|
||||
// Reconcile each idempotent stage against Docker/migration authority on every retry.
|
||||
// A journal entry alone is never proof that a container or migration still exists.
|
||||
for _, stage := range stages {
|
||||
if err := operation(stage.name, stage.run); err != nil {
|
||||
if result.WorkspacePreparation != nil && result.WorkspacePreparation.Code == "schema_review_required" {
|
||||
return fail(stage.name, "Review the pending schema synchronization in application Administration, then repeat apply. No destructive change was confirmed by the installer.")
|
||||
}
|
||||
return fail(stage.name, err.Error())
|
||||
}
|
||||
}
|
||||
result.PlatformReady = true
|
||||
result.Stage = "bindings-ready"
|
||||
result.Action = "Platform and prepared database bindings are ready. Complete workspace readiness before a human-reviewed question."
|
||||
result.WorkspaceReady = true
|
||||
result.Stage = "workspace-ready"
|
||||
result.Action = "Platform, workspace preparation and runtime checks passed. Open the application for the manual human-reviewed question."
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func runtimeDiagnostic(ctx context.Context, plan preflight.Plan, runner compose.Runner, action string) error {
|
||||
bound, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
defer cancel()
|
||||
name, err := compose.NewOneShotContainerName(plan.Installation.ProjectName() + "-readiness")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value, err := runner.Run(bound, plan.Installation.ComposeArgs("run", "--rm", "-T", "--no-deps", "--pull", "never", "--name", name,
|
||||
"--entrypoint", "node", "core", "/app/backend/dist/operator-command.js", action), nil)
|
||||
var report struct {
|
||||
Ready bool `json:"ready"`
|
||||
}
|
||||
if err != nil || value.ExitCode != 0 || json.Unmarshal([]byte(value.Stdout), &report) != nil || !report.Ready {
|
||||
return errors.New("Runtime diagnostic failed; inspect application diagnostics and correct the prepared configuration")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func installAssets(installation config.Installation, plan preflight.Plan) error {
|
||||
names := make([]string, 0, len(plan.Release.Files))
|
||||
for name := range plan.Release.Files {
|
||||
|
||||
@@ -86,7 +86,7 @@ type dockerFixture struct {
|
||||
|
||||
func (r *dockerFixture) Run(_ context.Context, args []string, input io.Reader) (compose.Result, error) {
|
||||
if input != nil {
|
||||
if args[len(args)-1] != bindingClient {
|
||||
if args[len(args)-1] != bindingClient && args[len(args)-1] != readinessClient {
|
||||
return compose.Result{}, fmt.Errorf("unexpected interactive input")
|
||||
}
|
||||
command := strings.Join(args, " ")
|
||||
@@ -101,6 +101,12 @@ func (r *dockerFixture) Run(_ context.Context, args []string, input io.Reader) (
|
||||
return compose.Result{}, fmt.Errorf("file newline leaked into scalar credential")
|
||||
}
|
||||
r.calls = append(r.calls, append([]string{}, args...))
|
||||
if args[len(args)-1] == readinessClient {
|
||||
if r.fail == "schema-review" {
|
||||
return compose.Result{ExitCode: 1, Stdout: `{"ok":false,"code":"schema_review_required","completed":0,"workspaceId":"chinook","runId":"e9ca48f6-0a09-49bd-a003-04f9d518d702"}`}, nil
|
||||
}
|
||||
return compose.Result{Stdout: `{"ok":true,"code":"workspaces_prepared","completed":1}`}, nil
|
||||
}
|
||||
return compose.Result{Stdout: `{"ok":true,"code":"bindings_ready","completed":1}`}, nil
|
||||
}
|
||||
r.calls = append(r.calls, append([]string{}, args...))
|
||||
@@ -137,6 +143,9 @@ func (r *dockerFixture) Run(_ context.Context, args []string, input io.Reader) (
|
||||
if strings.Contains(line, " ps ") {
|
||||
return compose.Result{Stdout: `[{"Service":"core","State":"running","Health":"healthy"},{"Service":"frontend","State":"running","Health":"healthy"},{"Service":"catalog-db","State":"running","Health":"healthy"},{"Service":"qdrant","State":"running","Health":"healthy"},{"Service":"embedding","State":"running","Health":"healthy"},{"Service":"embedding-model-init","State":"exited","ExitCode":0}]`}, nil
|
||||
}
|
||||
if strings.Contains(line, "/app/backend/dist/operator-command.js") {
|
||||
return compose.Result{Stdout: `{"ready":true}`}, nil
|
||||
}
|
||||
return compose.Result{Stdout: `{"ok":true}`}, nil
|
||||
}
|
||||
|
||||
@@ -162,7 +171,7 @@ func TestApplyReleasedPlanWithoutInputAndRepeatPreservesData(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !result.PlatformReady || result.WorkspaceReady {
|
||||
if !result.PlatformReady || !result.WorkspaceReady || result.Stage != "workspace-ready" {
|
||||
t.Fatalf("wrong readiness: %+v", result)
|
||||
}
|
||||
}
|
||||
@@ -185,6 +194,22 @@ func TestApplyReleasedPlanWithoutInputAndRepeatPreservesData(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkspaceReviewAndRuntimeFailureNeverClaimWorkspaceReady(t *testing.T) {
|
||||
for _, stage := range []string{"schema-review", "operator-command.js pi-test"} {
|
||||
t.Run(stage, func(t *testing.T) {
|
||||
path, p := fixture(t)
|
||||
r := &dockerFixture{fail: stage}
|
||||
result, err := Run(context.Background(), Request{PlanPath: path, InstallationPath: p.Installation.Path}, r, func(context.Context, preflight.Plan) error { return nil })
|
||||
if err == nil || !result.PlatformReady || !result.BindingsReady || result.WorkspaceReady {
|
||||
t.Fatalf("readiness failure hidden: %+v %v", result, err)
|
||||
}
|
||||
if stage == "schema-review" && (result.WorkspacePreparation == nil || result.WorkspacePreparation.Code != "schema_review_required") {
|
||||
t.Fatalf("human gate lost: %+v", result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func flatten(calls [][]string) []string {
|
||||
out := []string{}
|
||||
for _, c := range calls {
|
||||
|
||||
Reference in New Issue
Block a user