videogen/scripts/cloud-runtime-env.py
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

191 lines
6.5 KiB
Python

#!/usr/bin/env python3
"""Run one backend with the repo cloud profile without printing secrets."""
from __future__ import annotations
import argparse
import os
import re
import subprocess
import sys
from pathlib import Path
from urllib.parse import urlsplit, urlunsplit
_KEY = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_DATABASE_OVERRIDES = {
"reelforge": "REELFORGE_DATABASE_URL",
"mint": "MINT_DATABASE_URL",
"vend": "VEND_DATABASE_URL",
"ledgerline": "LEDGERLINE_DATABASE_URL",
"relay": "RELAY_DATABASE_URL",
}
_STORAGE_PROFILES = frozenset({"reelforge", "relay"})
def _parse_dotenv(path: Path) -> dict[str, str]:
parsed: dict[str, str] = {}
for raw in path.read_text(encoding="utf-8").splitlines():
line = raw.strip()
if not line or line.startswith("#"):
continue
if line.startswith("export "):
line = line[7:].strip()
key, separator, value = line.partition("=")
key = key.strip()
if not separator or not _KEY.fullmatch(key):
continue
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
value = value[1:-1]
parsed.setdefault(key, value)
return parsed
def _first(env: dict[str, str], *names: str) -> str:
for name in names:
value = env.get(name, "").strip()
if value:
return value
return ""
def _sqlalchemy_url(url: str) -> str:
if url.startswith("postgres://"):
return "postgresql+psycopg://" + url[len("postgres://") :]
if url.startswith("postgresql://"):
return "postgresql+psycopg://" + url[len("postgresql://") :]
return url
def _valid_postgres_url(url: str) -> bool:
try:
parsed = urlsplit(url)
except ValueError:
return False
return (
parsed.scheme in {"postgres", "postgresql", "postgresql+psycopg"}
and bool(parsed.hostname)
and not any(char.isspace() for char in url)
)
def _s3_origin(endpoint: str, bucket: str) -> str | None:
try:
parsed = urlsplit(endpoint.strip().rstrip("/"))
except ValueError:
return None
if parsed.scheme != "https" or not parsed.netloc or parsed.query or parsed.fragment:
return None
path = parsed.path.rstrip("/")
if path == f"/{bucket}":
path = ""
elif path:
return None
return urlunsplit((parsed.scheme, parsed.netloc, path, "", ""))
def build_environment(profile: str, dotenv: Path) -> tuple[dict[str, str], list[str]]:
# Ambient variables were deliberately supplied to this process and remain
# available to the child. Dotenv values are only a source: copy the small
# cloud subset needed by this profile, never every secret in the file.
env = dict(os.environ)
source = _parse_dotenv(dotenv) if dotenv.is_file() else {}
source.update(env)
errors: list[str] = []
database_url = _first(source, _DATABASE_OVERRIDES[profile], "DATABASE_URL")
if not database_url:
errors.append(f"missing {_DATABASE_OVERRIDES[profile]} or DATABASE_URL")
elif not _valid_postgres_url(database_url):
errors.append(
"database setting must be a postgres:// or postgresql:// URL, "
"not a psql command"
)
else:
env["DATABASE_URL"] = database_url
if profile == "reelforge":
env["NEON_DATABASE_URL"] = _sqlalchemy_url(database_url)
elif profile == "relay":
env["TENSORZERO_POSTGRES_URL"] = database_url
if profile in _STORAGE_PROFILES:
product_bucket = (
"REELFORGE_R2_BUCKET_NAME" if profile == "reelforge" else "RELAY_R2_BUCKET_NAME"
)
bucket = _first(source, product_bucket, "R2_BUCKET_NAME", "R2_BUCKET")
endpoint = _first(source, "R2_S3_ENDPOINT")
for name in ("R2_ACCOUNT_ID", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY"):
value = _first(source, name)
if not value:
errors.append(f"missing {name}")
else:
env[name] = value
if not bucket:
errors.append(
f"missing {product_bucket}, R2_BUCKET_NAME, or R2_BUCKET"
)
else:
env["R2_BUCKET_NAME"] = bucket
env["R2_BUCKET"] = bucket
if not endpoint:
account_id = _first(source, "R2_ACCOUNT_ID")
if account_id:
endpoint = f"https://{account_id}.r2.cloudflarestorage.com"
else:
errors.append("missing R2_S3_ENDPOINT (cannot derive without R2_ACCOUNT_ID)")
if endpoint and bucket:
normalized_endpoint = _s3_origin(endpoint, bucket)
if normalized_endpoint is None:
errors.append(
"R2_S3_ENDPOINT must be an HTTPS S3 origin without a path "
"other than the configured bucket name"
)
else:
env["R2_S3_ENDPOINT"] = normalized_endpoint
if profile == "relay":
# Relay gives S3_* priority; do not overwrite AWS provider keys
# used independently by Bedrock or SageMaker.
access_key = _first(source, "R2_ACCESS_KEY_ID")
secret_key = _first(source, "R2_SECRET_ACCESS_KEY")
if access_key:
env["S3_ACCESS_KEY_ID"] = access_key
if secret_key:
env["S3_SECRET_ACCESS_KEY"] = secret_key
elif profile == "reelforge":
public_base_url = _first(source, "R2_PUBLIC_BASE_URL")
if public_base_url:
env["R2_PUBLIC_BASE_URL"] = public_base_url
return env, errors
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("profile", choices=sorted(_DATABASE_OVERRIDES))
parser.add_argument(
"--env-file",
type=Path,
default=Path(__file__).resolve().parents[1] / ".env",
)
parser.add_argument("--check", action="store_true")
args, command = parser.parse_known_args()
env, errors = build_environment(args.profile, args.env_file)
if errors:
for error in errors:
print(f"cloud profile error: {error}", file=sys.stderr)
return 2
if args.check:
print(f"cloud profile {args.profile}: configuration present (values hidden)")
return 0
if command and command[0] == "--":
command = command[1:]
if not command:
parser.error("a command is required unless --check is used")
return subprocess.run(command, env=env, check=False).returncode
if __name__ == "__main__":
raise SystemExit(main())