videogen/scripts/scribase-branch-migrate.sh
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

201 lines
9.6 KiB
Bash
Executable File

#!/usr/bin/env bash
# Rehearse Menivor's pending Alembic migrations on a Scribase time-travel
# branch (SN3.2). Menivor's own database is never touched.
#
# SCRIBASE_ACCESS_TOKEN=... scripts/scribase-branch-migrate.sh \
# --org <org> --project <project> [--env production] [--at <RFC 3339>] \
# [--data sanitized|snapshot] [--ttl-hours 2] [--keep] [--out proof.json]
#
# Check out the PR first; the script applies this working tree's `alembic
# upgrade head`:
# 1. branches --env of the Scribase project that mirrors Menivor's schema
# as it was at --at (default one minute ago; sanitized data by default)
# and waits for the branch to be live;
# 2. carries the branch's serverless WebSocket (SN3.1) to a local TCP port
# and runs the real `alembic upgrade head` against it, timed, with
# `alembic current` before and after;
# 3. deletes the branch (its TTL removes it anyway) and prints one proof
# JSON object. Exit code 0 only when the upgrade succeeded.
#
# Alembic revisions are Python (some read data), so there is no SQL-only
# fallback: the deployment must have the serverless proxy turned on.
#
# Needs: curl, node >= 22 (global WebSocket), the API venv (.venv/bin/python
# with alembic; override with PYTHON=...). Environment: SCRIBASE_ACCESS_TOKEN
# (required), SCRIBASE_API_URL (default https://api.scribase.com),
# SCRIBASE_SERVERLESS_WS_URL (optional WebSocket endpoint override for a
# self-hosted or local proxy).
set -euo pipefail
usage() {
echo "scribase-branch-migrate: $1" >&2
echo "usage: scripts/scribase-branch-migrate.sh --org <org> --project <project> [--env production] [--at <RFC 3339>] [--data sanitized|snapshot] [--ttl-hours 2] [--keep] [--out <file>]" >&2
exit 2
}
ORG="" PROJECT="" PARENT="production" AT="" DATA="sanitized" TTL=2 KEEP=0 OUT="" READY_TIMEOUT=900
while [ $# -gt 0 ]; do
case "$1" in
--org) ORG="${2:-}"; shift 2 ;;
--project) PROJECT="${2:-}"; shift 2 ;;
--env) PARENT="${2:-}"; shift 2 ;;
--at) AT="${2:-}"; shift 2 ;;
--data) DATA="${2:-}"; shift 2 ;;
--ttl-hours) TTL="${2:-}"; shift 2 ;;
--keep) KEEP=1; shift ;;
--out) OUT="${2:-}"; shift 2 ;;
--ready-timeout-seconds) READY_TIMEOUT="${2:-}"; shift 2 ;;
*) usage "unknown option $1" ;;
esac
done
[ -n "$ORG" ] && [ -n "$PROJECT" ] || usage "--org and --project are required"
[ -n "${SCRIBASE_ACCESS_TOKEN:-}" ] || usage "set SCRIBASE_ACCESS_TOKEN (scribase login, or an agent token with branch scope)"
case "$DATA" in sanitized|snapshot) ;; *) usage "--data must be sanitized or snapshot" ;; esac
[[ "$TTL" =~ ^[0-9]+$ ]] && [ "$TTL" -ge 1 ] && [ "$TTL" -le 720 ] || usage "--ttl-hours must be 1 to 720"
[[ "$PARENT" =~ ^[a-z0-9-]+$ ]] || usage "--env must be an environment id"
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
PYTHON="${PYTHON:-$ROOT/.venv/bin/python}"
[ -x "$PYTHON" ] || PYTHON="$(command -v python3)"
command -v node >/dev/null || usage "node >= 22 is required for the WebSocket bridge"
API="${SCRIBASE_API_URL:-https://api.scribase.com}"
API="${API%/}/v1/organizations/$ORG/projects/$PROJECT"
[ -n "$AT" ] || AT="$("$PYTHON" -c 'import datetime as d; print((d.datetime.now(d.timezone.utc)-d.timedelta(minutes=1)).strftime("%Y-%m-%dT%H:%M:%SZ"))')"
BRANCH="rehearse-menivor-$(date -u +%Y%m%d%H%M%S)"
WORK="$(mktemp -d "${TMPDIR:-/tmp}/scribase-rehearse.XXXXXX")"
BRIDGE_PID=""
now_ms() { "$PYTHON" -c 'import time; print(int(time.time()*1000))'; }
json_get() { "$PYTHON" -c 'import json,sys
d=json.load(sys.stdin)
for k in sys.argv[1].split("."):
d=(d or {}).get(k) if isinstance(d,dict) else None
print("" if d is None else d)' "$1"; }
# api METHOD ROUTE [BODY] -> body on stdout; HTTP status in $WORK/status.
api() {
local method="$1" route="$2" body="${3:-}"
local args=(-sS -o "$WORK/body" -w '%{http_code}' -X "$method" \
-H "authorization: Bearer $SCRIBASE_ACCESS_TOKEN" -H 'accept: application/json' \
-H 'user-agent: menivor-scribase-branch-migrate' --max-time 120)
if [ -n "$body" ]; then
args+=(-H 'content-type: application/json' -H "idempotency-key: $BRANCH-$RANDOM$RANDOM" --data "$body")
fi
curl "${args[@]}" "$API$route" > "$WORK/status" || echo 000 > "$WORK/status"
cat "$WORK/body" 2>/dev/null || true
}
status() { cat "$WORK/status"; }
PROOF_ERROR="" MIGRATE_MS="" READY_MS="" BEFORE="" AFTER="" DELETED=false OK=false LOG_TAIL=""
finish() {
set +e
[ -n "$BRIDGE_PID" ] && kill "$BRIDGE_PID" 2>/dev/null
if [ "$KEEP" = 0 ] && [ -n "${CREATED:-}" ]; then
api DELETE "/environments/$BRANCH" >/dev/null
case "$(status)" in 2*) DELETED=true ;; esac
fi
PROOF="$(ORG="$ORG" PROJECT="$PROJECT" PARENT="$PARENT" BRANCH="$BRANCH" AT="$AT" DATA="$DATA" \
READY_MS="$READY_MS" MIGRATE_MS="$MIGRATE_MS" BEFORE="$BEFORE" AFTER="$AFTER" DELETED="$DELETED" \
OK="$OK" PROOF_ERROR="$PROOF_ERROR" LOG_TAIL="$LOG_TAIL" "$PYTHON" -c '
import json, os, datetime
e = os.environ
num = lambda k: int(e[k]) if e.get(k) else None
proof = {
"product": "menivor", "org": e["ORG"], "project": e["PROJECT"], "parent": e["PARENT"],
"branch": e["BRANCH"], "at": e["AT"], "data": e["DATA"], "transport": "bridge",
"branch_ready_ms": num("READY_MS"), "revision_before": e.get("BEFORE") or None,
"revision_after": e.get("AFTER") or None, "migrate_ms": num("MIGRATE_MS"),
"branch_deleted": e["DELETED"] == "true", "ok": e["OK"] == "true",
"finished_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
}
if e.get("PROOF_ERROR"): proof["error"] = e["PROOF_ERROR"]
if e.get("LOG_TAIL") and e["OK"] != "true": proof["log_tail"] = e["LOG_TAIL"]
print(json.dumps(proof, indent=2))')"
[ -n "$OUT" ] && printf '%s\n' "$PROOF" > "$OUT"
printf '%s\n' "$PROOF"
rm -rf "$WORK"
[ "$OK" = true ] && exit 0 || exit 1
}
trap finish EXIT
fail() { PROOF_ERROR="$1"; exit 1; }
# 1. Branch at a point in time and wait for it.
started="$(now_ms)"
api POST "/environments/$PARENT/branch-time/branch" \
"{\"at\":\"$AT\",\"name\":\"$BRANCH\",\"ttl_hours\":$TTL,\"data\":\"$DATA\"}" > "$WORK/create.json"
case "$(status)" in 2*) CREATED=1 ;; *) fail "branch create answered $(status): $(json_get detail < "$WORK/create.json")" ;; esac
while :; do
[ $(( $(now_ms) - started )) -gt $(( READY_TIMEOUT * 1000 )) ] && fail "branch $BRANCH was not ready in time"
state="$(api GET "/environments/$BRANCH/branch-time" | json_get status.state 2>/dev/null || true)"
[ "$state" = failed ] && fail "branch $BRANCH failed to rewind"
if [ "$state" = succeeded ]; then
phase="$(api GET "/environments/$BRANCH" | json_get phase 2>/dev/null || true)"
{ [ -z "$phase" ] || [ "$phase" = ready ]; } && break
fi
sleep 3
done
READY_MS=$(( $(now_ms) - started ))
# 2. The branch's serverless string, bridged to a local port.
api GET "/environments/$BRANCH/serverless" > "$WORK/serverless.json"
case "$(status)" in
200) ;;
503) fail "the serverless proxy is not turned on for this deployment; Alembic needs it (SN3.1)" ;;
*) fail "serverless answered $(status)" ;;
esac
CONN="$(json_get connection_uri < "$WORK/serverless.json")"
read -r HOST USERINFO DBNAME < <("$PYTHON" -c '
import sys, urllib.parse as u
p = u.urlsplit(sys.argv[1].replace("postgresql://", "http://", 1).replace("postgres://", "http://", 1))
print(p.hostname, p.netloc.rsplit("@", 1)[0], p.path.lstrip("/") or "postgres")' "$CONN")
WS_URL="${SCRIBASE_SERVERLESS_WS_URL:-wss://$HOST/v2}?address=$HOST:5432"
cat > "$WORK/bridge.mjs" <<'NODE'
// Local TCP port -> the Scribase serverless WebSocket (Postgres wire protocol inside).
import net from 'node:net';
const target = process.argv[2];
const server = net.createServer((socket) => {
const ws = new WebSocket(target);
ws.binaryType = 'arraybuffer';
const queued = [];
socket.on('data', (chunk) => (ws.readyState === 1 ? ws.send(chunk) : queued.push(chunk)));
ws.onopen = () => { for (const chunk of queued) ws.send(chunk); queued.length = 0; };
ws.onmessage = (event) => socket.write(Buffer.from(event.data));
ws.onclose = () => socket.end();
ws.onerror = () => socket.destroy();
socket.on('close', () => ws.close());
socket.on('error', () => ws.close());
});
server.listen(0, '127.0.0.1', () => console.log(server.address().port));
NODE
node "$WORK/bridge.mjs" "$WS_URL" > "$WORK/bridge.port" 2> "$WORK/bridge.log" &
BRIDGE_PID=$!
for _ in $(seq 1 50); do [ -s "$WORK/bridge.port" ] && break; sleep 0.1; done
PORT="$(head -1 "$WORK/bridge.port")"
[ -n "$PORT" ] || fail "the local bridge did not start: $(cat "$WORK/bridge.log")"
LOCAL_URL="postgresql://$USERINFO@127.0.0.1:$PORT/$DBNAME?sslmode=disable"
# Every variable Menivor's config reads, so nothing can fall back to its own database.
export REELFORGE_DATABASE_URL="$LOCAL_URL" NEON_DATABASE_URL="$LOCAL_URL" DATABASE_URL="$LOCAL_URL"
cd "$ROOT"
resolved_host="$(PYTHONPATH="$ROOT/apps/api:$ROOT" "$PYTHON" -c '
import urllib.parse as u
from app.config import config
url = config.neon.get("database_url", "") if getattr(config, "neon", None) is not None else ""
print(u.urlsplit(url.replace("+psycopg", "", 1)).hostname or "")' 2>/dev/null || echo 127.0.0.1)"
[ "$resolved_host" = 127.0.0.1 ] || fail "Menivor's config resolved the database host to '$resolved_host', not the branch bridge; refusing to run"
# 3. The real upgrade, timed.
BEFORE="$("$PYTHON" -m alembic current 2>/dev/null | tail -1 | awk '{print $1}')"
started="$(now_ms)"
if "$PYTHON" -m alembic upgrade head > "$WORK/upgrade.log" 2>&1; then
OK=true
fi
MIGRATE_MS=$(( $(now_ms) - started ))
AFTER="$("$PYTHON" -m alembic current 2>/dev/null | tail -1 | awk '{print $1}')"
LOG_TAIL="$(tail -c 2000 "$WORK/upgrade.log" | sed -E 's#postgresql(\+psycopg)?://[^@ ]+@#postgresql://***@#g')"
[ "$OK" = true ] || PROOF_ERROR="alembic upgrade head failed"