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

334 lines
16 KiB
Bash
Executable File

#!/usr/bin/env bash
# cutover.sh: move the Menivor money database from box 1 Postgres to Neon (MG9,
# owner decision MD21). Runbook: infra-box/RUNBOOK-MENIVOR-NEON.md.
#
# cutover.sh --preflight-only [--last-flip <ISO>] [--drill-report <file>]
# cutover.sh --rehearse [--target-var <VAR>]
# cutover.sh --yes [--last-flip <ISO>] [--drill-report <file>] [--no-post-drill]
#
# --preflight-only run every check below and stop. Changes nothing.
# --rehearse copy the LIVE box database (writers keep running) into an
# empty Neon branch whose URL is in <VAR> (default
# MENIVOR_NEON_REHEARSAL_URL in the env file), verify with
# drift allowed, and report the timings the real cutover will
# need. No writer is stopped and the env file is not touched.
# --yes the real cutover:
# 1. preflight (below); any failure stops here with nothing changed;
# 2. stop the writers (api, worker, housekeeping, beat): downtime starts;
# 3. copy.sh box -> Neon (direct URL), verify.sh exact (every count, money
# table md5s, sequences). On a mismatch the writers restart on box 1 and
# nothing else changes;
# 4. switch the env file: COMPOSE_FILE adds docker-compose.neon.yml (the
# previous file is kept as a .bak), run migrate, start the stack;
# 5. /healthz answers: downtime ends and is written down. If it does not
# answer within 3 min, the env file is switched back and the stack starts
# on box 1 again (automatic rollback);
# 6. stop the box database container (kept, with its data, for rollback.sh),
# measure host RAM before and after, append to the origin-flip log, and run
# the read-only Neon restore check (restore-drill.sh --mode neon-branch --at)
# at the moment the copy was verified, expecting the verified money counts.
#
# Preflight: env file has MENIVOR_NEON_DIRECT_URL, MENIVOR_NEON_DATABASE_URL and
# MENIVOR_NEON_PROJECT_ID; both URLs use sslmode=require; the stack still runs on
# box 1; docker-compose.neon.yml is in the stack; compose >= 2.24 (for !override);
# the box database is up; Neon answers on the same Postgres major and is empty;
# a PASS restore-drill report (--mode neon-branch --probe) on this Neon project
# from the last 7 days; the last origin flip (NCUT_FLIPS_LOG or --last-flip) is
# at least 48 h ago; free disk for the dump.
#
# Reports: NCUT_STATE_DIR/cutover-<time>.json. Exit 0 = done (or checks passed).
set -Eeuo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib.sh
. "$HERE/lib.sh"
usage() { sed -n '2,38p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 2; }
MODE="" LAST_FLIP="" TARGET_VAR=MENIVOR_NEON_REHEARSAL_URL POST_DRILL=1
DRILL_REPORT="${NCUT_DRILL_REPORT:-$NCUT_STATE_DIR/neon-drill-report.json}"
NCUT_RESTORE_DRILL="${NCUT_RESTORE_DRILL:-/opt/infra-box/backup/restore-drill.sh}"
NCUT_DRILL_ENV="${NCUT_DRILL_ENV:-/etc/products/menivor-neon-drill.env}"
NCUT_HEALTH_TIMEOUT_S="${NCUT_HEALTH_TIMEOUT_S:-180}"
NCUT_SETTLE_S="${NCUT_SETTLE_S:-30}"
while (($#)); do
case "$1" in
--preflight-only) MODE=preflight ;;
--rehearse) MODE=rehearse ;;
--yes) MODE=cutover ;;
--last-flip) LAST_FLIP="$2"; shift ;;
--drill-report) DRILL_REPORT="$2"; shift ;;
--target-var) TARGET_VAR="$2"; shift ;;
--no-post-drill) POST_DRILL=0 ;;
-h | --help) usage ;;
*) echo "unknown argument: $1" >&2; usage ;;
esac
shift
done
[[ -n "$MODE" ]] || usage
[[ -z "$LAST_FLIP" || "$LAST_FLIP" =~ $NCUT_ISO_RE ]] || ncut_die "--last-flip must be ISO UTC, e.g. 2026-09-28T20:00:00Z"
[[ "$TARGET_VAR" =~ ^[A-Z_][A-Z0-9_]*$ ]] || ncut_die "--target-var must be an env variable name"
BOX_EP="container:$MENIVOR_DB_CONTAINER/$MENIVOR_DB_NAME"
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
REPORT_FILE="$NCUT_STATE_DIR/cutover-$STAMP.json"
STARTED_AT="$(ncut_now)"
NOTES=()
note() { NOTES+=("$*"); ncut_log "$*"; }
declare -A R=() # report fields (strings or numbers)
write_report() { # write_report <verdict> <summary>
install -d -m 700 "$NCUT_STATE_DIR"
local args=() k
for k in "${!R[@]}"; do args+=(--arg "$k" "${R[$k]}"); done
jq -n --arg verdict "$1" --arg summary "$2" --arg mode "$MODE" --arg started "$STARTED_AT" \
--arg notes "$(printf '%s\n' "${NOTES[@]+"${NOTES[@]}"}")" "${args[@]+"${args[@]}"}" \
'$ARGS.named | del(.notes) + {notes: ($notes | split("\n") | map(select(length > 0)))}
| with_entries(.value |= (if type == "string" and test("^-?[0-9]+$") then tonumber else . end))' \
>"$REPORT_FILE"
chmod 600 "$REPORT_FILE"
echo "CUTOVER $1 mode=$MODE $2 (report: $REPORT_FILE)"
}
# Once the writers are stopped, any failure must leave the stack serving again.
WRITERS_STOPPED=0
SWITCHED=0
ncut_on_die() {
# Inside $(...) only the parent may act; it gets the failure through its ERR trap.
[[ "$BASHPID" == "$$" ]] || exit 1
trap - ERR
if ((SWITCHED)); then
note "failure after the switch: switching back to box 1"
switch_env box || true
docker start "$MENIVOR_DB_CONTAINER" >/dev/null 2>&1 || true
ncut_compose up -d >/dev/null 2>&1 || true
elif ((WRITERS_STOPPED)); then
note "failure before the switch: restarting the writers on box 1"
# shellcheck disable=SC2086
ncut_compose start $NCUT_WRITERS >/dev/null 2>&1 || true
fi
write_report FAIL "$*" || true
}
trap 'ncut_die "unexpected error on line $LINENO"' ERR
switch_env() { # switch_env neon|box
if [[ "$1" == neon ]]; then
menivor_env_set COMPOSE_FILE "$NCUT_COMPOSE_FILES_NEON" to-neon
else
menivor_env_set COMPOSE_FILE "$NCUT_COMPOSE_FILES_BOX" to-box
fi
menivor_env_set MENIVOR_DB_TARGET "$1" "to-$1"
}
version_ge() { [[ "$(printf '%s\n%s\n' "$2" "$1" | sort -V | head -n 1)" == "$2" ]]; }
# ---------------------------------------------------------------- preflight ---
CHECK_FAILS=()
check() { # check <ok 0|1> <message>
if [[ "$1" == 0 ]]; then note "ok: $2"; else CHECK_FAILS+=("$2"); ncut_log "FAIL: $2"; fi
}
load_neon_env() {
MENIVOR_NEON_DIRECT_URL="$(menivor_env_get MENIVOR_NEON_DIRECT_URL || true)"
MENIVOR_NEON_DATABASE_URL="$(menivor_env_get MENIVOR_NEON_DATABASE_URL || true)"
MENIVOR_NEON_PROJECT_ID="$(menivor_env_get MENIVOR_NEON_PROJECT_ID || true)"
export MENIVOR_NEON_DIRECT_URL MENIVOR_NEON_DATABASE_URL MENIVOR_NEON_PROJECT_ID
}
last_flip_epoch() {
if [[ -n "$LAST_FLIP" ]]; then ncut_iso_to_epoch "$LAST_FLIP"; return; fi
[[ -r "$NCUT_FLIPS_LOG" ]] || return 1
local iso
iso="$(grep -Eo '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z' "$NCUT_FLIPS_LOG" | sort | tail -n 1)"
[[ -n "$iso" ]] || return 1
ncut_iso_to_epoch "$iso"
}
drill_report_ok() { # prints why not, returns 1 when the report does not qualify
[[ -r "$DRILL_REPORT" ]] || { echo "no restore-drill report at $DRILL_REPORT"; return 1; }
local verdict mode run notes run_iso age
verdict="$(jq -r '.verdict // ""' "$DRILL_REPORT")"
mode="$(jq -r '.mode // ""' "$DRILL_REPORT")"
run="$(jq -r '.run // ""' "$DRILL_REPORT")"
notes="$(jq -r '(.notes // []) | join("\n")' "$DRILL_REPORT")"
[[ "$verdict" == PASS && "$mode" == neon-branch ]] || { echo "drill report is $verdict/$mode, need PASS/neon-branch"; return 1; }
grep -q "destructive write" <<<"$notes" || { echo "drill report is not a --probe drill (no destructive write)"; return 1; }
grep -q "project $MENIVOR_NEON_PROJECT_ID," <<<"$notes" || { echo "drill report is for another Neon project"; return 1; }
[[ "$run" =~ ^([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2})([0-9]{2})([0-9]{2})Z ]] || { echo "drill report has no run time"; return 1; }
run_iso="${BASH_REMATCH[1]}-${BASH_REMATCH[2]}-${BASH_REMATCH[3]}T${BASH_REMATCH[4]}:${BASH_REMATCH[5]}:${BASH_REMATCH[6]}Z"
age=$(($(ncut_epoch) - $(ncut_iso_to_epoch "$run_iso")))
((age <= 7 * 86400)) || { echo "drill report is $((age / 86400)) days old (max 7)"; return 1; }
echo "drill PASS at $run_iso"
}
preflight() {
local rc r why v
[[ -r "$MENIVOR_ENV_FILE" ]] && r=0 || r=1; check $r "env file $MENIVOR_ENV_FILE readable"
load_neon_env
for v in MENIVOR_NEON_DIRECT_URL MENIVOR_NEON_DATABASE_URL; do
[[ "${!v}" =~ ^postgres(ql)?(\+[a-z0-9]+)?:// ]] && r=0 || r=1; check $r "$v is a postgres URL"
[[ "${!v}" == *sslmode=require* || "${!v}" == *sslmode=verify-full* ]] && r=0 || r=1; check $r "$v requires TLS (sslmode=require)"
done
[[ "$MENIVOR_NEON_DATABASE_URL" == *-pooler.* ]] \
|| note "note: MENIVOR_NEON_DATABASE_URL is not a -pooler host; the app will use direct connections"
[[ "$MENIVOR_NEON_PROJECT_ID" =~ ^[a-z0-9-]+$ ]] && r=0 || r=1; check $r "MENIVOR_NEON_PROJECT_ID set"
[[ "$(ncut_db_target)" == box ]] && r=0 || r=1; check $r "stack still runs on box 1 Postgres (COMPOSE_FILE has no neon override)"
[[ -f "$MENIVOR_STACK/docker-compose.neon.yml" ]] && r=0 || r=1; check $r "docker-compose.neon.yml present in $MENIVOR_STACK"
v="$(ncut_compose version --short 2>/dev/null | tr -d 'v' || true)"
version_ge "${v:-0}" 2.24.0 && r=0 || r=1; check $r "docker compose ${v:-missing} >= 2.24 (needed for !override)"
[[ "$(docker inspect -f '{{.State.Running}}' "$MENIVOR_DB_CONTAINER" 2>/dev/null || true)" == true ]] && r=0 || r=1
check $r "box database container $MENIVOR_DB_CONTAINER running"
if [[ -n "$MENIVOR_NEON_DIRECT_URL" ]]; then
local box_major neon_major tables db_bytes free_bytes
box_major="$(ncut_server_major "$BOX_EP" 2>/dev/null || echo "?")"
neon_major="$(ncut_server_major env:MENIVOR_NEON_DIRECT_URL 2>/dev/null || echo "?")"
[[ "$neon_major" != "?" ]] && r=0 || r=1; check $r "Neon answers on the direct URL"
[[ "$box_major" == "$neon_major" ]] && r=0 || r=1; check $r "same Postgres major on box ($box_major) and Neon ($neon_major)"
tables="$(ncut_user_tables env:MENIVOR_NEON_DIRECT_URL 2>/dev/null | grep -c . || true)"
[[ "$tables" == 0 ]] && r=0 || r=1; check $r "Neon database is empty ($tables user tables)"
db_bytes="$(ncut_sql "$BOX_EP" "SELECT pg_database_size(current_database())" 2>/dev/null || echo 0)"
install -d -m 700 "$NCUT_STATE_DIR"
free_bytes="$(df -Pk "$NCUT_STATE_DIR" | awk 'NR == 2 {print $4 * 1024}')"
((free_bytes > 2 * db_bytes + 1073741824)) && r=0 || r=1; check $r "free disk for the dump ($((free_bytes / 1048576)) MiB free, database $((db_bytes / 1048576)) MiB)"
R[box_db_bytes]="$db_bytes"
fi
if why="$(drill_report_ok)"; then rc=0; else rc=1; fi
check $rc "restore drill on Neon: $why"
local flip now
now="$(ncut_epoch)"
if flip="$(last_flip_epoch)"; then
((now - flip >= NCUT_MIN_FLIP_GAP_S)) && r=0 || r=1; check $r "last origin flip $(((now - flip) / 3600)) h ago (need >= $((NCUT_MIN_FLIP_GAP_S / 3600)) h)"
else
check 1 "last origin flip unknown: no $NCUT_FLIPS_LOG entry and no --last-flip (the S1.1 flip must be at least 48 h old)"
fi
if ((${#CHECK_FAILS[@]})); then
ncut_die "preflight failed: $(IFS=';'; echo "${CHECK_FAILS[*]}")"
fi
note "preflight passed"
}
# ------------------------------------------------------------------ rehearse ---
rehearse() {
[[ -n "${!TARGET_VAR:-}" ]] || { v="$(menivor_env_get "$TARGET_VAR" || true)"; printf -v "$TARGET_VAR" '%s' "$v"; export "${TARGET_VAR?}"; }
[[ -n "${!TARGET_VAR:-}" ]] || ncut_die "$TARGET_VAR is empty: create an empty Neon branch and put its direct URL there"
load_neon_env
[[ -z "$MENIVOR_NEON_DIRECT_URL" || "${!TARGET_VAR}" != "$MENIVOR_NEON_DIRECT_URL" ]] \
|| ncut_die "$TARGET_VAR equals MENIVOR_NEON_DIRECT_URL: rehearse on a separate branch"
ncut_prepare_state_dir
local out t0
t0=$SECONDS
out="$("$HERE/copy.sh" --source "$BOX_EP" --target "env:$TARGET_VAR" --work "$NCUT_WORK")"
parse_copy "$out"
"$HERE/verify.sh" --source "$BOX_EP" --target "env:$TARGET_VAR" --allow-drift \
--report "$NCUT_WORK/verify.json" >&2 || ncut_die "rehearsal verify failed (see $NCUT_WORK/verify.json)"
R[verify_rows]="$(jq -r .rows "$NCUT_WORK/verify.json")"
R[copy_and_verify_s]=$((SECONDS - t0))
R[expected_downtime_s]=$((SECONDS - t0 + 60))
R[work_dir]="$NCUT_WORK"
note "rehearsal: copy+verify took ${R[copy_and_verify_s]}s; plan for about ${R[expected_downtime_s]}s of downtime (plus stack start)"
write_report PASS "rehearsal copied $(jq -r .tables "$NCUT_WORK/verify.json") tables"
}
parse_copy() {
local kv
for kv in $1; do
case "$kv" in dump_bytes=* | dump_s=* | restore_s=*) R[${kv%%=*}]="${kv#*=}" ;; esac
done
}
# ------------------------------------------------------------------- cutover ---
cutover() {
preflight
ncut_prepare_state_dir
R[work_dir]="$NCUT_WORK"
local before_mem db_mem out t_stop t_up verified_at c
before_mem="$(ncut_host_mem)"
db_mem="$(ncut_container_mem "$MENIVOR_DB_CONTAINER")"
R[host_used_mib_before]="${before_mem%% *}"
R[host_total_mib]="${before_mem##* }"
R[db_container_mem_before]="$db_mem"
# 2. writers down: downtime starts.
note "stopping writers: $NCUT_WRITERS"
WRITERS_STOPPED=1
t_stop=$SECONDS
R[writers_stopped_at]="$(ncut_now)"
# shellcheck disable=SC2086
ncut_compose stop $NCUT_WRITERS >&2
# 3. copy and verify, exact.
out="$("$HERE/copy.sh" --source "$BOX_EP" --target env:MENIVOR_NEON_DIRECT_URL --work "$NCUT_WORK")" \
|| ncut_die "copy to Neon failed (Neon was restored in one transaction, so it is still empty)"
parse_copy "$out"
"$HERE/verify.sh" --source "$BOX_EP" --target env:MENIVOR_NEON_DIRECT_URL \
--report "$NCUT_WORK/verify.json" >&2 \
|| ncut_die "verify failed: $(jq -r '.mismatches | join("; ")' "$NCUT_WORK/verify.json" 2>/dev/null | head -c 600). Reset the Neon branch before a retry."
verified_at="$(ncut_now)"
R[verified_at]="$verified_at"
R[verify_tables]="$(jq -r .tables "$NCUT_WORK/verify.json")"
R[verify_rows]="$(jq -r .rows "$NCUT_WORK/verify.json")"
for c in credit_ledger wallet_ledger_entries premium_credit_ledger users; do
R[count_$c]="$(jq -r --arg t "public.$c" '.counts[$t].target // empty' "$NCUT_WORK/verify.json")"
done
# 4. switch and start.
note "switching the env file to Neon"
SWITCHED=1
switch_env neon
ncut_compose run --rm migrate >&2 || ncut_die "migrate against Neon failed"
ncut_compose up -d >&2 || ncut_die "stack did not start on Neon"
# 5. health.
if ! ncut_wait_healthy "$NCUT_HEALTH_TIMEOUT_S"; then
ncut_die "api not healthy on Neon after ${NCUT_HEALTH_TIMEOUT_S}s"
fi
t_up=$SECONDS
SWITCHED=0 WRITERS_STOPPED=0
R[serving_at]="$(ncut_now)"
R[downtime_s]=$((t_up - t_stop))
note "serving on Neon; downtime ${R[downtime_s]}s"
# 6. box database off (kept), measures, logs, post check.
docker stop -t 60 "$MENIVOR_DB_CONTAINER" >/dev/null || note "could not stop $MENIVOR_DB_CONTAINER (stop it by hand)"
sleep "$NCUT_SETTLE_S"
local after_mem
after_mem="$(ncut_host_mem)"
R[host_used_mib_after]="${after_mem%% *}"
if [[ "${before_mem%% *}" =~ ^[0-9]+$ && "${after_mem%% *}" =~ ^[0-9]+$ ]]; then
R[ram_freed_mib]=$((${before_mem%% *} - ${after_mem%% *}))
fi
R[capacity_line]="| $(date -u +%F) | box 1 | menivor-db-1 stopped after the Neon cutover (MG9) | db container used $db_mem; host used ${before_mem%% *} MiB before, ${after_mem%% *} MiB after (${R[ram_freed_mib]:-n/a} MiB freed) |"
install -d "$(dirname "$NCUT_FLIPS_LOG")"
printf '%s\tmenivor-db-neon-cutover\n' "${R[serving_at]}" >>"$NCUT_FLIPS_LOG"
if ((POST_DRILL)) && [[ -x "$NCUT_RESTORE_DRILL" && -r "$NCUT_DRILL_ENV" ]]; then
local expects=()
for c in credit_ledger wallet_ledger_entries users; do
[[ -n "${R[count_$c]:-}" ]] && expects+=(--expect "$c=${R[count_$c]}")
done
# A branch needs a moment of history after the time it is taken at.
sleep 5
if "$NCUT_RESTORE_DRILL" --mode neon-branch --at "$verified_at" --env-file "$NCUT_DRILL_ENV" \
"${expects[@]}" --report "$NCUT_WORK/post-drill.json" >&2; then
R[post_drill]=PASS
else
R[post_drill]=FAIL
note "post-cutover Neon branch check FAILED (the stack is serving; see $NCUT_WORK/post-drill.json)"
fi
else
R[post_drill]=skipped
note "post-cutover Neon branch check skipped (needs $NCUT_RESTORE_DRILL and $NCUT_DRILL_ENV)"
fi
write_report PASS "Menivor serves from Neon; downtime ${R[downtime_s]}s; ${R[verify_rows]} rows verified"
}
case "$MODE" in
preflight) preflight; write_report PASS "preflight passed" ;;
rehearse) rehearse ;;
cutover) cutover ;;
esac