File size: 11,452 Bytes
842d5f6 | 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 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | """Generated, site-bound backend integration seam."""
from __future__ import annotations
import importlib
import json
import os
import sqlite3
import threading
from contextlib import closing
from pathlib import Path
from typing import Any, Callable
from websitebench.local_clone_auth import LocalAuthStore
from websitebench.site_backend import SiteBackend, SiteBindingError, load_runtime
from websitebench.site_backend.copy_cutover import (
CopyCutoverError,
publish_transformed_sqlite_copy,
)
from websitebench.site_backend.database import BASE_SCHEMA, utc_now
DEFAULT_RUNTIME_PATH = Path(__file__).resolve().parents[2] / "backend" / "runtime.json"
LEGACY_DATABASE_FILENAME = "capterra.sqlite3"
CANONICAL_DATABASE_FILENAME = "websitebench-capterra.sqlite3"
LEGACY_BACKUP_SUFFIX = ".capterra-unbound-legacy"
class CapterraAuthStore(LocalAuthStore):
"""Keep OTP material process-local across in-process app restarts."""
_process_mail_secrets: dict[tuple[str, str, str], str] = {}
_process_mail_lock = threading.RLock()
def ensure_schema(self) -> None:
if not self._schema_ready and _auth_schema_is_current(
self.database_path, self.site_id
):
self._schema_ready = True
super().ensure_schema()
def _process_key(self, purpose: str, flow_id: str) -> tuple[str, str, str]:
self._mail_secret_key(purpose, flow_id)
return str(self.database_path.resolve()), purpose, flow_id
def _remember_mail_code(self, purpose: str, flow_id: str, code: str) -> None:
super()._remember_mail_code(purpose, flow_id, code)
normalized = super()._mail_code(purpose, flow_id)
if normalized is None:
raise RuntimeError("mail code was not retained in process memory")
with self._process_mail_lock:
self._process_mail_secrets[self._process_key(purpose, flow_id)] = normalized
def _mail_code(self, purpose: str, flow_id: str) -> str | None:
current = super()._mail_code(purpose, flow_id)
if current is not None:
return current
with self._process_mail_lock:
return self._process_mail_secrets.get(self._process_key(purpose, flow_id))
def _clear_mail_secrets(self) -> None:
database_prefix = str(self.database_path.resolve())
with self._process_mail_lock:
for key in list(self._process_mail_secrets):
if key[0] == database_prefix:
del self._process_mail_secrets[key]
super()._clear_mail_secrets()
def reconcile_mail(self, *, worker_token: str | None = None) -> None:
super().reconcile_mail(worker_token=worker_token)
with self.connect() as connection, self._transaction(connection):
connection.execute(
"UPDATE local_auth_mail_outbox "
"SET last_error='startup claim replay' "
"WHERE last_error='startup-claim-replay'"
)
def _auth_schema_is_current(database_path: Path, site_id: str | None) -> bool:
"""Recognize a bound v4 auth schema without mutating persisted rows."""
if not database_path.is_file():
return False
try:
with sqlite3.connect(database_path) as connection:
binding = connection.execute(
"SELECT site_id FROM websitebench_site_binding WHERE singleton=1"
).fetchone()
versions = {
str(row[0])
for row in connection.execute(
"SELECT version FROM local_auth_schema_migrations"
).fetchall()
}
except sqlite3.DatabaseError:
return False
binding_matches = (
binding is not None
and isinstance(binding[0], str)
and (site_id is None or binding[0] == site_id)
)
return binding_matches and versions.issuperset({"0001", "0002", "0003", "0004"})
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 _legacy_capterra_prefix_connection(
connection: sqlite3.Connection,
) -> None:
"""Verify the exact site-owned migration prefix before copy adoption."""
tables = {
str(row[0])
for row in connection.execute(
"SELECT name FROM sqlite_master WHERE type='table'"
)
}
if "websitebench_site_binding" in tables:
raise SiteBindingError("legacy Capterra source is already site-bound")
if "clawbench_site_binding" in tables:
raise SiteBindingError("Capterra database uses the other runtime namespace")
if not {"schema_migrations", "products", "accounts"}.issubset(tables):
raise SiteBindingError(
"unbound database does not match the Capterra business schema"
)
rows = connection.execute(
"SELECT version,name FROM schema_migrations ORDER BY version"
).fetchall()
from backend.db import MIGRATIONS
expected = [(migration.version, migration.name) for migration in MIGRATIONS]
actual = [(int(row[0]), str(row[1])) for row in rows]
if not actual or actual != expected[: len(actual)]:
raise SiteBindingError(
"unbound database has an invalid Capterra migration prefix"
)
def _bind_legacy_capterra_copy(
source: Path,
canonical: Path,
*,
site_id: str,
migration_declaration: str | None,
migration_hook: Callable[[sqlite3.Connection], None] | None,
) -> bool:
"""Copy-upgrade one verified Capterra migration-prefix database."""
if not source.exists():
return False
def transform(database: Path) -> None:
with closing(sqlite3.connect(database, isolation_level=None)) as connection:
connection.execute("PRAGMA foreign_keys=ON")
connection.executescript(BASE_SCHEMA)
connection.execute("BEGIN IMMEDIATE")
try:
connection.execute(
"INSERT INTO websitebench_site_binding"
"(singleton,site_id,bound_at) VALUES (1,?,?)",
(site_id, utc_now()),
)
if migration_declaration is not None:
if migration_hook is None:
raise SiteBindingError("Capterra migration hook is unavailable")
migration_hook(connection)
connection.execute(
"INSERT INTO websitebench_backend_migrations"
"(migration_id,applied_at) VALUES (?,?)",
(f"site-migration:{migration_declaration}", utc_now()),
)
connection.execute(
"INSERT OR IGNORE INTO websitebench_backend_migrations"
"(migration_id,applied_at) VALUES ('site-backend-v1',?)",
(utc_now(),),
)
if connection.execute("PRAGMA foreign_key_check").fetchall():
raise SiteBindingError("Capterra copy has foreign-key violations")
connection.execute("COMMIT")
except BaseException:
if connection.in_transaction:
connection.execute("ROLLBACK")
raise
def validate_canonical(database: Path) -> None:
with closing(sqlite3.connect(database)) as connection:
binding = connection.execute(
"SELECT singleton,site_id FROM websitebench_site_binding"
).fetchall()
integrity = connection.execute("PRAGMA integrity_check").fetchall()
foreign_keys = connection.execute("PRAGMA foreign_key_check").fetchall()
if binding != [(1, site_id)] or integrity != [("ok",)] or foreign_keys:
raise SiteBindingError("Capterra copy failed integrity validation")
try:
publish_transformed_sqlite_copy(
source,
canonical,
expected_source_name=LEGACY_DATABASE_FILENAME,
expected_canonical_name=CANONICAL_DATABASE_FILENAME,
transform=transform,
validate_source=_legacy_capterra_prefix_connection,
validate_canonical=validate_canonical,
reserved_paths=(source.with_name(source.name + LEGACY_BACKUP_SUFFIX),),
)
except CopyCutoverError as exc:
raise SiteBindingError(str(exc)) from exc
return True
def open_site_services(
*,
mail_mode: str = "LOCAL_ONLY",
mail_worker_token: str | None = None,
database_path: Path | None = None,
) -> tuple[SiteBackend, LocalAuthStore]:
"""Open one bound database; never omit the site id for permanent auth."""
runtime_path = Path(
os.environ.get(
"WEBSITEBENCH_SITE_BACKEND_RUNTIME",
str(DEFAULT_RUNTIME_PATH),
)
).resolve()
runtime = load_runtime(runtime_path)
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 not None:
if selected_database.name != runtime.database_filename:
raise RuntimeError(
"deployed database filename does not match runtime contract"
)
legacy_database = selected_database.with_name(LEGACY_DATABASE_FILENAME)
if not selected_database.exists() and legacy_database.exists():
_bind_legacy_capterra_copy(
legacy_database,
selected_database,
site_id=runtime.site_id,
migration_declaration=runtime.migration_hook,
migration_hook=migration_hook,
)
if selected_database is None:
backend = SiteBackend.open(
runtime_path,
migration_hook=migration_hook,
seed_hook=seed_hook,
)
else:
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()
auth = CapterraAuthStore(
backend.lifecycle.database_path,
site_id=backend.config.site_id,
mail_mode=mail_mode,
mail_worker_token=mail_worker_token,
)
if _auth_schema_is_current(backend.lifecycle.database_path, backend.config.site_id):
auth._schema_ready = True
auth.ensure_schema()
return backend, auth
|