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.

fix(`crbn`): add progressbars

Sidwebworks32eb0846b330
diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.ts
index 70899ef2a0..4427a22b22 100644
--- a/packages/dev/src/commands/up.ts
+++ b/packages/dev/src/commands/up.ts
@@ -1,5 +1,5 @@
import { join } from "node:path";
-import { box, intro, log, outro, tasks } from "@clack/prompts";
+import { box, intro, log, outro, progress, tasks } from "@clack/prompts";
import { config as loadDotenv } from "dotenv";
import { execa } from "execa";
import { currentBranch, isLinkedWorktree } from "../lib/git.js";
@@ -25,7 +25,9 @@ import {
import {
bootSharedRedis,
bootStack,
+ listComposeServices,
listContainers,
+ pullStack,
tailServiceLogs
} from "../services/compose.js";
import {
@@ -136,48 +138,85 @@ export async function up(
await bootSharedRedis(root);
return `shared redis on :${SHARED_REDIS_PORT} (index ${redisDb})`;
}
- },
+ }
+ ]);
+
+ // Pull images outside `tasks()` so we can use clack's progress bar (one
+ // tick per `<service> Pulled` event). Spinner subtitle inside `tasks()`
+ // can't render a bar, only a single line of text.
+ {
+ const services = await listComposeServices(root, slug);
+ const max = Math.max(services.length, 1);
+ const bar = progress({ style: "heavy", max });
+ bar.start("Pulling docker images");
+ try {
+ await pullStack(root, slug, (line) => {
+ bar.message(line.slice(0, 80));
+ if (/ Pulled$/.test(line)) bar.advance(1);
+ });
+ bar.stop("images up to date");
+ } catch (err) {
+ bar.stop("pull failed");
+ throw err;
+ }
+ }
+
+ await tasks([
{
title: "Boot docker compose stack",
task: async (msg) => {
- msg("pulling/starting 12 services");
+ msg("starting 12 services");
await bootStack(root, slug);
return "containers up";
}
- },
- {
- title: "Wait for services",
- task: async (msg) => {
- msg("postgres + kong + inngest");
- await waitForTcp([
+ }
+ ]);
+
+ // 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.
+ {
+ const bar = progress({ style: "heavy", max: 4 });
+ bar.start("Waiting for services");
+ try {
+ await waitForTcp(
+ [
`tcp:${ports.PORT_DB}`,
`tcp:${ports.PORT_API}`,
`tcp:${ports.PORT_INNGEST}`
- ]);
- msg("storage tables");
- await waitForStorageTables(ports.PORT_DB, {
- onTimeout: async () => {
- const containers = await listContainers(root, slug);
- const out: string[] = ["", "--- container state ---"];
- for (const name of ["postgres", "storage"]) {
- const c = containers.find((x) => x.Service === name);
- out.push(
- c
- ? `${name.padEnd(10)} state=${c.State} health=${c.Health ?? "n/a"} ${c.Status}`
- : `${name.padEnd(10)} (not found)`
- );
- }
- out.push("", "--- storage logs (last 50) ---");
- out.push(await tailServiceLogs(root, slug, "storage", 50));
- out.push("", "--- postgres logs (last 20) ---");
- out.push(await tailServiceLogs(root, slug, "postgres", 20));
- out.push("");
- process.stderr.write(out.join("\n") + "\n");
+ ],
+ { onProgress: (line) => bar.advance(1, line.slice(0, 80)) }
+ );
+ await waitForStorageTables(ports.PORT_DB, {
+ onProgress: (line) => bar.message(line.slice(0, 80)),
+ onTimeout: async () => {
+ const containers = await listContainers(root, slug);
+ const out: string[] = ["", "--- container state ---"];
+ for (const name of ["postgres", "storage"]) {
+ const c = containers.find((x) => x.Service === name);
+ out.push(
+ c
+ ? `${name.padEnd(10)} state=${c.State} health=${c.Health ?? "n/a"} ${c.Status}`
+ : `${name.padEnd(10)} (not found)`
+ );
}
- });
- return "all services responding";
- }
- },
+ out.push("", "--- storage logs (last 50) ---");
+ out.push(await tailServiceLogs(root, slug, "storage", 50));
+ out.push("", "--- postgres logs (last 20) ---");
+ out.push(await tailServiceLogs(root, slug, "postgres", 20));
+ out.push("");
+ process.stderr.write(out.join("\n") + "\n");
+ }
+ });
+ bar.advance(1, "storage.buckets ready");
+ bar.stop("all services responding");
+ } catch (err) {
+ bar.stop("services not ready");
+ throw err;
+ }
+ }
+
+ await tasks([
...(shouldMigrate
? [
{
diff --git a/packages/dev/src/services/compose.ts b/packages/dev/src/services/compose.ts
index 96ad97ea94..9980e60bfe 100644
--- a/packages/dev/src/services/compose.ts
+++ b/packages/dev/src/services/compose.ts
@@ -22,6 +22,50 @@ export async function bootStack(root: string, slug: string) {
);
}
+// 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
+// via `onLine` so the caller can feed it into a spinner subtitle.
+export async function pullStack(
+ root: string,
+ slug: string,
+ onLine: (line: string) => void
+) {
+ const proc = execa(
+ "docker",
+ [
+ "compose",
+ "-f",
+ COMPOSE_DEV_FILE,
+ "-p",
+ projectName(slug),
+ "--env-file",
+ ".env.local",
+ "--progress",
+ "plain",
+ "pull"
+ ],
+ { cwd: root, reject: false, all: true }
+ );
+
+ let buf = "";
+ proc.all?.on("data", (b: Buffer) => {
+ buf += b.toString();
+ const lines = buf.split("\n");
+ buf = lines.pop() ?? "";
+ for (const l of lines) {
+ const trimmed = l.trim();
+ if (trimmed) onLine(trimmed);
+ }
+ });
+
+ const r = await proc;
+ if (r.exitCode !== 0) {
+ process.stderr.write(r.all?.toString() ?? "");
+ throw new Error(`docker compose pull failed (exit ${r.exitCode})`);
+ }
+}
+
export async function stopStack(
root: string,
slug: string,
@@ -90,6 +134,34 @@ export async function listContainers(
.map((l) => JSON.parse(l) as Container);
}
+// Names of services declared in the dev compose file, resolved via
+// `docker compose config --services` so we don't drift if services are added.
+export async function listComposeServices(
+ root: string,
+ slug: string
+): Promise<string[]> {
+ const r = await execa(
+ "docker",
+ [
+ "compose",
+ "-f",
+ COMPOSE_DEV_FILE,
+ "-p",
+ projectName(slug),
+ "--env-file",
+ ".env.local",
+ "config",
+ "--services"
+ ],
+ { cwd: root, reject: false }
+ );
+ if (r.exitCode !== 0) return [];
+ return (r.stdout ?? "")
+ .split("\n")
+ .map((s) => s.trim())
+ .filter(Boolean);
+}
+
// Tail logs for a single compose service. Returns merged stdout/stderr —
// docker compose writes log content to stderr on some versions. Empty string
// if the call fails; callers use this for best-effort diagnostics.
diff --git a/packages/dev/src/services/migrations.ts b/packages/dev/src/services/migrations.ts
index 6c7e2506d2..281c47ef87 100644
--- a/packages/dev/src/services/migrations.ts
+++ b/packages/dev/src/services/migrations.ts
@@ -3,15 +3,29 @@ import { join } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { execa } from "execa";
-// Block until each tcp:<port> accepts on 127.0.0.1.
-export async function waitForTcp(targets: string[]) {
+// Block until each tcp:<port> accepts on 127.0.0.1. `onProgress` fires once
+// per port as it opens — caller streams these into a spinner subtitle so a
+// stuck service (e.g. inngest pulling its container) is visible instead of a
+// 60s silent hang.
+export async function waitForTcp(
+ targets: string[],
+ opts: { onProgress?: (line: string) => void } = {}
+) {
const ports = targets.map((t) => {
const m = t.match(/^tcp:(\d+)$/);
if (!m)
throw new Error(`waitForTcp: bad target "${t}" (expected tcp:<port>)`);
return Number(m[1]);
});
- await Promise.all(ports.map((p) => waitForPort(p, 60_000)));
+ const total = ports.length;
+ let opened = 0;
+ await Promise.all(
+ ports.map(async (p) => {
+ await waitForPort(p, 60_000);
+ opened += 1;
+ opts.onProgress?.(`tcp:${p} open (${opened}/${total})`);
+ })
+ );
}
async function waitForPort(
@@ -50,28 +64,41 @@ function tryConnect(host: string, port: number): Promise<boolean> {
// state / logs without leaking compose-project knowledge into this module.
export async function waitForStorageTables(
port: number,
- opts: { onTimeout?: () => Promise<void> } = {}
+ opts: {
+ onTimeout?: () => Promise<void>;
+ onProgress?: (line: string) => void;
+ } = {}
) {
const url = `postgresql://postgres:postgres@localhost:${port}/postgres`;
const env = { ...process.env, PGSSLMODE: "disable" };
const deadline = Date.now() + 180_000;
+ const start = Date.now();
+ const elapsed = () => Math.floor((Date.now() - start) / 1000);
+ opts.onProgress?.("waiting for postgres to accept queries");
while (Date.now() < deadline) {
const r = await execa("psql", [url, "-tAc", "SELECT 1"], {
env,
reject: false
});
- if (r.exitCode === 0 && r.stdout?.trim() === "1") break;
+ if (r.exitCode === 0 && r.stdout?.trim() === "1") {
+ opts.onProgress?.(`postgres ready (${elapsed()}s)`);
+ break;
+ }
await sleep(1000);
}
+ opts.onProgress?.("waiting for storage-api to create storage.buckets");
while (Date.now() < deadline) {
const r = await execa(
"psql",
[url, "-tAc", "SELECT to_regclass('storage.buckets')"],
{ env, reject: false }
);
- if (r.exitCode === 0 && r.stdout?.trim() === "storage.buckets") return;
+ if (r.exitCode === 0 && r.stdout?.trim() === "storage.buckets") {
+ opts.onProgress?.(`storage.buckets ready (${elapsed()}s)`);
+ return;
+ }
await sleep(1000);
}