WebsiteBench / tasks /etsy /environment /reference /clone /backend /site_backend_integration.py
AgPerry's picture
Add files using upload-large-folder tool
9f517f2 verified
Raw History Blame Contribute Delete
7.57 kB
"""Generated, site-bound backend integration seam."""
from __future__ import annotations
import importlib
import json
import os
import sqlite3
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 = "etsy.sqlite3"
CANONICAL_DATABASE_FILENAME = "websitebench-etsy.sqlite3"
LEGACY_BACKUP_SUFFIX = ".etsy-unbound-legacy"
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_etsy_prefix_connection(connection: sqlite3.Connection) -> None:
"""Verify Etsy's own ordered business migrations before copy binding."""
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 Etsy source is already site-bound")
if "clawbench_site_binding" in tables:
raise SiteBindingError("Etsy database uses the other runtime namespace")
if not {"schema_migrations", "listings", "accounts"}.issubset(tables):
raise SiteBindingError(
"unbound database does not match the Etsy business schema"
)
rows = connection.execute(
"SELECT version,name FROM schema_migrations ORDER BY version"
).fetchall()
from backend.db import MIGRATIONS
expected = [(version, name) for version, name, _action in MIGRATIONS]
actual = [(str(row[0]), str(row[1])) for row in rows]
if not actual or actual != expected[: len(actual)]:
raise SiteBindingError("unbound database has an invalid Etsy migration prefix")
def _bind_legacy_etsy_copy(
source: Path,
canonical: Path,
*,
site_id: str,
) -> bool:
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()),
)
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("Etsy 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("Etsy 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_etsy_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(
database_path: Path | None = None,
) -> tuple[SiteBackend, LocalAuthStore]:
"""Open one bound database; never omit the site id for permanent auth.
Etsy predates the shared runtime. Its business schema is initialized
before this seam is called; the one-time legacy path binds that same file
to Etsy and adds the WebsiteBench payment ledger. Every later open fails
closed if the database belongs to another site.
"""
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 = (
str(database_path.resolve())
if database_path is not None
else os.environ.get("WEBSITEBENCH_SITE_BACKEND_DATABASE")
)
if deployed_database is None:
backend = SiteBackend.open(
runtime_path,
migration_hook=migration_hook,
seed_hook=seed_hook,
)
else:
database_path = Path(deployed_database).resolve()
if database_path.name != runtime.database_filename:
raise RuntimeError(
"deployed database filename does not match runtime contract"
)
legacy_database = database_path.with_name(LEGACY_DATABASE_FILENAME)
if not database_path.exists() and legacy_database.exists():
_bind_legacy_etsy_copy(
legacy_database,
database_path,
site_id=runtime.site_id,
)
backend = SiteBackend.open(
json.loads(runtime_path.read_text(encoding="utf-8")),
data_root=database_path.parent,
migration_hook=migration_hook,
seed_hook=seed_hook,
)
if backend.lifecycle.database_path != database_path:
raise RuntimeError(
"deployed database path does not match backend preflight"
)
backend.lifecycle.initialize()
auth = LocalAuthStore(
backend.lifecycle.database_path,
site_id=backend.config.site_id,
)
# Etsy's existing clone auth runtime owns its historical local-auth
# schema. The WebsiteBench seam is opened here for site binding/payment,
# but must not pre-create a conflicting auth schema before the app opens
# its site-owned compatibility store.
return backend, auth