Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

crbn: auto-heal from stale volumes

Sidwebworks336d72947946
diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.ts
index 4427a22b22..c426447fea 100644
--- a/packages/dev/src/commands/up.ts
+++ b/packages/dev/src/commands/up.ts
@@ -1,4 +1,5 @@
import { join } from "node:path";
+import { setTimeout as sleep } from "node:timers/promises";
import { box, intro, log, outro, progress, tasks } from "@clack/prompts";
import { config as loadDotenv } from "dotenv";
import { execa } from "execa";
@@ -28,10 +29,14 @@ import {
listComposeServices,
listContainers,
pullStack,
+ restartServices,
tailServiceLogs
} from "../services/compose.js";
import {
+ applyBootstrapSql,
applyMigrations,
+ storageBucketsExists,
+ waitForPostgres,
waitForStorageTables,
waitForTcp
} from "../services/migrations.js";
@@ -172,11 +177,15 @@ export async function up(
}
]);
- // Wait for services via clack progress bar: 3 TCP ports + 1 for the
- // storage.buckets gate. `waitForStorageTables` updates the subtitle as it
- // polls; the final advance fires only once the table actually appears.
+ // Wait for services via clack progress bar:
+ // 3× TCP ports → +1 supabase roles → +1 storage.buckets = 5 ticks.
+ // Heal path: if storage.buckets hasn't appeared within 30s of postgres
+ // becoming query-ready, re-apply init.sql + restart storage/gotrue/postgrest.
+ // This recovers worktrees whose pgdata volume predates the current init.sql
+ // (Docker only runs init scripts on a fresh data dir, so role passwords can
+ // drift and storage-api auth-fails forever).
{
- const bar = progress({ style: "heavy", max: 4 });
+ const bar = progress({ style: "heavy", max: 5 });
bar.start("Waiting for services");
try {
await waitForTcp(
@@ -187,6 +196,27 @@ export async function up(
],
{ onProgress: (line) => bar.advance(1, line.slice(0, 80)) }
);
+
+ bar.message("waiting for postgres to accept queries");
+ await waitForPostgres(ports.PORT_DB);
+
+ const earlyDeadline = Date.now() + 30_000;
+ let bucketsReady = false;
+ while (Date.now() < earlyDeadline) {
+ if (await storageBucketsExists(ports.PORT_DB)) {
+ bucketsReady = true;
+ break;
+ }
+ await sleep(1000);
+ }
+ if (!bucketsReady) {
+ bar.message("storage stuck — re-applying init.sql");
+ await applyBootstrapSql(root, ports.PORT_DB);
+ bar.message("restarting storage / gotrue / postgrest");
+ await restartServices(root, slug, ["storage", "gotrue", "postgrest"]);
+ }
+ bar.advance(1, "supabase roles ok");
+
await waitForStorageTables(ports.PORT_DB, {
onProgress: (line) => bar.message(line.slice(0, 80)),
onTimeout: async () => {
diff --git a/packages/dev/src/services/compose.ts b/packages/dev/src/services/compose.ts
index 9980e60bfe..38530bd24a 100644
--- a/packages/dev/src/services/compose.ts
+++ b/packages/dev/src/services/compose.ts
@@ -22,6 +22,30 @@ export async function bootStack(root: string, slug: string) {
);
}
+// `docker compose restart` a subset of services. Used by the storage-stuck
+// heal path: after re-applying init.sql we restart storage/gotrue/postgrest so
+// they reconnect with the freshly-rotated supabase role passwords.
+export async function restartServices(
+ root: string,
+ slug: string,
+ services: string[]
+) {
+ if (services.length === 0) return;
+ await execa(
+ "docker",
+ [
+ "compose",
+ "-f",
+ COMPOSE_DEV_FILE,
+ "-p",
+ projectName(slug),
+ "restart",
+ ...services
+ ],
+ { cwd: root, reject: false, stdio: "ignore" }
+ );
+}
+
// Pull all images before `up -d` so `bootStack` doesn't block silently behind
// a multi-GB download. `--progress=plain` emits parseable per-line status to
// stderr (`<service> Pulling`, `<service> Pulled`); we stream the latest line
diff --git a/packages/dev/src/services/migrations.ts b/packages/dev/src/services/migrations.ts
index 281c47ef87..669602e32d 100644
--- a/packages/dev/src/services/migrations.ts
+++ b/packages/dev/src/services/migrations.ts
@@ -1,3 +1,4 @@
+import { readFileSync } from "node:fs";
import net from "node:net";
import { join } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
@@ -56,6 +57,56 @@ function tryConnect(host: string, port: number): Promise<boolean> {
});
}
+// Block until postgres accepts queries (TCP-open ≠ ready — init scripts run
+// after the port opens). Standalone so callers can re-apply bootstrap SQL or
+// restart dependents between this gate and `waitForStorageTables`.
+export async function waitForPostgres(port: number, timeoutMs = 60_000) {
+ const url = `postgresql://postgres:postgres@localhost:${port}/postgres`;
+ const env = { ...process.env, PGSSLMODE: "disable" };
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const r = await execa("psql", [url, "-tAc", "SELECT 1"], {
+ env,
+ reject: false
+ });
+ if (r.exitCode === 0 && r.stdout?.trim() === "1") return;
+ await sleep(1000);
+ }
+ throw new Error(`postgres did not accept queries within ${timeoutMs}ms`);
+}
+
+// Single-shot check used by the heal path to decide whether storage-api has
+// already bootstrapped its schema.
+export async function storageBucketsExists(port: number): Promise<boolean> {
+ const url = `postgresql://postgres:postgres@localhost:${port}/postgres`;
+ const r = await execa(
+ "psql",
+ [url, "-tAc", "SELECT to_regclass('storage.buckets')"],
+ { env: { ...process.env, PGSSLMODE: "disable" }, reject: false }
+ );
+ return r.exitCode === 0 && r.stdout?.trim() === "storage.buckets";
+}
+
+// Re-apply `packages/dev/docker/init.sql` over psql as the superuser.
+// `docker-entrypoint-initdb.d` only runs on a fresh pgdata volume — a worktree
+// with a pre-existing volume from before init.sql evolved keeps the old role
+// passwords forever, so storage-api / gotrue / postgrest auth-fail on every
+// boot. Re-applying is idempotent (`ALTER USER ... PASSWORD`, `CREATE SCHEMA
+// IF NOT EXISTS`).
+export async function applyBootstrapSql(root: string, port: number) {
+ const sql = readFileSync(join(root, "packages/dev/docker/init.sql"), "utf8");
+ const url = `postgresql://postgres:postgres@localhost:${port}/postgres`;
+ const r = await execa("psql", [url, "-v", "ON_ERROR_STOP=1"], {
+ input: sql,
+ env: { ...process.env, PGSSLMODE: "disable" },
+ reject: false
+ });
+ if (r.exitCode !== 0) {
+ process.stderr.write(r.stderr?.toString() ?? "");
+ throw new Error(`init.sql apply failed (exit ${r.exitCode})`);
+ }
+}
+
// Block until postgres accepts queries, then until supabase storage-api
// bootstraps `storage.buckets`. Postgres opens its TCP port well before init
// scripts finish — querying `SELECT 1` is the real readiness signal. Storage