"""Generated, site-bound backend integration seam.""" from __future__ import annotations import importlib import json import os import secrets import sqlite3 from pathlib import Path from typing import Any, Callable from websitebench.local_clone_auth import ( MAIL_LOCAL_ONLY, MAIL_SMTP_PENDING, LocalAuthStore, ) from websitebench.site_backend import SiteBackend, load_runtime DEFAULT_RUNTIME_PATH = ( Path(__file__).resolve().parents[2] / "backend" / "runtime.json" ) DEFAULT_DEPLOYMENT_PROFILE = "offline-harbor" _AUTH_MAIL_WORKER_TOKEN = secrets.token_urlsafe(32) def auth_mail_worker_token() -> str: """Return process-local mail-worker authority without persisting it.""" return _AUTH_MAIL_WORKER_TOKEN def _declared_hook( declaration: str | None, ) -> Callable[[sqlite3.Connection], None] | None: if declaration is None: return None module_name, function_name = declaration.split(":", 1) module = importlib.import_module(module_name) hook: Any = getattr(module, function_name, None) if not callable(hook): raise RuntimeError(f"declared backend hook is not callable: {declaration}") actual = f"{hook.__module__}:{hook.__name__}" if actual != declaration: raise RuntimeError( f"declared backend hook resolved as {actual!r}, expected {declaration!r}" ) return hook def resolve_runtime_path() -> Path: return Path( os.environ.get( "WEBSITEBENCH_SITE_BACKEND_RUNTIME", str(DEFAULT_RUNTIME_PATH), ) ).absolute() def open_site_services( *, database_path: Path | None = None, auth_now: Callable[[], int] | None = None, mail_worker_token: str | None = None, ) -> tuple[SiteBackend, LocalAuthStore]: """Open one bound database; never omit the site id for permanent auth.""" runtime_path = resolve_runtime_path() runtime = load_runtime(runtime_path) profile_name = os.environ.get( "WEBSITEBENCH_BACKEND_PROFILE", DEFAULT_DEPLOYMENT_PROFILE ).strip() or DEFAULT_DEPLOYMENT_PROFILE profile = runtime.deployment["profiles"].get(profile_name) if profile is None: raise RuntimeError("IMDb backend profile is not declared") if profile["payment_adapter"] != "local-sandbox": raise RuntimeError("IMDb has no enabled payment capability") benchmark_mailbox = bool( os.environ.get("WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL", "").strip() ) mail_mode = ( MAIL_SMTP_PENDING if benchmark_mailbox or profile["mail_adapter"] != "local-outbox" else MAIL_LOCAL_ONLY ) selected_mail_worker_token = ( (mail_worker_token or _AUTH_MAIL_WORKER_TOKEN) if mail_mode == MAIL_SMTP_PENDING else None ) migration_hook = _declared_hook(runtime.migration_hook) seed_hook = _declared_hook(runtime.seed_hook) deployed_database = os.environ.get( "WEBSITEBENCH_SITE_BACKEND_DATABASE", ) selected_database = ( Path(deployed_database).resolve() if deployed_database is not None else database_path.resolve() if database_path is not None else None ) if selected_database is None: backend = SiteBackend.open( runtime_path, migration_hook=migration_hook, seed_hook=seed_hook, ) else: if selected_database.name != runtime.database_filename: raise RuntimeError( "deployed database filename does not match runtime contract" ) backend = SiteBackend.open( json.loads(runtime_path.read_text(encoding="utf-8")), data_root=selected_database.parent, migration_hook=migration_hook, seed_hook=seed_hook, ) if backend.lifecycle.database_path != selected_database: raise RuntimeError( "deployed database path does not match backend preflight" ) backend.lifecycle.initialize() # The runtime records hook declarations once, while the immutable IMDb # catalog grows across clone releases. Re-run the declared idempotent # migration/reconciliation hook through this generated seam so an already # bound persistent database converges without replacing its user state. if migration_hook is not None: with sqlite3.connect(backend.lifecycle.database_path, timeout=30) as connection: connection.row_factory = sqlite3.Row connection.execute("PRAGMA foreign_keys=ON") connection.execute("PRAGMA busy_timeout=30000") migration_hook(connection) auth_options: dict[str, Any] = { "site_id": backend.config.site_id, "mail_mode": mail_mode, "mail_worker_token": selected_mail_worker_token, } if auth_now is not None: auth_options["now"] = auth_now auth = LocalAuthStore( backend.lifecycle.database_path, **auth_options, ) auth.ensure_schema() backend.deployment_profile_name = profile_name backend.deployment_profile = dict(profile) return backend, auth