File size: 5,146 Bytes
a1c39ac | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | """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
|