acupedia-api/app/bootstrap/orchestrator.py

265 lines
8.2 KiB
Python

from __future__ import annotations
from collections.abc import Awaitable, Callable
from pathlib import Path
from typing import Any
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from .adapters import (
AuthBootstrapAdapter,
CommerceBootstrapAdapter,
ContentBootstrapAdapter,
MediaBootstrapAdapter,
)
from .result import BootstrapRunResult, StepResult
from .validation import BootstrapValidator
class BootstrapOrchestrator:
"""
Deterministic orchestration over bounded-context seeders.
The orchestrator coordinates ordering and transaction boundaries only.
It does not absorb bounded-context seeding rules.
"""
def __init__(
self,
session_factory: async_sessionmaker[AsyncSession],
) -> None:
self.session_factory = session_factory
self.auth = AuthBootstrapAdapter()
self.content = ContentBootstrapAdapter()
self.media = MediaBootstrapAdapter()
self.commerce = CommerceBootstrapAdapter()
self.validator = BootstrapValidator()
async def run_auth(
self,
*,
bootstrap_admin: Any | None = None,
) -> BootstrapRunResult:
details = await self._transaction(
lambda session: self.auth.run(
session,
bootstrap_admin=bootstrap_admin,
)
)
return self._success("auth", "auth", details)
async def run_content(
self,
*,
config_path: Path,
modules_root: Path,
module_codes: set[str] | None = None,
template_codes: set[str] | None = None,
content_codes: set[str] | None = None,
search_facets_only: bool = False,
skip_search_facets: bool = False,
publish_content: bool = False,
cleanup: bool = False,
cleanup_mode: str | None = None,
continue_on_error: bool = False,
created_by: UUID | None = None,
) -> BootstrapRunResult:
async with self.session_factory() as session:
details = await self.content.run(
session,
config_path=config_path,
modules_root=modules_root,
module_codes=module_codes,
template_codes=template_codes,
content_codes=content_codes,
search_facets_only=search_facets_only,
skip_search_facets=skip_search_facets,
publish_content=publish_content,
cleanup=cleanup,
cleanup_mode=cleanup_mode,
continue_on_error=continue_on_error,
created_by=created_by,
)
return self._success("content", "content", details)
async def run_media(
self,
*,
manifest_path: Path,
media_root: Path,
storage: Any,
bucket: str,
validate_only: bool = False,
dry_run: bool = False,
force_reupload: bool = False,
) -> BootstrapRunResult:
async with self.session_factory() as session:
details = await self.media.run(
session,
manifest_path=manifest_path,
media_root=media_root,
storage=storage,
bucket=bucket,
validate_only=validate_only,
dry_run=dry_run,
force_reupload=force_reupload,
)
step_status = "success" if bool(details.get("ok", True)) else "failed"
return BootstrapRunResult(
command="media",
status=step_status,
steps=[
StepResult(
name="media",
status=step_status,
details=details,
)
],
)
async def run_commerce(
self,
*,
plans_path: Path | None = None,
plans: Any = None,
coupons: Any = None,
) -> BootstrapRunResult:
details = await self._transaction(
lambda session: self.commerce.run(
session,
plans_path=plans_path,
plans=plans,
coupons=coupons,
)
)
return self._success("commerce", "commerce", details)
async def run_validate(self) -> BootstrapRunResult:
async with self.session_factory() as session:
validation = await self.validator.validate(session)
step = StepResult(
name="validate",
status="success" if validation.ok else "failed",
details={
**validation.details,
"missing_tables": list(validation.missing_tables),
},
)
return BootstrapRunResult(
command="validate",
status=step.status,
steps=[step],
)
async def run_all(
self,
*,
bootstrap_admin: Any | None = None,
content_config_path: Path,
modules_root: Path,
media_manifest_path: Path,
media_root: Path,
storage: Any,
bucket: str,
module_codes: set[str] | None = None,
template_codes: set[str] | None = None,
content_codes: set[str] | None = None,
search_facets_only: bool = False,
skip_search_facets: bool = False,
publish_content: bool = False,
continue_on_error: bool = False,
created_by: UUID | None = None,
validate_only: bool = False,
dry_run: bool = False,
force_reupload: bool = False,
plans_path: Path | None = None,
plans: Any = None,
coupons: Any = None,
) -> BootstrapRunResult:
combined = BootstrapRunResult(
command="all",
status="success",
)
results = (
await self.run_auth(bootstrap_admin=bootstrap_admin),
await self.run_content(
config_path=content_config_path,
modules_root=modules_root,
module_codes=module_codes,
template_codes=template_codes,
content_codes=content_codes,
search_facets_only=search_facets_only,
skip_search_facets=skip_search_facets,
publish_content=publish_content,
continue_on_error=continue_on_error,
created_by=created_by,
),
await self.run_media(
manifest_path=media_manifest_path,
media_root=media_root,
storage=storage,
bucket=bucket,
validate_only=validate_only,
dry_run=dry_run,
force_reupload=force_reupload,
),
)
for result in results:
combined.steps.extend(result.steps)
if result.status != "success":
combined.status = "failed"
return combined
commerce_result = await self.run_commerce(
plans_path=plans_path,
plans=plans,
coupons=coupons,
)
combined.steps.extend(commerce_result.steps)
if commerce_result.status != "success":
combined.status = "failed"
return combined
validate_result = await self.run_validate()
combined.steps.extend(validate_result.steps)
if validate_result.status != "success":
combined.status = "failed"
return combined
async def _transaction(
self,
fn: Callable[[AsyncSession], Awaitable[dict[str, object]]],
) -> dict[str, object]:
async with self.session_factory() as session:
try:
details = await fn(session)
await session.commit()
return details
except Exception:
await session.rollback()
raise
@staticmethod
def _success(
command: str,
step_name: str,
details: dict[str, object],
) -> BootstrapRunResult:
return BootstrapRunResult(
command=command,
status="success",
steps=[
StepResult(
name=step_name,
status="success",
details=details,
)
],
)