"""Run the single-container Space. Local data is intentionally disposable.""" from __future__ import annotations import json import os from pathlib import Path import re import secrets import signal import subprocess import sys import time from urllib.parse import quote, urlsplit from urllib.request import urlopen APP = Path("/app") BACKEND = APP / "backend" FRONTEND = APP / "frontend" PYTHON = str(BACKEND / ".venv/bin/python") AUTH_KEYS = ("BETTER_AUTH_SECRET", "BACKEND_AUTH_SECRET", "APP_SETTINGS_ENCRYPTION_KEY") class StartupError(RuntimeError): pass def public_origin(env: dict[str, str]) -> str: explicit = env.get("HF_PUBLIC_URL", "").strip() host = env.get("SPACE_HOST", "").strip() if not explicit and not re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?", host): raise StartupError("Set HF_PUBLIC_URL to the Space HTTPS URL if SPACE_HOST is unavailable.") value = explicit or f"https://{host}" if re.search(r"[\s\\\x00-\x1f]", value): raise StartupError("HF_PUBLIC_URL contains invalid characters.") parsed = urlsplit(value) if (not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ("", "/") or not re.fullmatch(r"[A-Za-z0-9.-]+", parsed.hostname)): raise StartupError("HF_PUBLIC_URL must contain only a scheme and hostname.") try: port = parsed.port except ValueError as error: raise StartupError("HF_PUBLIC_URL has an invalid port.") from error local = parsed.hostname in ("localhost", "127.0.0.1") if parsed.scheme != "https" and not (local and parsed.scheme == "http"): raise StartupError("Public Space URLs must use HTTPS.") if not local and port not in (None, 443): raise StartupError("Public Space URLs must use the standard HTTPS port.") return f"{parsed.scheme}://{parsed.netloc.lower()}" def private_write(path: Path, content: str) -> None: descriptor = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) with os.fdopen(descriptor, "w", encoding="utf-8") as handle: handle.write(content) def load_secrets(directory: Path, env: dict[str, str]) -> dict[str, str]: path = directory / "secrets.json" if path.is_symlink(): raise StartupError("Refusing a symlink for runtime secrets.") if path.exists(): try: state = json.loads(path.read_text(encoding="utf-8")) except (ValueError, OSError) as error: raise StartupError("Runtime secrets cannot be read; refusing to replace them.") from error if any(not isinstance(state.get(key), str) or len(state[key]) < 32 for key in (*AUTH_KEYS, "db_password", "redis_password")): raise StartupError("Runtime secrets are invalid; refusing to overwrite existing data.") for key in AUTH_KEYS: if env.get(key) and env[key] != state[key]: raise StartupError(f"{key} differs from the existing runtime secret; restore the original value.") return state state = {"db_password": secrets.token_hex(32), "redis_password": secrets.token_hex(32)} for key in AUTH_KEYS: value = env.get(key) or secrets.token_hex(32) if len(value) < 32: raise StartupError(f"{key} must have at least 32 characters.") state[key] = value private_write(path, json.dumps(state)) return state def build_environment(env: dict[str, str], directory: Path, state: dict[str, str], origin: str) -> dict[str, str]: result = dict(env) result.update({key: state[key] for key in AUTH_KEYS}) result.update({ "HOME": "/home/user", "HF_RUNTIME_DIR": str(directory), "PYTHONPATH": str(BACKEND), "PYTHONUNBUFFERED": "1", "PYTHON_DOTENV_DISABLED": "1", "NODE_ENV": "production", "SELF_HOST": "true", "NEXT_PUBLIC_SELF_HOST": "true", "DISABLE_SIGN_UP": "true", "ALLOW_UNSIGNED_BACKEND_AUTH": "false", "BETTER_AUTH_URL": origin, "BETTER_AUTH_TRUSTED_ORIGINS": origin, "CORS_ORIGINS": origin, "NEXT_PUBLIC_APP_URL": origin, "NEXT_PUBLIC_API_URL": "/api", "BACKEND_INTERNAL_URL": "http://127.0.0.1:8000", "TEMP_DIR": str(directory / "media"), "MEDIA_STORAGE": "local", "MEDIA_FAILOVER_ENABLED": "false", "MEDIA_UPLOAD_CONCURRENCY": "1", "REDIS_HOST": "127.0.0.1", "REDIS_PORT": "6379", "REDIS_PASSWORD": state["redis_password"], "REDISCLI_AUTH": state["redis_password"], "PGPASSWORD": state["db_password"], "PORT": "3107", "HOSTNAME": "127.0.0.1", "CUDA_VISIBLE_DEVICES": "", "OMP_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1", "MKL_NUM_THREADS": "1", "NUMEXPR_NUM_THREADS": "1", "OPENCV_FOR_THREADS_NUM": "1", "SOCIAL_PUBLISHING_ACCESS": "off", }) for key, default in { "TRANSCRIPTION_PROVIDER": "whisper", "WHISPER_MODEL_SIZE": "small", "WHISPER_FAST_MODEL_SIZE": "small", "LLM": "nvidia:minimaxai/minimax-m3.1-flash", "DEFAULT_PROCESSING_MODE": "fast", "MAX_VIDEO_DURATION": "10800", "MAX_VIDEO_UPLOAD_BYTES": "4000000000", }.items(): result[key] = result.get(key) or default result["BACKEND_DATABASE_URL"] = database_url(state["db_password"], backend=True) result["FRONTEND_DATABASE_URL"] = database_url(state["db_password"], backend=False) # Never inherit an unrelated remote DB/Redis URL from another deployment. result.pop("REDIS_URL", None) return result def database_url(password: str, *, backend: bool) -> str: scheme = "postgresql+asyncpg" if backend else "postgresql" return f"{scheme}://supoclip:{quote(password, safe='')}@127.0.0.1:5432/supoclip" def nginx_config(directory: Path, origin: str) -> str: parsed = urlsplit(origin) runtime = directory.as_posix() return f"""pid {runtime}/nginx/nginx.pid; error_log /dev/stderr warn; worker_processes 1; events {{ worker_connections 256; }} http {{ include /etc/nginx/mime.types; default_type application/octet-stream; access_log off; client_body_temp_path {runtime}/nginx/body; proxy_temp_path {runtime}/nginx/proxy; fastcgi_temp_path {runtime}/nginx/fastcgi; uwsgi_temp_path {runtime}/nginx/uwsgi; scgi_temp_path {runtime}/nginx/scgi; server {{ listen 7860; server_name _; client_max_body_size 4001048576; client_body_timeout 1800s; location / {{ proxy_pass http://127.0.0.1:3107; proxy_http_version 1.1; proxy_set_header Host "{parsed.netloc}"; proxy_set_header X-Forwarded-Host "{parsed.netloc}"; proxy_set_header X-Forwarded-Proto "{parsed.scheme}"; proxy_set_header Connection ""; proxy_buffering off; proxy_request_buffering off; proxy_read_timeout 1800s; proxy_send_timeout 1800s; }} }} }} """ class Services: def __init__(self, env: dict[str, str]): self.env = env self.children: list[tuple[str, subprocess.Popen]] = [] def start(self, name: str, command: list[str], *, env=None, cwd=BACKEND): print(f"Starting {name}...", flush=True) child = subprocess.Popen(command, env=env or self.env, cwd=cwd, start_new_session=True) self.children.append((name, child)) return child def check(self): for name, child in self.children: if child.poll() is not None: raise StartupError(f"{name} exited unexpectedly; shutting down this instance.") def run(self, command: list[str], *, env=None, safe_output=False) -> str: completed = subprocess.run(command, env=env or self.env, cwd=BACKEND, capture_output=True, text=True, timeout=180) if safe_output: # Used only for the owner CLI, whose messages explicitly redact errors. if completed.stdout.strip(): print(completed.stdout.strip(), flush=True) if completed.stderr.strip(): print(completed.stderr.strip(), file=sys.stderr, flush=True) if completed.returncode: # Commands may contain DB URLs; do not include their arguments or output. raise StartupError(f"A required {Path(command[0]).name} startup step failed; no secrets were logged.") return completed.stdout.strip() def wait(self, description: str, probe, timeout=180): deadline = time.monotonic() + timeout while time.monotonic() < deadline: self.check() try: if probe(): return except (OSError, StartupError, TimeoutError): pass time.sleep(0.5) raise StartupError(f"Timed out waiting for {description}.") def stop(self): for _, child in reversed(self.children): if child.poll() is None: try: os.killpg(child.pid, signal.SIGTERM) except ProcessLookupError: pass deadline = time.monotonic() + 15 for _, child in reversed(self.children): if child.poll() is not None: continue try: child.wait(timeout=max(0.1, deadline - time.monotonic())) except subprocess.TimeoutExpired: try: os.killpg(child.pid, signal.SIGKILL) except ProcessLookupError: pass child.wait(timeout=5) def http_ready(url: str) -> bool: with urlopen(url, timeout=3) as response: return response.status == 200 def main(): if os.geteuid() == 0: raise StartupError("Run the Space as UID1000, not root.") env = dict(os.environ) password = env.get("HF_ADMIN_PASSWORD", "") if not env.get("HF_ADMIN_EMAIL", "").strip() or not 12 <= len(password) <= 128 or not password.strip(): raise StartupError("Set HF_ADMIN_EMAIL and a nonblank 12-to-128-character HF_ADMIN_PASSWORD in Space Secrets.") origin = public_origin(env) directory = Path(env.get("HF_RUNTIME_DIR", "/home/user/runtime")) if not directory.is_absolute() or not re.fullmatch(r"/[A-Za-z0-9_./-]+", str(directory)) or ".." in directory.parts: raise StartupError("HF_RUNTIME_DIR must be an absolute local path without spaces or traversal.") if directory.is_symlink(): raise StartupError("Runtime storage must not be a symlink.") directory.mkdir(mode=0o700, parents=True, exist_ok=True) directory.chmod(0o700) for subdir in ("postgres", "pg-run", "redis", "media", "nginx", "nginx/body", "nginx/proxy", "nginx/fastcgi", "nginx/uwsgi", "nginx/scgi"): (directory / subdir).mkdir(mode=0o700, parents=True, exist_ok=True) state = load_secrets(directory, env) env = build_environment(env, directory, state, origin) services = Services(env) def interrupted(_signum, _frame): raise StartupError("Shutdown requested.") signal.signal(signal.SIGTERM, interrupted) signal.signal(signal.SIGINT, interrupted) try: pgdata = directory / "postgres" if not (pgdata / "PG_VERSION").exists(): if any(pgdata.iterdir()): raise StartupError("PostgreSQL directory is nonempty but incomplete; refusing to overwrite it.") password_file = directory / "pg-password" if password_file.exists(): password_file.unlink() private_write(password_file, state["db_password"]) try: services.run(["initdb", "-D", str(pgdata), "--username=supoclip", "--auth-local=scram-sha-256", "--auth-host=scram-sha-256", f"--pwfile={password_file}", "--encoding=UTF8", "--locale=C.UTF-8"]) finally: password_file.unlink(missing_ok=True) services.start("PostgreSQL", ["postgres", "-D", str(pgdata), "-h", "127.0.0.1", "-p", "5432", "-k", str(directory / "pg-run"), "-c", "shared_buffers=128MB", "-c", "max_connections=100", "-c", "max_parallel_workers_per_gather=0"]) psql = ["psql", "-h", "127.0.0.1", "-U", "supoclip", "-v", "ON_ERROR_STOP=1", "-At"] services.wait("authenticated PostgreSQL", lambda: services.run(psql + ["-d", "postgres", "-c", "SELECT 1"]) == "1") if services.run(psql + ["-d", "postgres", "-c", "SELECT 1 FROM pg_database WHERE datname='supoclip'"]) != "1": services.run(["createdb", "-h", "127.0.0.1", "-U", "supoclip", "supoclip"]) if services.run(psql + ["-d", "supoclip", "-c", "SELECT to_regclass('public.users') IS NOT NULL"]) != "t": services.run(psql + ["-d", "supoclip", "--single-transaction", "-f", str(APP / "init.sql")]) redis_config = directory / "redis/redis.conf" if redis_config.exists(): redis_config.unlink() private_write(redis_config, f"bind 127.0.0.1\nport 6379\nprotected-mode yes\ndaemonize no\nsave \"\"\nappendonly no\nmaxmemory 256mb\nmaxmemory-policy noeviction\ndir {directory / 'redis'}\nrequirepass {state['redis_password']}\n") services.start("Redis", ["redis-server", str(redis_config)]) services.wait("Redis", lambda: services.run(["redis-cli", "-h", "127.0.0.1", "ping"]) == "PONG") backend_env = {**env, "DATABASE_URL": env["BACKEND_DATABASE_URL"], "SUPOCLIP_SERVICE": "backend"} services.start("backend", [PYTHON, "-m", "uvicorn", "src.main:app", "--host", "127.0.0.1", "--port", "8000", "--workers", "1"], env=backend_env) services.wait("backend database migrations", lambda: http_ready("http://127.0.0.1:8000/health/db")) frontend_env = {**env, "DATABASE_URL": env["FRONTEND_DATABASE_URL"]} services.run(["node", str(FRONTEND / "scripts/hf-bootstrap-owner.cjs")], env=frontend_env, safe_output=True) services.start("worker", [PYTHON, "-c", "from arq import run_worker; from src.workers.tasks import WorkerSettings; run_worker(WorkerSettings, max_jobs=1)"], env={**backend_env, "SUPOCLIP_SERVICE": "worker"}) services.start("frontend", ["node", "server.js"], env=frontend_env, cwd=FRONTEND) services.wait("frontend", lambda: http_ready("http://127.0.0.1:3107/api/auth/get-session")) services.wait("worker heartbeat", lambda: http_ready("http://127.0.0.1:8000/health/worker")) proxy_config = directory / "nginx/nginx.conf" proxy_config.write_text(nginx_config(directory, origin), encoding="utf-8") services.run(["nginx", "-t", "-c", str(proxy_config)]) services.start("public proxy", ["nginx", "-c", str(proxy_config), "-g", "daemon off;"]) print("SupoClip is ready on port7860. Open the direct Space URL and sign in with your owner credentials.", flush=True) print("Storage is temporary: download finished clips before stopping or rebuilding the Space.", flush=True) while True: services.check() time.sleep(1) finally: signal.signal(signal.SIGTERM, signal.SIG_IGN) signal.signal(signal.SIGINT, signal.SIG_IGN) services.stop() if __name__ == "__main__": try: main() except StartupError as error: print(str(error), file=sys.stderr, flush=True) raise SystemExit(1) except Exception: print("Space startup failed. Review service logs; credentials were not printed by the launcher.", file=sys.stderr, flush=True) raise SystemExit(1)