acupedia-api/app/cli/reset.py

253 lines
9.2 KiB
Python

from __future__ import annotations
import argparse
import asyncio
import logging
import os
from uuid import UUID
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.reset.models import ResetScope, ResetTarget
from app.reset.service import DataResetService, ResetError, ResetValidationError
logger = logging.getLogger("accupedia.reset")
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description=(
"AccuPedia production data-reset CLI. Dry-run is the default; pass --execute "
"to perform destructive changes."
)
)
parser.add_argument("--database-url", default=os.environ.get("DATABASE_URL"))
parser.add_argument("--schema", default="acu_content")
parser.add_argument(
"--scope",
required=True,
choices=[scope.value for scope in ResetScope],
help="Reset scope: all, module, template, or content",
)
parser.add_argument("--module-code")
parser.add_argument("--template-code")
parser.add_argument("--content-id", type=UUID)
parser.add_argument("--source-key")
parser.add_argument(
"--execute",
action="store_true",
help="Execute the reset. Without this option the CLI performs a dry-run only.",
)
parser.add_argument(
"--confirm",
help=(
"Required only for --scope all execution. Must equal RESET-ALL exactly. "
"This is intentionally separate from --execute."
),
)
parser.add_argument(
"--allow-shared-content",
action="store_true",
help=(
"Module scope only: detach content shared with other modules instead of refusing "
"the reset. Shared content rows and their definition sets are preserved."
),
)
parser.add_argument(
"--lock-timeout-ms",
type=int,
default=10_000,
help="PostgreSQL lock timeout for the destructive transaction (default: 10000).",
)
parser.add_argument(
"--statement-timeout-ms",
type=int,
default=120_000,
help="PostgreSQL statement timeout for the reset transaction (default: 120000).",
)
parser.add_argument(
"--log-level",
default="INFO",
choices=["DEBUG", "INFO", "WARNING", "ERROR"],
)
return parser
def _build_target(args: argparse.Namespace) -> ResetTarget:
scope = ResetScope(args.scope)
supplied = {
"module_code": bool(args.module_code),
"template_code": bool(args.template_code),
"content_id": args.content_id is not None,
"source_key": bool(args.source_key),
}
if scope is ResetScope.ALL:
if any(supplied.values()):
raise ResetValidationError("all scope does not accept module/template/content selectors")
return ResetTarget(scope=scope)
if scope is ResetScope.MODULE:
if not args.module_code:
raise ResetValidationError("module scope requires --module-code")
if supplied["template_code"] or supplied["content_id"] or supplied["source_key"]:
raise ResetValidationError("module scope accepts only --module-code")
return ResetTarget(scope=scope, module_code=args.module_code)
if scope is ResetScope.TEMPLATE:
if not args.template_code:
raise ResetValidationError("template scope requires --template-code")
if supplied["module_code"] or supplied["content_id"] or supplied["source_key"]:
raise ResetValidationError("template scope accepts only --template-code")
return ResetTarget(scope=scope, template_code=args.template_code)
if scope is ResetScope.CONTENT:
if supplied["module_code"] or supplied["template_code"]:
raise ResetValidationError("content scope does not accept module/template selectors")
if supplied["content_id"] == supplied["source_key"]:
raise ResetValidationError(
"content scope requires exactly one of --content-id or --source-key"
)
return ResetTarget(
scope=scope,
content_id=args.content_id,
source_key=args.source_key,
)
raise ResetValidationError(f"Unsupported scope: {scope}")
def _validate_runtime_guards(args: argparse.Namespace, target: ResetTarget) -> None:
if args.lock_timeout_ms <= 0:
raise ResetValidationError("--lock-timeout-ms must be greater than zero")
if args.statement_timeout_ms <= 0:
raise ResetValidationError("--statement-timeout-ms must be greater than zero")
if args.allow_shared_content and target.scope is not ResetScope.MODULE:
raise ResetValidationError("--allow-shared-content is valid only for module scope")
if args.execute and target.scope is ResetScope.ALL and args.confirm != "RESET-ALL":
raise ResetValidationError(
"Executing --scope all requires both --execute and --confirm RESET-ALL"
)
def _log_impact(impact) -> None:
logger.warning("RESET PLAN scope=%s target=%s", impact.scope.value, impact.target)
if impact.module_ids:
logger.warning("modules=%s", len(impact.module_ids))
if impact.definition_set_ids:
logger.warning("definition_sets=%s", len(impact.definition_set_ids))
if impact.content_ids:
logger.warning("content_items=%s", len(impact.content_ids))
if impact.shared_content_ids:
logger.warning("shared_content_items=%s", len(impact.shared_content_ids))
if impact.affected_module_codes:
logger.warning("affected_module_codes=%s", ",".join(impact.affected_module_codes))
if impact.table_counts:
total = sum(entry.row_count for entry in impact.table_counts)
logger.warning("base_tables=%s rows=%s", len(impact.table_counts), total)
for entry in impact.table_counts:
logger.info("table=%s rows=%s", entry.table_name, entry.row_count)
for note in impact.notes:
logger.warning("note=%s", note)
def _log_summary(summary) -> None:
logger.info(
"RESET COMPLETE scope=%s target=%s modules=%s definition_sets=%s "
"content_items=%s shared_detached=%s truncated_tables=%s truncated_rows_estimate=%s",
summary.scope.value,
summary.target,
summary.deleted_modules,
summary.deleted_definition_sets,
summary.deleted_content_items,
summary.detached_shared_content_items,
summary.truncated_tables,
summary.truncated_rows_estimate,
)
for note in summary.notes:
logger.info("note=%s", note)
async def run(args: argparse.Namespace) -> int:
if not args.database_url:
raise ResetValidationError("DATABASE_URL is required")
target = _build_target(args)
_validate_runtime_guards(args, target)
engine = create_async_engine(
args.database_url,
pool_pre_ping=True,
connect_args={
"server_settings": {
"search_path": f"{args.schema},public",
}
},
)
session_factory = async_sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False,
autoflush=False,
)
try:
async with session_factory() as session:
service = DataResetService(session, schema=args.schema)
# Inspection is read-only and always occurs first. Rolling back
# afterwards ensures no implicit autobegin transaction survives
# into the explicit destructive transaction.
impact = await service.inspect(target)
_log_impact(impact)
await session.rollback()
if not args.execute:
logger.warning("DRY RUN ONLY: no data was changed. Re-run with --execute to apply.")
return 0
async with session.begin():
await session.execute(
text("select set_config('lock_timeout', :value, true)"),
{"value": f"{args.lock_timeout_ms}ms"},
)
await session.execute(
text("select set_config('statement_timeout', :value, true)"),
{"value": f"{args.statement_timeout_ms}ms"},
)
# Re-inspect inside the same transaction to avoid acting on a
# stale plan produced before locks/transactional execution.
impact = await service.inspect(target)
summary = await service.execute(
target,
allow_shared_content=args.allow_shared_content,
)
await session.execute(text("SET CONSTRAINTS ALL IMMEDIATE"))
_log_summary(summary)
return 0
finally:
await engine.dispose()
def main() -> None:
args = build_parser().parse_args()
logging.basicConfig(
level=getattr(logging, args.log_level),
format="%(asctime)s %(levelname)s %(name)s - %(message)s",
)
try:
raise SystemExit(asyncio.run(run(args)))
except ResetError as exc:
logger.error("Reset rejected: %s", exc)
raise SystemExit(2) from exc
except Exception as exc:
logger.exception("Reset failed: %s", exc)
raise SystemExit(1) from exc
if __name__ == "__main__":
main()