432 lines
19 KiB
Python
432 lines
19 KiB
Python
from __future__ import annotations
|
|
|
|
import logging
|
|
from pathlib import Path
|
|
from uuid import UUID
|
|
|
|
from sqlalchemy import text
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from .schema import CONTENT_SCHEMA, resolve_content_schema
|
|
|
|
from .contents import ContentSeeder
|
|
from .cleanup import ModuleContentCleaner
|
|
from .definitions import AttributeDefinitionSeeder
|
|
from .models import ModuleProcessSummary
|
|
from .modules import ModuleSeeder
|
|
from .presentation import TemplatePresentationSeeder
|
|
from .search_facets import SearchFacetSeeder
|
|
from .validators import ModuleValidationError, load_json, parse_config_document, parse_module_manifest
|
|
|
|
logger = logging.getLogger("acupedia.seed")
|
|
|
|
|
|
class SeedOrchestrator:
|
|
"""Coordinate module seeding with bounded transaction scopes.
|
|
|
|
Transaction policy:
|
|
* module metadata is committed independently;
|
|
* each content-mapping/template is one transaction and one commit;
|
|
* a failed template rolls back only that template;
|
|
* final stale-association reconciliation is committed independently and
|
|
is skipped when any template failed, preventing destructive cleanup
|
|
from an incomplete desired-content set.
|
|
|
|
ContentSeeder retains its row-level SAVEPOINTs. Those SAVEPOINTs provide
|
|
per-row recovery when continue_on_error=True, while the surrounding
|
|
template transaction provides the durable commit boundary.
|
|
"""
|
|
|
|
def __init__(self, session: AsyncSession, *, schema: str = CONTENT_SCHEMA) -> None:
|
|
self._session = session
|
|
self._schema = resolve_content_schema(schema)
|
|
self._definitions = AttributeDefinitionSeeder(session, schema=self._schema)
|
|
self._contents = ContentSeeder(session, schema=self._schema)
|
|
self._modules = ModuleSeeder(session, schema=self._schema)
|
|
self._presentations = TemplatePresentationSeeder(session, schema=self._schema)
|
|
self._search_facets = SearchFacetSeeder(session, schema=self._schema)
|
|
|
|
async def process_config(
|
|
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,
|
|
) -> tuple[ModuleProcessSummary, ...]:
|
|
entries = parse_config_document(load_json(config_path), modules_root=modules_root)
|
|
summaries: list[ModuleProcessSummary] = []
|
|
|
|
if cleanup and cleanup_mode is not None:
|
|
raise ModuleValidationError(
|
|
"cleanup alias cannot be combined with an explicit cleanup mode"
|
|
)
|
|
|
|
effective_cleanup_mode = "archive" if cleanup else cleanup_mode
|
|
if effective_cleanup_mode is not None:
|
|
if effective_cleanup_mode not in {"archive", "delete"}:
|
|
raise ModuleValidationError(
|
|
f"unsupported cleanup mode: {effective_cleanup_mode!r}"
|
|
)
|
|
if not module_codes or len(module_codes) != 1:
|
|
raise ModuleValidationError(
|
|
"cleanup requires exactly one module code"
|
|
)
|
|
if template_codes or content_codes:
|
|
raise ModuleValidationError(
|
|
"cleanup cannot be combined with template/content selectors; "
|
|
"cleanup removes the entire selected module content set before reseeding"
|
|
)
|
|
if search_facets_only:
|
|
raise ModuleValidationError(
|
|
"cleanup cannot be combined with search-facets-only mode"
|
|
)
|
|
|
|
for entry in entries:
|
|
if module_codes and entry.code not in module_codes:
|
|
continue
|
|
|
|
if effective_cleanup_mode is not None:
|
|
async with self._session.begin():
|
|
cleanup_result = await ModuleContentCleaner(
|
|
self._session, schema=self._schema
|
|
).cleanup(entry.code, mode=effective_cleanup_mode)
|
|
await self._session.execute(text("SET CONSTRAINTS ALL IMMEDIATE"))
|
|
|
|
logger.info(
|
|
"Cleaned module bootstrap state: mode=%s module=%s definition_sets=%s "
|
|
"contents=%s search_facets=%s search_documents=%s associations=%s "
|
|
"content_items=%s definitions=%s members_removed=%s "
|
|
"presentation_contracts=%s search_mappings=%s",
|
|
effective_cleanup_mode,
|
|
cleanup_result.module_code,
|
|
cleanup_result.definition_set_count,
|
|
cleanup_result.content_count,
|
|
cleanup_result.search_facet_count,
|
|
cleanup_result.search_document_count,
|
|
cleanup_result.module_content_count,
|
|
cleanup_result.content_item_count,
|
|
cleanup_result.definition_count,
|
|
cleanup_result.definition_member_count,
|
|
cleanup_result.presentation_contract_count,
|
|
cleanup_result.search_facet_mapping_count,
|
|
)
|
|
|
|
try:
|
|
summaries.append(
|
|
await self.process_module(
|
|
config=entry,
|
|
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,
|
|
)
|
|
)
|
|
except Exception:
|
|
# No module-wide transaction exists here. Any successfully
|
|
# committed templates remain durable by design.
|
|
if self._session.in_transaction():
|
|
await self._session.rollback()
|
|
logger.exception("Module processing failed: %s", entry.code)
|
|
if not continue_on_error:
|
|
raise
|
|
|
|
return tuple(summaries)
|
|
|
|
async def _process_search_facets_only(self, *, config) -> ModuleProcessSummary:
|
|
"""Seed/reconcile only a module's canonical search facets and reindex.
|
|
|
|
This mode intentionally does not upsert module metadata, definitions,
|
|
presentations, content, or module_contents. All prerequisites must
|
|
already exist in the database.
|
|
"""
|
|
search_facets_path = config.path / "search_facets.json"
|
|
if not search_facets_path.exists():
|
|
raise ModuleValidationError(
|
|
f"search_facets.json does not exist for {config.code}: "
|
|
f"{search_facets_path}"
|
|
)
|
|
|
|
async with self._session.begin():
|
|
module_result = await self._session.execute(
|
|
text(
|
|
f"""
|
|
select id, code, slug
|
|
from {self._schema}.modules
|
|
where code = :code
|
|
"""
|
|
),
|
|
{"code": config.code},
|
|
)
|
|
module_row = module_result.mappings().one_or_none()
|
|
if module_row is None:
|
|
raise ModuleValidationError(
|
|
f"Cannot seed search facets only; module does not exist: {config.code}"
|
|
)
|
|
|
|
facet_count, facet_mapping_count = await self._search_facets.seed_file(
|
|
search_facets_path,
|
|
module_code=config.code,
|
|
)
|
|
await self._session.execute(text("SET CONSTRAINTS ALL IMMEDIATE"))
|
|
|
|
logger.info(
|
|
"Committed search facets only: module=%s facets=%s mappings=%s",
|
|
config.code,
|
|
facet_count,
|
|
facet_mapping_count,
|
|
)
|
|
|
|
return ModuleProcessSummary(
|
|
module_id=module_row["id"],
|
|
module_code=module_row["code"],
|
|
module_slug=module_row["slug"],
|
|
definition_sets_processed=0,
|
|
content_rows_succeeded=0,
|
|
content_rows_failed=0,
|
|
associations_written=0,
|
|
stale_associations_removed=0,
|
|
presentation_contracts_processed=0,
|
|
errors=(),
|
|
)
|
|
|
|
async def process_module(
|
|
self,
|
|
*,
|
|
config,
|
|
template_codes: set[str] | None,
|
|
content_codes: set[str] | None,
|
|
search_facets_only: bool,
|
|
skip_search_facets: bool,
|
|
publish_content: bool,
|
|
continue_on_error: bool,
|
|
created_by: UUID | None,
|
|
) -> ModuleProcessSummary:
|
|
module_json_path = config.path / "module.json"
|
|
if not module_json_path.exists():
|
|
raise ModuleValidationError(
|
|
f"module.json does not exist for {config.code}: {module_json_path}"
|
|
)
|
|
|
|
if search_facets_only:
|
|
return await self._process_search_facets_only(config=config)
|
|
|
|
manifest = parse_module_manifest(load_json(module_json_path), module_dir=config.path)
|
|
|
|
requested_template_codes = (
|
|
{code.strip().lower() for code in template_codes if code.strip()}
|
|
if template_codes
|
|
else None
|
|
)
|
|
if requested_template_codes:
|
|
manifest_codes = {mapping.code for mapping in manifest.content_mapping}
|
|
missing_template_codes = requested_template_codes - manifest_codes
|
|
if missing_template_codes:
|
|
raise ModuleValidationError(
|
|
f"Requested template code(s) are not mapped by module {config.code}: "
|
|
+ ", ".join(sorted(missing_template_codes))
|
|
)
|
|
|
|
partial_run = bool(requested_template_codes or content_codes)
|
|
|
|
# Module metadata has its own short transaction so every template can
|
|
# subsequently reference a durable module row.
|
|
async with self._session.begin():
|
|
module_result = await self._modules.upsert_module(config=config, manifest=manifest)
|
|
await self._session.execute(text("SET CONSTRAINTS ALL IMMEDIATE"))
|
|
|
|
desired_content_ids: set[UUID] = set()
|
|
next_sort_order = 0
|
|
definition_sets_processed = 0
|
|
content_rows_succeeded = 0
|
|
content_rows_failed = 0
|
|
associations_written = 0
|
|
presentation_contracts_processed = 0
|
|
errors: list[str] = []
|
|
mapping_failed = False
|
|
|
|
for mapping in manifest.content_mapping:
|
|
if requested_template_codes and mapping.code not in requested_template_codes:
|
|
continue
|
|
|
|
try:
|
|
# Exactly one template/content mapping per durable transaction.
|
|
async with self._session.begin():
|
|
if not mapping.template_path.exists():
|
|
raise ModuleValidationError(f"Template not found: {mapping.template_path}")
|
|
if not mapping.data_path.exists():
|
|
raise ModuleValidationError(f"Data file not found: {mapping.data_path}")
|
|
|
|
template_document = load_json(mapping.template_path)
|
|
template_code = str(template_document.get("code", "")).strip().lower()
|
|
if template_code != mapping.code:
|
|
raise ModuleValidationError(
|
|
f"content_mapping code {mapping.code!r} does not match "
|
|
f"template code {template_code!r}"
|
|
)
|
|
|
|
definition_set = await self._definitions.seed(template_document)
|
|
if definition_set.code != mapping.code:
|
|
raise ModuleValidationError(
|
|
f"Seeded definition set code mismatch for {mapping.code!r}"
|
|
)
|
|
|
|
presentation_results = await self._presentations.seed(
|
|
definition_set=definition_set,
|
|
document=template_document,
|
|
)
|
|
|
|
batch = await self._contents.seed_document(
|
|
definition_set_code=mapping.code,
|
|
document=load_json(mapping.data_path),
|
|
publish=publish_content,
|
|
continue_on_error=continue_on_error,
|
|
content_codes=content_codes,
|
|
)
|
|
|
|
if content_codes:
|
|
# For single/subset content runs, only the rows actually
|
|
# seeded by this invocation are candidates for module
|
|
# association. Never rewrite unrelated template rows.
|
|
content_ids = [result.content_id for result in batch.results]
|
|
elif batch.results:
|
|
# Preserve authored sequence from the source document.
|
|
content_ids = [result.content_id for result in batch.results]
|
|
known_ids = set(content_ids)
|
|
all_ids = await self._modules.resolve_content_ids_for_definition_set(
|
|
definition_set_code=mapping.code
|
|
)
|
|
for remaining_id in all_ids:
|
|
if remaining_id not in known_ids:
|
|
content_ids.append(remaining_id)
|
|
else:
|
|
content_ids = await self._modules.resolve_content_ids_for_definition_set(
|
|
definition_set_code=mapping.code
|
|
)
|
|
|
|
mapping_associations = 0
|
|
mapping_next_sort_order = next_sort_order
|
|
for content_id in content_ids:
|
|
if partial_run:
|
|
inserted = await self._modules.ensure_module_content(
|
|
module_id=module_result.module_id,
|
|
content_id=content_id,
|
|
is_highlighted=False,
|
|
created_by=created_by,
|
|
)
|
|
if inserted:
|
|
mapping_associations += 1
|
|
else:
|
|
await self._modules.upsert_module_content(
|
|
module_id=module_result.module_id,
|
|
content_id=content_id,
|
|
sort_order=mapping_next_sort_order,
|
|
is_highlighted=False,
|
|
created_by=created_by,
|
|
)
|
|
mapping_associations += 1
|
|
mapping_next_sort_order += 1
|
|
|
|
# Force deferred constraints to be checked inside this
|
|
# template transaction rather than at some later boundary.
|
|
await self._session.execute(text("SET CONSTRAINTS ALL IMMEDIATE"))
|
|
|
|
# Update in-memory summary only after the template transaction
|
|
# has committed successfully.
|
|
definition_sets_processed += 1
|
|
presentation_contracts_processed += len(presentation_results)
|
|
content_rows_succeeded += batch.succeeded
|
|
content_rows_failed += batch.failed
|
|
errors.extend(f"{mapping.code}: {error}" for error in batch.errors)
|
|
desired_content_ids.update(content_ids)
|
|
associations_written += mapping_associations
|
|
next_sort_order = mapping_next_sort_order
|
|
|
|
logger.info(
|
|
"Committed template: module=%s template=%s content_ok=%s "
|
|
"content_failed=%s associations=%s",
|
|
config.code,
|
|
mapping.code,
|
|
batch.succeeded,
|
|
batch.failed,
|
|
mapping_associations,
|
|
)
|
|
|
|
except Exception as exc:
|
|
mapping_failed = True
|
|
errors.append(f"{mapping.code}: {exc}")
|
|
logger.exception(
|
|
"Content mapping failed and was rolled back: module=%s mapping=%s",
|
|
config.code,
|
|
mapping.code,
|
|
)
|
|
if not continue_on_error:
|
|
raise
|
|
|
|
stale_removed = 0
|
|
if not mapping_failed and not partial_run:
|
|
async with self._session.begin():
|
|
stale_removed = await self._modules.reconcile_module_contents(
|
|
module_id=module_result.module_id,
|
|
desired_content_ids=desired_content_ids,
|
|
)
|
|
await self._session.execute(text("SET CONSTRAINTS ALL IMMEDIATE"))
|
|
elif partial_run:
|
|
logger.info(
|
|
"Skipping stale module-content reconciliation for partial seed: "
|
|
"module=%s templates=%s content_codes=%s",
|
|
config.code,
|
|
sorted(requested_template_codes or []),
|
|
sorted(content_codes or []),
|
|
)
|
|
else:
|
|
logger.warning(
|
|
"Skipping stale module-content reconciliation for module=%s because one or more "
|
|
"template mappings failed",
|
|
config.code,
|
|
)
|
|
|
|
# Canonical search facets are module-level configuration. Seed them only
|
|
# after every template has been committed, because mappings resolve
|
|
# attribute_definition IDs and the subsequent reindex needs durable
|
|
# module-content associations. A missing file is intentionally a no-op.
|
|
if not mapping_failed and not skip_search_facets:
|
|
search_facets_path = config.path / "search_facets.json"
|
|
if search_facets_path.exists():
|
|
async with self._session.begin():
|
|
facet_count, facet_mapping_count = await self._search_facets.seed_file(
|
|
search_facets_path,
|
|
module_code=config.code,
|
|
)
|
|
await self._session.execute(text("SET CONSTRAINTS ALL IMMEDIATE"))
|
|
logger.info(
|
|
"Committed search facets: module=%s facets=%s mappings=%s",
|
|
config.code,
|
|
facet_count,
|
|
facet_mapping_count,
|
|
)
|
|
|
|
return ModuleProcessSummary(
|
|
module_id=module_result.module_id,
|
|
module_code=module_result.code,
|
|
module_slug=module_result.slug,
|
|
definition_sets_processed=definition_sets_processed,
|
|
content_rows_succeeded=content_rows_succeeded,
|
|
content_rows_failed=content_rows_failed,
|
|
associations_written=associations_written,
|
|
stale_associations_removed=stale_removed,
|
|
presentation_contracts_processed=presentation_contracts_processed,
|
|
errors=tuple(errors),
|
|
)
|