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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(self-host): harden deploy.sh against the bug classes hit in the field
Sidwebworks94fb666982a6
diff --git a/contrib/deploying/simple-docker-caddy/deploy.sh b/contrib/deploying/simple-docker-caddy/deploy.shindex 973bbc559f..763902483b 100755--- a/contrib/deploying/simple-docker-caddy/deploy.sh+++ b/contrib/deploying/simple-docker-caddy/deploy.sh@@ -25,9 +25,12 @@ readonly ENV_FILE="$HERE/.env"readonly ENV_EXAMPLE="$HERE/.env.example"# Secrets generated by `init` (value auto-created) vs. supplied by the operator.-readonly GENERATED_SECRETS="postgres_password session_secret inngest_signing_key inngest_event_key"+# postgres_password is handled on its own (paired with postgrest_db_uri), so it is+# NOT in GENERATED_SECRETS. ALL_SECRETS is the full set the stack needs to deploy.+readonly GENERATED_SECRETS="session_secret inngest_signing_key inngest_event_key"readonly TRIO_SECRETS="jwt_secret anon_key service_role_key"readonly SUPPLIED_SECRETS="resend_api_key smtp_password"+readonly ALL_SECRETS="postgres_password postgrest_db_uri $GENERATED_SECRETS $TRIO_SECRETS $SUPPLIED_SECRETS"log() { printf '\033[0;36m[%s]\033[0m %s\n' "$(date '+%H:%M:%S')" "$*"; }warn() { printf '\033[0;33m[warn]\033[0m %s\n' "$*" >&2; }@@ -51,6 +54,27 @@ swarm_active() { [ "$(docker info --format '{{.Swarm.LocalNodeState}}' 2>/dev/nusecret_exists() { docker secret inspect "$1" >/dev/null 2>&1; }create_secret() { printf '%s' "$2" | docker secret create "$1" - >/dev/null && log "secret '$1' created"; }+# Create or replace a secret. Refuses (clear error) if it is in use by the running+# stack — Swarm secrets are immutable while attached, so rotation needs `down` first.+replace_secret() {+ if secret_exists "$1"; then+ docker secret rm "$1" >/dev/null 2>&1 \+ || error "secret '$1' is in use — run '$SCRIPT_NAME down' first, then retry"+ fi+ create_secret "$1" "$2"+}++# postgres_password and postgrest_db_uri MUST always carry the same password. The+# PostgREST image is FROM scratch (no shell) so it can't run the secrets-entrypoint+# shim to assemble the URI from the password at boot — it reads a ready-made URI from+# its own secret file (PGRST_DB_URI=@/run/secrets/postgrest_db_uri). Minting them+# anywhere else independently is what causes "password authentication failed for+# user authenticator". This is the ONLY place either is written.+set_postgres_password() {+ replace_secret postgres_password "$1"+ replace_secret postgrest_db_uri "postgres://authenticator:${1}@postgres:5432/postgres"+}+# ── init ──────────────────────────────────────────────────────────────────────cmd_init() {require_cmds docker openssl@@ -67,31 +91,26 @@ cmd_init() {chmod +x "$HERE/bin/secrets-entrypoint.sh" "$HERE/postgres/"*.shlog "Creating Docker secrets (skipping any that already exist)"- local s pgpw=""+ local s++ # Postgres password + the PostgREST URI derived from it — always minted together.+ # On --force, or if EITHER is missing, (re)mint the pair so they can't drift apart.+ if secret_exists postgres_password && secret_exists postgrest_db_uri && [ "$force" -ne 1 ]; then+ log "secret 'postgres_password' exists — skip (postgrest_db_uri tracks it)"+ else+ set_postgres_password "$(openssl rand -hex 24)"+ fi+for s in $GENERATED_SECRETS; doif secret_exists "$s" && [ "$force" -ne 1 ]; then log "secret '$s' exists — skip"; continue; fi- secret_exists "$s" && docker secret rm "$s" >/dev/nullcase "$s" in- postgres_password) pgpw="$(openssl rand -hex 24)"; create_secret "$s" "$pgpw" ;;- session_secret) create_secret "$s" "$(openssl rand -hex 32)" ;;+ session_secret) replace_secret "$s" "$(openssl rand -hex 32)" ;;# Inngest self-host rejects the signkey- prefix — plain hex only.- inngest_signing_key) create_secret "$s" "$(openssl rand -hex 32)" ;;- inngest_event_key) create_secret "$s" "$(openssl rand -hex 16)" ;;+ inngest_signing_key) replace_secret "$s" "$(openssl rand -hex 32)" ;;+ inngest_event_key) replace_secret "$s" "$(openssl rand -hex 16)" ;;esacdone- # PostgREST's image has no shell, so it can't use the secrets-entrypoint shim.- # It reads any value from a file when prefixed with @, so it gets the full- # connection URI (password and all) as its own secret, minted from pgpw above.- if secret_exists postgrest_db_uri && [ "$force" -ne 1 ]; then- log "secret 'postgrest_db_uri' exists — skip"- elif [ -n "$pgpw" ]; then- secret_exists postgrest_db_uri && docker secret rm postgrest_db_uri >/dev/null- create_secret postgrest_db_uri "postgres://authenticator:${pgpw}@postgres:5432/postgres"- else- warn "postgres_password already existed — can't regenerate 'postgrest_db_uri'. Use '$SCRIPT_NAME init --force' to rotate both."- fi-# Supabase key trio — must be minted together (anon/service signed by jwt_secret).if secret_exists jwt_secret && [ "$force" -ne 1 ]; thenlog "secret 'jwt_secret' exists — skipping Supabase trio"@@ -102,10 +121,9 @@ cmd_init() {jwt=$(printf '%s\n' "$trio" | sed -n 's/^SUPABASE_JWT_SECRET=//p')anon=$(printf '%s\n' "$trio" | sed -n 's/^SUPABASE_ANON_KEY=//p')svc=$(printf '%s\n' "$trio" | sed -n 's/^SUPABASE_SERVICE_ROLE_KEY=//p')- for s in jwt_secret anon_key service_role_key; do secret_exists "$s" && docker secret rm "$s" >/dev/null; done- create_secret jwt_secret "$jwt"- create_secret anon_key "$anon"- create_secret service_role_key "$svc"+ replace_secret jwt_secret "$jwt"+ replace_secret anon_key "$anon"+ replace_secret service_role_key "$svc"fi# Operator-supplied secrets — placeholders so the stack deploys; replace later.@@ -142,18 +160,25 @@ cmd_build() {cmd_deploy() {require_cmds docker; load_envswarm_active || error "swarm not active — run '$SCRIPT_NAME init'"+ # Every external secret must exist or `docker stack deploy` fails cryptically.+ local s missing=""+ for s in $ALL_SECRETS; do secret_exists "$s" || missing="$missing $s"; done+ [ -z "$missing" ] || error "missing secret(s):${missing} — run '$SCRIPT_NAME init'"log "Deploying stack '$STACK_NAME'"# --resolve-image never: use the locally built tags as-is for the no-registry path.local resolve=never; [ -n "${CARBON_REGISTRY:-}" ] && resolve=alwaysdocker stack deploy --detach=true --resolve-image "$resolve" -c "$STACK_FILE" "$STACK_NAME"}-# Wait until a service has a healthy (or, if no healthcheck, running) task.+# Wait until a service has a healthy task. Matches on the exact Swarm service-name+# label, NOT a name substring — `name=carbon_postgres` also matches carbon_postgres-t+# and would report a false positive.wait_healthy() {local svc="$1" timeout="${2:-180}" name="${STACK_NAME}_$1" waited=0log "Waiting for $name to be healthy (timeout ${timeout}s)"while [ "$waited" -lt "$timeout" ]; do- if docker ps --filter "name=$name" --filter health=healthy --format '{{.Names}}' | grep -q .; then+ if docker ps --filter "label=com.docker.swarm.service.name=$name" \+ --filter health=healthy -q | grep -q .; thenlog "$name healthy"; return 0fisleep 5; waited=$((waited + 5))@@ -172,16 +197,36 @@ cmd_migrate() {docker service create \--name "$job" \--mode replicated-job \- --detach=false \+ --detach=true \--network "${STACK_NAME}_internal" \--secret postgres_password \--restart-condition on-failure \- --restart-max-attempts 30 \+ --restart-max-attempts 10 \--env PGSSLMODE=disable \--workdir /repo/packages/database \"$CARBON_IMAGE_ERP" \sh -c 'pnpm exec supabase migration up --include-all \- --db-url "postgresql://supabase_admin:$(cat /run/secrets/postgres_password)@postgres:5432/postgres"'+ --db-url "postgresql://supabase_admin:$(cat /run/secrets/postgres_password)@postgres:5432/postgres"' >/dev/null++ # Wait for the one-shot job to finish, then ALWAYS surface its logs and abort on+ # failure — a detached job otherwise dies silently and `up` would roll on regardless.+ # Succeed on Complete; only fail once retries are exhausted (no task still active),+ # so a transient mid-retry Failed doesn't abort a job that would have succeeded.+ local waited=0 timeout=600 outcome="" states=""+ while [ "$waited" -lt "$timeout" ]; do+ states=$(docker service ps "$job" --format '{{.CurrentState}}' 2>/dev/null)+ if printf '%s\n' "$states" | grep -q '^Complete'; then outcome=complete; break; fi+ if ! printf '%s\n' "$states" | grep -qE '^(Running|Ready|Preparing|Assigned|Starting|New|Pending|Accepted)' \+ && printf '%s\n' "$states" | grep -qE '^(Failed|Rejected)'; then outcome=failed; break; fi+ sleep 5; waited=$((waited + 5))+ done++ if [ "$outcome" != complete ]; then+ warn "Migration job ${outcome:-timed out}. Logs:"+ docker service logs "$job" 2>&1 | tail -60 >&2 || true+ docker service rm "$job" >/dev/null 2>&1 || true+ error "Migrations failed — see logs above."+ fidocker service rm "$job" >/dev/null 2>&1 || truelog "Migrations applied"}@@ -211,11 +256,14 @@ cmd_secret() {else error "usage: $SCRIPT_NAME secret $name <value> (or pipe the value on stdin)"fi[ -n "$val" ] || error "empty value for secret '$name'"- if secret_exists "$name"; then- docker secret rm "$name" >/dev/null 2>&1 \- || error "secret '$name' is in use — run '$SCRIPT_NAME down' first, then set it"+ # Rotating the DB password must also re-mint the derived PostgREST URI, or+ # postgrest fails auth. Note: the DB only adopts a new password on a fresh+ # pgdata volume, so a live rotation needs `down --volumes` + `init --force`.+ if [ "$name" = "postgres_password" ]; then+ set_postgres_password "$val"+ return 0fi- create_secret "$name" "$val"+ replace_secret "$name" "$val"}cmd_status() {@@ -237,12 +285,19 @@ cmd_down() {docker stack rm "$STACK_NAME"if [ "${1:-}" = "--volumes" ]; thenwarn "Waiting for tasks to stop, then deleting volumes (DATA LOSS)"- sleep 10- docker volume ls -q --filter "name=${STACK_NAME}_" | xargs -r docker volume rm+ local waited=0+ while docker ps -q --filter "label=com.docker.stack.namespace=${STACK_NAME}" | grep -q .; do+ [ "$waited" -ge 60 ] && break+ sleep 3; waited=$((waited + 3))+ done+ docker volume ls -q --filter "name=${STACK_NAME}_" | xargs -r docker volume rm >/dev/null 2>&1 \+ || warn "some volumes still in use — re-run '$SCRIPT_NAME down --volumes'"+ log "Volumes removed"fi}-usage() { sed -n '10,28p' "$0" | sed 's/^# \{0,1\}//'; exit "${1:-0}"; }+# Print the "Usage:" comment block (from that line until the first non-comment line).+usage() { awk '/^# Usage:/{f=1} f&&!/^#/{exit} f{sub(/^# ?/,"");print}' "$0"; exit "${1:-0}"; }main() {local sub="${1:-}"; [ $# -gt 0 ] && shift || true