acupedia-api/app/reset/service.py

639 lines
23 KiB
Python

from __future__ import annotations
import re
from collections.abc import Iterable
from uuid import UUID
from sqlalchemy import bindparam, text
from sqlalchemy.ext.asyncio import AsyncSession
from .models import ResetImpact, ResetScope, ResetSummary, ResetTarget, TableCount
_SCHEMA_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_CODE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$")
class ResetError(RuntimeError):
"""Base reset failure."""
class ResetValidationError(ResetError):
"""Invalid reset request or unsafe reset condition."""
class ResetTargetNotFoundError(ResetError):
"""Requested module/template/content does not exist."""
def _validate_schema(schema: str) -> str:
value = schema.strip()
if not _SCHEMA_RE.fullmatch(value):
raise ResetValidationError(f"Invalid PostgreSQL schema identifier: {schema!r}")
return value
def _validate_code(value: str, *, field_name: str) -> str:
normalized = value.strip()
if not normalized:
raise ResetValidationError(f"{field_name} cannot be blank")
if not _CODE_RE.fullmatch(normalized):
raise ResetValidationError(f"Invalid {field_name}: {value!r}")
return normalized
def _quote_identifier(value: str) -> str:
return '"' + value.replace('"', '""') + '"'
def _dedupe_uuids(values: Iterable[UUID]) -> tuple[UUID, ...]:
return tuple(dict.fromkeys(values))
class DataResetService:
"""Production-grade destructive data reset service.
Scope semantics
---------------
all:
Truncate every BASE TABLE in the configured schema while preserving
schema objects, functions, views, constraints, and migrations.
module:
Reset a module's seed-owned graph. The module row is deleted, its
module associations are removed by FK cascade, exclusively-owned
content is deleted, and eligible definition sets are deleted after
content removal. Shared content is rejected by default.
template:
Delete the exact attribute-definition set and therefore the complete
content/template graph beneath it. Any module_contents rows for those
content items are removed by FK cascade.
content:
Delete one content item by UUID or source_key. Dependent values,
translations, tags, media links, and module_contents are removed via
the schema's FK cascade rules.
Every mutating method assumes the caller owns the transaction boundary.
"""
def __init__(self, session: AsyncSession, *, schema: str = "acu_content") -> None:
self._session = session
self._schema = _validate_schema(schema)
self._q_schema = _quote_identifier(self._schema)
async def inspect(self, target: ResetTarget) -> ResetImpact:
if target.scope is ResetScope.ALL:
return await self._inspect_all()
if target.scope is ResetScope.MODULE:
if not target.module_code:
raise ResetValidationError("module scope requires module_code")
return await self._inspect_module(target.module_code)
if target.scope is ResetScope.TEMPLATE:
if not target.template_code:
raise ResetValidationError("template scope requires template_code")
return await self._inspect_template(target.template_code)
if target.scope is ResetScope.CONTENT:
if bool(target.content_id) == bool(target.source_key):
raise ResetValidationError(
"content scope requires exactly one of content_id or source_key"
)
return await self._inspect_content(
content_id=target.content_id,
source_key=target.source_key,
)
raise ResetValidationError(f"Unsupported reset scope: {target.scope}")
async def execute(
self,
target: ResetTarget,
*,
allow_shared_content: bool = False,
) -> ResetSummary:
impact = await self.inspect(target)
if target.scope is ResetScope.ALL:
return await self._execute_all(impact)
if target.scope is ResetScope.MODULE:
return await self._execute_module(
impact,
allow_shared_content=allow_shared_content,
)
if target.scope is ResetScope.TEMPLATE:
return await self._execute_template(impact)
if target.scope is ResetScope.CONTENT:
return await self._execute_content(impact)
raise ResetValidationError(f"Unsupported reset scope: {target.scope}")
async def _inspect_all(self) -> ResetImpact:
table_result = await self._session.execute(
text(
"""
select table_name
from information_schema.tables
where table_schema = :schema
and table_type = 'BASE TABLE'
order by table_name
"""
),
{"schema": self._schema},
)
table_names = [str(row[0]) for row in table_result.all()]
counts: list[TableCount] = []
for table_name in table_names:
statement = text(
f"select count(*) from {self._q_schema}.{_quote_identifier(table_name)}"
)
count = int((await self._session.execute(statement)).scalar_one())
counts.append(TableCount(table_name=table_name, row_count=count))
return ResetImpact(
scope=ResetScope.ALL,
target=self._schema,
table_counts=tuple(counts),
notes=(
"All base-table data in the configured schema will be removed.",
"Schema objects, views, functions, types, and migrations are preserved.",
),
)
async def _inspect_module(self, module_code: str) -> ResetImpact:
code = _validate_code(module_code, field_name="module_code").upper()
module_row = (
await self._session.execute(
text(
f"""
select id, code
from {self._q_schema}.modules
where upper(code) = :code
"""
),
{"code": code},
)
).mappings().one_or_none()
if module_row is None:
raise ResetTargetNotFoundError(f"Module not found: {code}")
module_id = module_row["id"]
content_rows = (
await self._session.execute(
text(
f"""
select
ci.id as content_id,
ci.attribute_definition_set_id,
exists (
select 1
from {self._q_schema}.module_contents mc_other
where mc_other.content_id = ci.id
and mc_other.module_id <> :module_id
) as is_shared
from {self._q_schema}.module_contents mc
join {self._q_schema}.content_items ci
on ci.id = mc.content_id
where mc.module_id = :module_id
order by ci.id
"""
),
{"module_id": module_id},
)
).mappings().all()
content_ids = _dedupe_uuids(row["content_id"] for row in content_rows)
shared_ids = _dedupe_uuids(
row["content_id"] for row in content_rows if bool(row["is_shared"])
)
# Include definition sets referenced by current module content plus
# definition sets following the canonical module template-code prefix.
definition_set_result = await self._session.execute(
text(
f"""
select distinct ads.id
from {self._q_schema}.attribute_definition_sets ads
where ads.id in (
select distinct ci.attribute_definition_set_id
from {self._q_schema}.module_contents mc
join {self._q_schema}.content_items ci on ci.id = mc.content_id
where mc.module_id = :module_id
)
or left(upper(ads.code), length(:template_prefix)) = :template_prefix
order by ads.id
"""
),
{"module_id": module_id, "template_prefix": f"{code}_"},
)
definition_set_ids = _dedupe_uuids(row[0] for row in definition_set_result.all())
affected_modules = await self._module_codes_for_content_ids(content_ids)
notes: list[str] = []
if shared_ids:
notes.append(
f"{len(shared_ids)} content item(s) are associated with another module. "
"Execution is refused unless --allow-shared-content is supplied."
)
return ResetImpact(
scope=ResetScope.MODULE,
target=code,
module_ids=(module_id,),
definition_set_ids=definition_set_ids,
content_ids=content_ids,
shared_content_ids=shared_ids,
affected_module_codes=affected_modules,
notes=tuple(notes),
)
async def _inspect_template(self, template_code: str) -> ResetImpact:
code = _validate_code(template_code, field_name="template_code").upper()
definition_set = (
await self._session.execute(
text(
f"""
select id, code
from {self._q_schema}.attribute_definition_sets
where upper(code) = :code
or upper(attribute_prefix_code) = :code
order by case when upper(code) = :code then 0 else 1 end
limit 2
"""
),
{"code": code},
)
).mappings().all()
if not definition_set:
raise ResetTargetNotFoundError(f"Template not found: {code}")
if len(definition_set) > 1:
raise ResetValidationError(f"Template identifier is ambiguous: {code}")
definition_set_id = definition_set[0]["id"]
content_result = await self._session.execute(
text(
f"""
select id
from {self._q_schema}.content_items
where attribute_definition_set_id = :definition_set_id
order by id
"""
),
{"definition_set_id": definition_set_id},
)
content_ids = _dedupe_uuids(row[0] for row in content_result.all())
affected_modules = await self._module_codes_for_content_ids(content_ids)
return ResetImpact(
scope=ResetScope.TEMPLATE,
target=code,
definition_set_ids=(definition_set_id,),
content_ids=content_ids,
affected_module_codes=affected_modules,
notes=(
"Deleting the definition set also deletes definitions and presentation contracts.",
"All content using this template is deleted first so restrictive definition FKs remain valid.",
),
)
async def _inspect_content(
self,
*,
content_id: UUID | None,
source_key: str | None,
) -> ResetImpact:
if content_id is not None:
where_sql = "ci.id = :value"
value: object = content_id
target_label = str(content_id)
else:
assert source_key is not None
normalized_source_key = source_key.strip()
if not normalized_source_key:
raise ResetValidationError("source_key cannot be blank")
where_sql = "ci.source_key = :value"
value = normalized_source_key
target_label = normalized_source_key
row = (
await self._session.execute(
text(
f"""
select ci.id, ci.attribute_definition_set_id, ci.source_key, ci.title
from {self._q_schema}.content_items ci
where {where_sql}
"""
),
{"value": value},
)
).mappings().one_or_none()
if row is None:
raise ResetTargetNotFoundError(f"Content not found: {target_label}")
affected_modules = await self._module_codes_for_content_ids((row["id"],))
return ResetImpact(
scope=ResetScope.CONTENT,
target=row["source_key"] or str(row["id"]),
definition_set_ids=(row["attribute_definition_set_id"],),
content_ids=(row["id"],),
affected_module_codes=affected_modules,
notes=(f"Content title: {row['title']}",),
)
async def _module_codes_for_content_ids(
self,
content_ids: tuple[UUID, ...],
) -> tuple[str, ...]:
if not content_ids:
return ()
statement = text(
f"""
select distinct coalesce(m.code, m.slug) as module_code
from {self._q_schema}.module_contents mc
join {self._q_schema}.modules m on m.id = mc.module_id
where mc.content_id in :content_ids
order by module_code
"""
).bindparams(bindparam("content_ids", expanding=True))
result = await self._session.execute(statement, {"content_ids": list(content_ids)})
return tuple(str(row[0]) for row in result.all())
async def _eligible_definition_set_ids(
self,
definition_set_ids: tuple[UUID, ...],
) -> tuple[UUID, ...]:
"""
Return only definition sets that no longer have content_items.
This is especially important for module reset with
--allow-shared-content. A definition set still used by preserved
shared content must not have its hierarchy metadata removed.
"""
if not definition_set_ids:
return ()
statement = text(
f"""
select ads.id
from {self._q_schema}.attribute_definition_sets ads
where ads.id in :definition_set_ids
and not exists (
select 1
from {self._q_schema}.content_items ci
where ci.attribute_definition_set_id = ads.id
)
order by ads.id
"""
).bindparams(
bindparam("definition_set_ids", expanding=True)
)
result = await self._session.execute(
statement,
{
"definition_set_ids": list(definition_set_ids),
},
)
return _dedupe_uuids(
row[0] for row in result.all()
)
async def _delete_definition_memberships(
self,
definition_set_ids: tuple[UUID, ...],
) -> int:
"""
Delete hierarchy relationships involving definitions belonging
to the supplied definition sets.
attribute_definition_members references attribute_definitions
from BOTH:
- parent_attribute_definition_id
- child_attribute_definition_id
Both directions must therefore be removed before deleting the
underlying definitions.
"""
if not definition_set_ids:
return 0
statement = text(
f"""
delete from {self._q_schema}.attribute_definition_members adm
where exists (
select 1
from {self._q_schema}.attribute_definitions ad
where ad.attribute_definition_set_id in :definition_set_ids
and (
adm.parent_attribute_definition_id = ad.id
or adm.child_attribute_definition_id = ad.id
)
)
"""
).bindparams(
bindparam("definition_set_ids", expanding=True)
)
result = await self._session.execute(
statement,
{
"definition_set_ids": list(definition_set_ids),
},
)
return int(result.rowcount or 0)
async def _delete_definition_sets_if_unreferenced(
self,
definition_set_ids: tuple[UUID, ...],
) -> tuple[int, int]:
"""
Delete definition sets in FK-safe order.
Returns:
(
deleted_definition_sets,
deleted_definition_memberships,
)
"""
eligible_ids = await self._eligible_definition_set_ids(
definition_set_ids
)
if not eligible_ids:
return 0, 0
deleted_memberships = (
await self._delete_definition_memberships(
eligible_ids
)
)
statement = text(
f"""
delete from {self._q_schema}.attribute_definition_sets ads
where ads.id in :definition_set_ids
and not exists (
select 1
from {self._q_schema}.content_items ci
where ci.attribute_definition_set_id = ads.id
)
"""
).bindparams(
bindparam("definition_set_ids", expanding=True)
)
result = await self._session.execute(
statement,
{
"definition_set_ids": list(eligible_ids),
},
)
return (
int(result.rowcount or 0),
deleted_memberships,
)
async def _execute_all(self, impact: ResetImpact) -> ResetSummary:
table_names = [entry.table_name for entry in impact.table_counts]
if not table_names:
return ResetSummary(
scope=ResetScope.ALL,
target=impact.target,
executed=True,
notes=("No base tables found; nothing to truncate.",),
)
qualified = ", ".join(
f"{self._q_schema}.{_quote_identifier(table_name)}"
for table_name in table_names
)
await self._session.execute(text(f"TRUNCATE TABLE {qualified} RESTART IDENTITY CASCADE"))
return ResetSummary(
scope=ResetScope.ALL,
target=impact.target,
executed=True,
truncated_tables=len(table_names),
truncated_rows_estimate=sum(entry.row_count for entry in impact.table_counts),
notes=("All base tables in the configured schema were truncated.",),
)
async def _execute_module(
self,
impact: ResetImpact,
*,
allow_shared_content: bool,
) -> ResetSummary:
if impact.shared_content_ids and not allow_shared_content:
raise ResetValidationError(
f"Module {impact.target} contains {len(impact.shared_content_ids)} shared content item(s). "
"Re-run with --allow-shared-content to detach them from this module while preserving "
"their shared content rows."
)
module_id = impact.module_ids[0]
shared = set(impact.shared_content_ids)
exclusive_ids = tuple(content_id for content_id in impact.content_ids if content_id not in shared)
# Remove module first. FK cascades detach every module_content and also
# remove module-specific entitlements/access-plan mappings according to
# the canonical schema.
module_delete = await self._session.execute(
text(f"delete from {self._q_schema}.modules where id = :module_id"),
{"module_id": module_id},
)
deleted_modules = int(module_delete.rowcount or 0)
deleted_content = 0
if exclusive_ids:
statement = text(
f"delete from {self._q_schema}.content_items where id in :content_ids"
).bindparams(bindparam("content_ids", expanding=True))
result = await self._session.execute(statement, {"content_ids": list(exclusive_ids)})
deleted_content = int(result.rowcount or 0)
# Delete only definition sets that no longer have content rows. This is
# what keeps --allow-shared-content safe.
(
deleted_definition_sets,
deleted_definition_memberships,
) = await self._delete_definition_sets_if_unreferenced(
impact.definition_set_ids,
)
return ResetSummary(
scope=ResetScope.MODULE,
target=impact.target,
executed=True,
deleted_modules=deleted_modules,
deleted_definition_sets=deleted_definition_sets,
deleted_content_items=deleted_content,
detached_shared_content_items=len(
impact.shared_content_ids
),
notes=(
(
"Shared content rows were preserved."
if impact.shared_content_ids
else "No shared content detected."
),
(
f"Deleted {deleted_definition_memberships} "
"attribute-definition hierarchy membership row(s)."
),
),
)
async def _execute_template(self, impact: ResetImpact) -> ResetSummary:
definition_set_id = impact.definition_set_ids[0]
deleted_content = 0
if impact.content_ids:
statement = text(
f"delete from {self._q_schema}.content_items where id in :content_ids"
).bindparams(bindparam("content_ids", expanding=True))
result = await self._session.execute(
statement,
{"content_ids": list(impact.content_ids)},
)
deleted_content = int(result.rowcount or 0)
(
deleted_definition_sets,
deleted_definition_memberships,
) = await self._delete_definition_sets_if_unreferenced(
(definition_set_id,),
)
return ResetSummary(
scope=ResetScope.TEMPLATE,
target=impact.target,
executed=True,
deleted_definition_sets=deleted_definition_sets,
deleted_content_items=deleted_content,
notes=(
(
"Template definitions and presentation contracts "
"were removed."
),
(
f"Deleted {deleted_definition_memberships} "
"attribute-definition hierarchy membership row(s)."
),
),
)
async def _execute_content(self, impact: ResetImpact) -> ResetSummary:
content_id = impact.content_ids[0]
result = await self._session.execute(
text(f"delete from {self._q_schema}.content_items where id = :content_id"),
{"content_id": content_id},
)
deleted_content = int(result.rowcount or 0)
return ResetSummary(
scope=ResetScope.CONTENT,
target=impact.target,
executed=True,
deleted_content_items=deleted_content,
notes=("Dependent content rows were removed by FK cascade.",),
)