From 4d8436477ad27a349b87f51a058d07f0d82e3042 Mon Sep 17 00:00:00 2001 From: Amit Salunke Date: Tue, 8 Sep 2026 18:35:21 +0530 Subject: [PATCH] Initial Commit --- .env.example | 24 + .gitignore | 12 + README.md | 145 ++++++ acupedia_ops/__init__.py | 2 + acupedia_ops/ansible/__init__.py | 0 acupedia_ops/ansible/runner.py | 14 + acupedia_ops/bootstrap/__init__.py | 13 + acupedia_ops/bootstrap/api_cli.py | 109 +++++ acupedia_ops/cli.py | 424 ++++++++++++++++++ acupedia_ops/common/__init__.py | 0 acupedia_ops/common/config.py | 20 + acupedia_ops/common/env.py | 83 ++++ acupedia_ops/common/logging.py | 4 + acupedia_ops/common/paths.py | 7 + acupedia_ops/common/process.py | 85 ++++ acupedia_ops/common/workspace_paths.py | 107 +++++ acupedia_ops/data/__init__.py | 0 acupedia_ops/data/content/__init__.py | 0 .../data/content/normalize_content.py | 2 + acupedia_ops/data/content/sanitize_json.py | 2 + .../data/content/validate_content_refs.py | 2 + acupedia_ops/data/image/__init__.py | 1 + .../data/image/clean_image_borders.py | 133 ++++++ acupedia_ops/data/image/normalize_images.py | 2 + acupedia_ops/data/image/resize_images.py | 2 + acupedia_ops/data/templates/__init__.py | 0 .../data/templates/add_display_order.py | 2 + .../data/templates/validate_templates.py | 2 + acupedia_ops/deployment/__init__.py | 0 acupedia_ops/deployment/backend.py | 5 + acupedia_ops/deployment/database.py | 5 + acupedia_ops/deployment/gitea_runner.py | 85 ++++ acupedia_ops/deployment/infra.py | 5 + acupedia_ops/deployment/mobile.py | 2 + acupedia_ops/local/__init__.py | 3 + acupedia_ops/local/bootstrap.py | 101 +++++ acupedia_ops/local/database.py | 55 +++ acupedia_ops/local/git_status.py | 53 +++ acupedia_ops/local/infrastructure.py | 103 +++++ acupedia_ops/local/services.py | 38 ++ acupedia_ops/local/validation.py | 102 +++++ acupedia_ops/local/workspace.py | 237 ++++++++++ ansible/ansible.cfg | 4 + ansible/inventories/dev/hosts.yml | 5 + ansible/inventories/gitea-runners.example.yml | 22 + ansible/inventories/prod/hosts.yml | 5 + ansible/inventories/staging/hosts.yml | 5 + ansible/playbooks/backend.yml | 7 + ansible/playbooks/database.yml | 7 + ansible/playbooks/gitea-runner-remove.yml | 9 + ansible/playbooks/gitea-runner.yml | 6 + ansible/playbooks/infra.yml | 7 + ansible/roles/.gitkeep | 0 ansible/roles/gitea_runner/defaults/main.yml | 35 ++ ansible/roles/gitea_runner/handlers/main.yml | 7 + ansible/roles/gitea_runner/tasks/main.yml | 132 ++++++ ansible/roles/gitea_runner/tasks/remove.yml | 33 ++ .../gitea_runner/templates/config.yaml.j2 | 31 ++ .../templates/gitea-act-runner.service.j2 | 21 + config/dev.yaml | 6 + config/local.yaml | 84 ++++ config/prod.yaml | 6 + config/staging.yaml | 6 + docker-compose.local.example.yml | 49 ++ docs/gitea-runner-lifecycle.md | 72 +++ docs/local-development.md | 196 ++++++++ pyproject.toml | 30 ++ requirements.txt | 3 + tests/__init__.py | 0 tests/bootstrap/__init__.py | 0 tests/bootstrap/test_api_cli.py | 22 + tests/common/__init__.py | 0 tests/common/test_config.py | 12 + tests/common/test_workspace_paths.py | 49 ++ tests/data/image/test_clean_image_borders.py | 11 + tests/deployment/__init__.py | 0 tests/deployment/test_gitea_runner.py | 8 + tests/local/__init__.py | 0 tests/local/test_bootstrap_args.py | 49 ++ tests/local/test_env.py | 16 + tests/local/test_workspace.py | 101 +++++ 81 files changed, 3047 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 acupedia_ops/__init__.py create mode 100644 acupedia_ops/ansible/__init__.py create mode 100644 acupedia_ops/ansible/runner.py create mode 100644 acupedia_ops/bootstrap/__init__.py create mode 100644 acupedia_ops/bootstrap/api_cli.py create mode 100644 acupedia_ops/cli.py create mode 100644 acupedia_ops/common/__init__.py create mode 100644 acupedia_ops/common/config.py create mode 100644 acupedia_ops/common/env.py create mode 100644 acupedia_ops/common/logging.py create mode 100644 acupedia_ops/common/paths.py create mode 100644 acupedia_ops/common/process.py create mode 100644 acupedia_ops/common/workspace_paths.py create mode 100644 acupedia_ops/data/__init__.py create mode 100644 acupedia_ops/data/content/__init__.py create mode 100644 acupedia_ops/data/content/normalize_content.py create mode 100644 acupedia_ops/data/content/sanitize_json.py create mode 100644 acupedia_ops/data/content/validate_content_refs.py create mode 100644 acupedia_ops/data/image/__init__.py create mode 100644 acupedia_ops/data/image/clean_image_borders.py create mode 100644 acupedia_ops/data/image/normalize_images.py create mode 100644 acupedia_ops/data/image/resize_images.py create mode 100644 acupedia_ops/data/templates/__init__.py create mode 100644 acupedia_ops/data/templates/add_display_order.py create mode 100644 acupedia_ops/data/templates/validate_templates.py create mode 100644 acupedia_ops/deployment/__init__.py create mode 100644 acupedia_ops/deployment/backend.py create mode 100644 acupedia_ops/deployment/database.py create mode 100644 acupedia_ops/deployment/gitea_runner.py create mode 100644 acupedia_ops/deployment/infra.py create mode 100644 acupedia_ops/deployment/mobile.py create mode 100644 acupedia_ops/local/__init__.py create mode 100644 acupedia_ops/local/bootstrap.py create mode 100644 acupedia_ops/local/database.py create mode 100644 acupedia_ops/local/git_status.py create mode 100644 acupedia_ops/local/infrastructure.py create mode 100644 acupedia_ops/local/services.py create mode 100644 acupedia_ops/local/validation.py create mode 100644 acupedia_ops/local/workspace.py create mode 100644 ansible/ansible.cfg create mode 100644 ansible/inventories/dev/hosts.yml create mode 100644 ansible/inventories/gitea-runners.example.yml create mode 100644 ansible/inventories/prod/hosts.yml create mode 100644 ansible/inventories/staging/hosts.yml create mode 100644 ansible/playbooks/backend.yml create mode 100644 ansible/playbooks/database.yml create mode 100644 ansible/playbooks/gitea-runner-remove.yml create mode 100644 ansible/playbooks/gitea-runner.yml create mode 100644 ansible/playbooks/infra.yml create mode 100644 ansible/roles/.gitkeep create mode 100644 ansible/roles/gitea_runner/defaults/main.yml create mode 100644 ansible/roles/gitea_runner/handlers/main.yml create mode 100644 ansible/roles/gitea_runner/tasks/main.yml create mode 100644 ansible/roles/gitea_runner/tasks/remove.yml create mode 100644 ansible/roles/gitea_runner/templates/config.yaml.j2 create mode 100644 ansible/roles/gitea_runner/templates/gitea-act-runner.service.j2 create mode 100644 config/dev.yaml create mode 100644 config/local.yaml create mode 100644 config/prod.yaml create mode 100644 config/staging.yaml create mode 100644 docker-compose.local.example.yml create mode 100644 docs/gitea-runner-lifecycle.md create mode 100644 docs/local-development.md create mode 100644 pyproject.toml create mode 100644 requirements.txt create mode 100644 tests/__init__.py create mode 100644 tests/bootstrap/__init__.py create mode 100644 tests/bootstrap/test_api_cli.py create mode 100644 tests/common/__init__.py create mode 100644 tests/common/test_config.py create mode 100644 tests/common/test_workspace_paths.py create mode 100644 tests/data/image/test_clean_image_borders.py create mode 100644 tests/deployment/__init__.py create mode 100644 tests/deployment/test_gitea_runner.py create mode 100644 tests/local/__init__.py create mode 100644 tests/local/test_bootstrap_args.py create mode 100644 tests/local/test_env.py create mode 100644 tests/local/test_workspace.py diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..2b4156e --- /dev/null +++ b/.env.example @@ -0,0 +1,24 @@ +# Local AccuPedia workspace. +# Copy this file to .env and adjust for your machine. +# +# Do NOT commit .env. + +ACUPEDIA_WORKSPACE_BASE_PATH=/home/amit/Work/Project/acupedia + +# Relative paths below are resolved against ACUPEDIA_WORKSPACE_BASE_PATH. +# Absolute paths are also accepted. +ACUPEDIA_API_PATH=acupedia-api +ACUPEDIA_MOBILE_PATH=acupedia-mobile-ui +ACUPEDIA_WEB_PORTAL_PATH=acupedia-web-portal +ACUPEDIA_ADMIN_PORTAL_PATH=acupedia-admin-portal +ACUPEDIA_CONTENT_PATH=acupedia-content +ACUPEDIA_OPS_PATH=acupedia-ops + +# Optional local overrides. +# Relative path values are resolved against ACUPEDIA_WORKSPACE_BASE_PATH. +ACUPEDIA_LOCAL_COMPOSE_FILE=acupedia-ops/docker-compose.local.yml +ACUPEDIA_API_BOOTSTRAP_COMMAND=acupedia-api/.venv/bin/acupedia-bootstrap +ACUPEDIA_API_PYTHON=acupedia-api/.venv/bin/python + +# Local runtime connection string. Keep real credentials only in .env. +ACUPEDIA_LOCAL_DATABASE_URL=postgresql+asyncpg://acupedia:CHANGE_ME@127.0.0.1:5432/acupedia diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c992da6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +.venv/ +__pycache__/ +*.py[cod] +.pytest_cache/ +.env +.env.* +!.env.example +output/ +tmp/ +*.log +*.pyc +.local/ diff --git a/README.md b/README.md index e69de29..1205dc1 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,145 @@ +# acupedia-ops + +Operational tooling for AccuPedia. + +The repository owns: + +- reusable content/data preprocessing; +- local development orchestration; +- backend bootstrap invocation through a CLI boundary; +- remote deployment orchestration; +- Gitea Actions runner lifecycle; +- Ansible playbooks/roles; +- operational validation and shared utilities. + +It does not own application business logic and does not import `app.*` from +`acupedia-api`. + +## Installation + +```bash +python -m venv .venv +source .venv/bin/activate +pip install -e . +``` + +For Ansible/deployment support: + +```bash +pip install -e ".[deployment]" +``` + +Development: + +```bash +pip install -e ".[dev]" +``` + + +## Workspace base path + +Local repositories can be configured relative to one canonical workspace root: + +```dotenv +ACUPEDIA_WORKSPACE_BASE_PATH=/home/amit/Work/Project/acupedia +ACUPEDIA_API_PATH=acupedia-api +ACUPEDIA_MOBILE_PATH=acupedia-mobile-ui +ACUPEDIA_WEB_PORTAL_PATH=acupedia-web-portal +ACUPEDIA_ADMIN_PORTAL_PATH=acupedia-admin-portal +ACUPEDIA_CONTENT_PATH=acupedia-content +ACUPEDIA_OPS_PATH=acupedia-ops +``` + +Relative paths are always resolved against `ACUPEDIA_WORKSPACE_BASE_PATH`, +never against the current working directory. Absolute component paths remain +supported. + +## Local workspace + +```bash +cp .env.example .env +acupedia-ops local validate +acupedia-ops local setup +``` + +Typical local flow: + +```bash +acupedia-ops local infra-up +acupedia-ops local bootstrap content --publish-content +``` + +Then, in separate terminals: + +```bash +acupedia-ops local run api +acupedia-ops local run mobile +``` + +For complete documentation see: + +- `docs/local-development.md` +- `docs/gitea-runner-lifecycle.md` + +## Local commands + +```text +acupedia-ops local validate +acupedia-ops local setup [--install] +acupedia-ops local status [--json] +acupedia-ops local run api|mobile|web|admin + +acupedia-ops local infra-up +acupedia-ops local infra-down +acupedia-ops local infra-restart +acupedia-ops local infra-status +acupedia-ops local logs + +acupedia-ops local bootstrap [auth|content|media|commerce|all|validate] +acupedia-ops local reset-db [--execute] +``` + +## Backend bootstrap boundary + +The bootstrap implementation remains in `acupedia-api`. `acupedia-ops` resolves +and invokes the backend-owned `acupedia-bootstrap` executable instead of +importing backend Python internals. + +Direct usage is also available: + +```bash +acupedia-ops bootstrap content \ + --api-root ../acupedia-api \ + -- \ + --config ../acupedia-content/config.json \ + --modules-root ../acupedia-content +``` + +## Image preprocessing + +```bash +acupedia-ops image clean-border input.jpg output.jpg +``` + +Directory and ZIP processing remain supported. + +## Gitea runner lifecycle + +```bash +export GITEA_RUNNER_REGISTRATION_TOKEN='...' + +acupedia-ops runner provision \ + --inventory ansible/inventories/gitea-runners.yml +``` + +See `docs/gitea-runner-lifecycle.md`. + +## Remote deployment + +```bash +acupedia-ops deploy backend --env dev +acupedia-ops deploy database --env dev +``` + +Local development deliberately uses native dev processes and Docker Compose. +Ansible remains the remote deployment/configuration mechanism. diff --git a/acupedia_ops/__init__.py b/acupedia_ops/__init__.py new file mode 100644 index 0000000..6675d78 --- /dev/null +++ b/acupedia_ops/__init__.py @@ -0,0 +1,2 @@ +"""AccuPedia operational tooling.""" +__version__ = "0.1.0" diff --git a/acupedia_ops/ansible/__init__.py b/acupedia_ops/ansible/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/acupedia_ops/ansible/runner.py b/acupedia_ops/ansible/runner.py new file mode 100644 index 0000000..24c00e4 --- /dev/null +++ b/acupedia_ops/ansible/runner.py @@ -0,0 +1,14 @@ +from __future__ import annotations +from typing import Any +from acupedia_ops.common.paths import ansible_root + +def run_playbook(*, playbook: str, inventory: str, extra_vars: dict[str, Any] | None = None) -> None: + try: + import ansible_runner + except ImportError as exc: + raise RuntimeError('Install deployment support with: pip install -e ".[deployment]"') from exc + root = ansible_root(); inventory_path = root / "inventories" / inventory; playbook_path = root / "playbooks" / playbook + if not inventory_path.exists(): raise FileNotFoundError(f"Inventory not found: {inventory_path}") + if not playbook_path.exists(): raise FileNotFoundError(f"Playbook not found: {playbook_path}") + result = ansible_runner.run(private_data_dir=str(root), inventory=str(inventory_path), playbook=str(playbook_path), extravars=extra_vars or {}) + if result.rc != 0: raise RuntimeError(f"Ansible playbook failed with exit code {result.rc}: {playbook_path}") diff --git a/acupedia_ops/bootstrap/__init__.py b/acupedia_ops/bootstrap/__init__.py new file mode 100644 index 0000000..b557edc --- /dev/null +++ b/acupedia_ops/bootstrap/__init__.py @@ -0,0 +1,13 @@ +from acupedia_ops.bootstrap.api_cli import ( + VALID_TARGETS, + resolve_api_root, + resolve_bootstrap_command, + run_api_bootstrap, +) + +__all__ = [ + "VALID_TARGETS", + "resolve_api_root", + "resolve_bootstrap_command", + "run_api_bootstrap", +] diff --git a/acupedia_ops/bootstrap/api_cli.py b/acupedia_ops/bootstrap/api_cli.py new file mode 100644 index 0000000..19a043c --- /dev/null +++ b/acupedia_ops/bootstrap/api_cli.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +import os +import shutil +from pathlib import Path +from typing import Mapping, Sequence + +from acupedia_ops.common.process import run_command +from acupedia_ops.common.workspace_paths import ( + resolve_command, + resolve_workspace_path, + workspace_base_path, +) + + +VALID_TARGETS = {"auth", "content", "media", "commerce", "all", "validate"} + + +def resolve_api_root(api_root: Path | None = None) -> Path: + base = workspace_base_path(required=False) + + if api_root is not None: + root = resolve_workspace_path( + api_root, + base_path=base, + ) if not Path(api_root).expanduser().is_absolute() else Path(api_root).expanduser().resolve() + else: + raw = os.environ.get("ACUPEDIA_API_PATH", "").strip() + if not raw: + raise RuntimeError( + "AccuPedia API path is required. Supply --api-root or set " + "ACUPEDIA_API_PATH." + ) + root = resolve_workspace_path(raw, base_path=base) + + if not root.is_dir(): + raise FileNotFoundError(f"AccuPedia API repository not found: {root}") + + if not (root / "app").is_dir(): + raise ValueError(f"Invalid AccuPedia API repository; missing: {root / 'app'}") + + if not (root / "pyproject.toml").is_file(): + raise ValueError( + f"Invalid AccuPedia API repository; missing: {root / 'pyproject.toml'}" + ) + + return root + + +def resolve_bootstrap_command(api_root: Path) -> list[str]: + """Resolve the backend-owned acupedia-bootstrap executable. + + Preference: + 1. ACUPEDIA_API_BOOTSTRAP_COMMAND + 2. API repo .venv script + 3. globally available acupedia-bootstrap + 4. `uv run acupedia-bootstrap` from the API repo + """ + configured = os.environ.get("ACUPEDIA_API_BOOTSTRAP_COMMAND", "").strip() + if configured: + return resolve_command( + configured, + base_path=workspace_base_path(required=False), + ) + + local_script = api_root / ".venv" / "bin" / "acupedia-bootstrap" + if local_script.is_file() and os.access(local_script, os.X_OK): + return [str(local_script)] + + global_script = shutil.which("acupedia-bootstrap") + if global_script: + return [global_script] + + if shutil.which("uv"): + return ["uv", "run", "acupedia-bootstrap"] + + raise RuntimeError( + "Unable to locate the acupedia-api bootstrap CLI. " + "Create the API virtual environment/install the project, install uv, " + "or set ACUPEDIA_API_BOOTSTRAP_COMMAND." + ) + + +def run_api_bootstrap( + *, + target: str, + api_root: Path | None = None, + environment: str | None = None, + extra_args: Sequence[str] = (), + extra_env: Mapping[str, str] | None = None, +) -> None: + if target not in VALID_TARGETS: + raise ValueError( + f"Unsupported bootstrap target {target!r}; " + f"expected one of: {', '.join(sorted(VALID_TARGETS))}" + ) + + root = resolve_api_root(api_root) + command = [ + *resolve_bootstrap_command(root), + target, + *[str(arg) for arg in extra_args], + ] + + env = dict(extra_env or {}) + if environment: + env["ACUPEDIA_ENV"] = environment + + run_command(command, cwd=root, env=env or None) diff --git a/acupedia_ops/cli.py b/acupedia_ops/cli.py new file mode 100644 index 0000000..b97d321 --- /dev/null +++ b/acupedia_ops/cli.py @@ -0,0 +1,424 @@ +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path + +from acupedia_ops.bootstrap.api_cli import VALID_TARGETS, run_api_bootstrap +from acupedia_ops.common.env import load_env_file +from acupedia_ops.common.paths import repo_root +from acupedia_ops.data.image.clean_image_borders import process_path +from acupedia_ops.deployment.backend import deploy_backend +from acupedia_ops.deployment.database import deploy_database +from acupedia_ops.deployment.gitea_runner import provision_runner, remove_runner +from acupedia_ops.local.bootstrap import local_bootstrap +from acupedia_ops.local.database import reset_local_database +from acupedia_ops.local.git_status import repository_status +from acupedia_ops.local.infrastructure import ( + infra_down, + infra_logs, + infra_restart, + infra_status, + infra_up, +) +from acupedia_ops.local.services import run_component, setup_components +from acupedia_ops.local.validation import has_errors, validate_workspace +from acupedia_ops.local.workspace import load_local_workspace + + +LOCAL_COMPONENTS = ("api", "mobile", "web", "admin") + + +def _build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="acupedia-ops", + description="AccuPedia operational tooling", + ) + parser.add_argument( + "--env-file", + type=Path, + default=None, + help="Local workspace .env file. Defaults to /.env.", + ) + + subparsers = parser.add_subparsers(dest="command", required=True) + + # Local development ------------------------------------------------- + local_parser = subparsers.add_parser( + "local", + help="Local development orchestration", + ) + local_sub = local_parser.add_subparsers( + dest="local_command", + required=True, + ) + + local_sub.add_parser( + "validate", + help="Validate local repository paths and configuration", + ) + + setup = local_sub.add_parser( + "setup", + help="Validate workspace and optionally install component dependencies", + ) + setup.add_argument( + "--component", + action="append", + choices=LOCAL_COMPONENTS, + help="Component to set up. Repeat as needed. Defaults to all.", + ) + setup.add_argument( + "--install", + action="store_true", + help="Run configured setup commands after validation", + ) + + status = local_sub.add_parser( + "status", + help="Show local repository and infrastructure status", + ) + status.add_argument("--json", action="store_true") + + run = local_sub.add_parser( + "run", + help="Run one component in its native development mode", + ) + run.add_argument("component", choices=LOCAL_COMPONENTS) + + infra_up_parser = local_sub.add_parser( + "infra-up", + help="Start local Docker Compose infrastructure", + ) + infra_up_parser.add_argument("--build", action="store_true") + infra_up_parser.add_argument("services", nargs="*") + + infra_down_parser = local_sub.add_parser( + "infra-down", + help="Stop local Docker Compose infrastructure", + ) + infra_down_parser.add_argument( + "--volumes", + action="store_true", + help="Also delete named volumes; destructive", + ) + + infra_restart_parser = local_sub.add_parser( + "infra-restart", + help="Restart local infrastructure services", + ) + infra_restart_parser.add_argument("services", nargs="*") + + local_sub.add_parser( + "infra-status", + help="Show Docker Compose infrastructure state", + ) + + logs = local_sub.add_parser( + "logs", + help="Show local infrastructure logs", + ) + logs.add_argument("services", nargs="*") + logs.add_argument("--follow", "-f", action="store_true") + logs.add_argument("--tail", type=int, default=200) + + bootstrap = local_sub.add_parser( + "bootstrap", + help="Invoke acupedia-api bootstrap using local content paths", + ) + bootstrap.add_argument( + "target", + nargs="?", + choices=sorted(VALID_TARGETS), + help="Defaults to bootstrap.default_target in config/local.yaml", + ) + bootstrap.add_argument( + "--publish-content", + action="store_true", + help="Publish content during content/all bootstrap", + ) + bootstrap.add_argument( + "bootstrap_args", + nargs=argparse.REMAINDER, + help="Additional arguments forwarded to acupedia-api after '--'", + ) + + reset_db = local_sub.add_parser( + "reset-db", + help="Use the backend-owned data reset CLI", + ) + reset_db.add_argument( + "--execute", + action="store_true", + help="Actually execute reset. Without this, backend dry-run is used.", + ) + reset_db.add_argument( + "reset_args", + nargs=argparse.REMAINDER, + help="Additional backend reset arguments after '--'", + ) + + # Image preprocessing ----------------------------------------------- + image_parser = subparsers.add_parser( + "image", + help="Image preprocessing operations", + ) + image_sub = image_parser.add_subparsers(dest="image_command", required=True) + clean = image_sub.add_parser("clean-border") + clean.add_argument("input", type=Path) + clean.add_argument("output", type=Path) + clean.add_argument("--border-fraction", type=float, default=0.035) + clean.add_argument("--difference-threshold", type=float, default=18.0) + clean.add_argument("--max-component-depth", type=float, default=0.025) + clean.add_argument("--max-edge-px", type=int, default=12) + clean.add_argument("--line-coverage", type=float, default=0.35) + + # Backend bootstrap adapter ----------------------------------------- + backend_bootstrap = subparsers.add_parser( + "bootstrap", + help="Direct adapter to the acupedia-api bootstrap CLI", + ) + backend_bootstrap.add_argument("target", choices=sorted(VALID_TARGETS)) + backend_bootstrap.add_argument("--api-root", type=Path) + backend_bootstrap.add_argument( + "--env", + dest="environment", + choices=("dev", "staging", "prod"), + ) + backend_bootstrap.add_argument("bootstrap_args", nargs=argparse.REMAINDER) + + # Remote deployment ------------------------------------------------- + deploy = subparsers.add_parser("deploy") + deploy_sub = deploy.add_subparsers(dest="deploy_command", required=True) + backend = deploy_sub.add_parser("backend") + backend.add_argument("--env", required=True, choices=("dev", "staging", "prod")) + database = deploy_sub.add_parser("database") + database.add_argument("--env", required=True, choices=("dev", "staging", "prod")) + + # Gitea runner lifecycle -------------------------------------------- + runner = subparsers.add_parser("runner") + runner_sub = runner.add_subparsers(dest="runner_command", required=True) + + provision = runner_sub.add_parser("provision") + provision.add_argument("--inventory", type=Path, required=True) + provision.add_argument("--limit") + provision.add_argument( + "--registration-token", + default=os.environ.get("GITEA_RUNNER_REGISTRATION_TOKEN"), + ) + provision.add_argument("--force-reregister", action="store_true") + provision.add_argument("--extra-var", action="append", default=[]) + + remove = runner_sub.add_parser("remove") + remove.add_argument("--inventory", type=Path, required=True) + remove.add_argument("--limit") + remove.add_argument("--remove-data", action="store_true") + remove.add_argument("--extra-var", action="append", default=[]) + + return parser + + +def _load_env(path: Path | None) -> None: + load_env_file(path or (repo_root() / ".env"), override=False) + + +def _forwarded(values: list[str]) -> list[str]: + result = list(values) + if result and result[0] == "--": + result = result[1:] + return result + + +def _print_validation(workspace) -> int: + issues = validate_workspace(workspace) + if not issues: + print("Local workspace validation: OK") + return 0 + + for issue in issues: + print(f"[{issue.level.upper()}] {issue.component}: {issue.message}") + return 1 if has_errors(issues) else 0 + + +def main() -> None: + parser = _build_parser() + args = parser.parse_args() + _load_env(args.env_file) + + if args.command == "local": + workspace = load_local_workspace(env_file=args.env_file) + + if args.local_command == "validate": + raise SystemExit(_print_validation(workspace)) + + if args.local_command == "setup": + exit_code = _print_validation(workspace) + if exit_code: + raise SystemExit(exit_code) + components = args.component or list(LOCAL_COMPONENTS) + if args.install: + setup_components(workspace, components) + else: + print( + "Validation completed. Dependency installation was not run; " + "use --install to run configured setup commands." + ) + return + + if args.local_command == "status": + rows = [] + for component, path in workspace.paths.items(): + status = repository_status(path) if path.exists() else None + rows.append( + { + "component": component, + "path": str(path), + "exists": path.exists(), + "git": bool(status and status.is_git_repo), + "branch": status.branch if status else None, + "revision": status.revision if status else None, + "dirty": status.dirty if status else None, + } + ) + + if args.json: + print(json.dumps(rows, indent=2)) + else: + for row in rows: + state = "missing" if not row["exists"] else "ok" + git = "" + if row["git"]: + dirty = "*" if row["dirty"] else "" + git = f" git={row['branch'] or '-'}@{row['revision'] or '-'}{dirty}" + print( + f"{row['component']:8} {state:7} {row['path']}{git}" + ) + + if workspace.infra.compose_file.exists(): + result = infra_status(workspace) + if result.stdout: + print("\nInfrastructure:\n" + result.stdout.rstrip()) + else: + print( + "\nInfrastructure: compose file not configured/found " + f"({workspace.infra.compose_file})" + ) + return + + if args.local_command == "run": + run_component(workspace, args.component) + return + + if args.local_command == "infra-up": + infra_up( + workspace, + build=args.build, + services=args.services, + ) + return + + if args.local_command == "infra-down": + infra_down(workspace, volumes=args.volumes) + return + + if args.local_command == "infra-restart": + infra_restart(workspace, services=args.services) + return + + if args.local_command == "infra-status": + result = infra_status(workspace) + if result.stdout: + print(result.stdout, end="") + if result.stderr: + print(result.stderr, end="") + raise SystemExit(result.returncode) + + if args.local_command == "logs": + infra_logs( + workspace, + services=args.services, + follow=args.follow, + tail=args.tail, + ) + return + + if args.local_command == "bootstrap": + local_bootstrap( + workspace, + target=args.target, + publish_content=args.publish_content, + extra_args=_forwarded(args.bootstrap_args), + ) + return + + if args.local_command == "reset-db": + reset_local_database( + workspace, + execute=args.execute, + extra_args=tuple(_forwarded(args.reset_args)), + ) + return + + if args.command == "image" and args.image_command == "clean-border": + result = process_path( + input_path=args.input, + output_path=args.output, + border_fraction=args.border_fraction, + difference_threshold=args.difference_threshold, + max_component_depth_fraction=args.max_component_depth, + max_edge_px=args.max_edge_px, + line_coverage=args.line_coverage, + ) + print(f"Processed images : {result.processed}") + print(f"Skipped images : {result.skipped}") + print(f"Copied files : {result.copied}") + print(f"Output : {result.output}") + return + + if args.command == "bootstrap": + run_api_bootstrap( + target=args.target, + api_root=args.api_root, + environment=args.environment, + extra_args=_forwarded(args.bootstrap_args), + ) + return + + if args.command == "deploy" and args.deploy_command == "backend": + deploy_backend(environment=args.env) + return + + if args.command == "deploy" and args.deploy_command == "database": + deploy_database(environment=args.env) + return + + if args.command == "runner" and args.runner_command == "provision": + token = args.registration_token + if not token: + parser.error( + "--registration-token or GITEA_RUNNER_REGISTRATION_TOKEN is required" + ) + provision_runner( + inventory=args.inventory, + registration_token=token, + limit=args.limit, + extra_vars=args.extra_var, + force_reregister=args.force_reregister, + ) + return + + if args.command == "runner" and args.runner_command == "remove": + remove_runner( + inventory=args.inventory, + limit=args.limit, + remove_data=args.remove_data, + extra_vars=args.extra_var, + ) + return + + parser.error("Unsupported command") + + +if __name__ == "__main__": + main() diff --git a/acupedia_ops/common/__init__.py b/acupedia_ops/common/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/acupedia_ops/common/config.py b/acupedia_ops/common/config.py new file mode 100644 index 0000000..8693c1c --- /dev/null +++ b/acupedia_ops/common/config.py @@ -0,0 +1,20 @@ +from __future__ import annotations +from dataclasses import dataclass +from pathlib import Path +from typing import Any +import yaml + +@dataclass(frozen=True) +class OpsConfig: + environment: str + values: dict[str, Any] + +def load_config(environment: str, config_root: Path | None = None) -> OpsConfig: + root = config_root or Path(__file__).resolve().parents[2] / "config" + path = root / f"{environment}.yaml" + if not path.exists(): + raise FileNotFoundError(f"Configuration not found: {path}") + values = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + if not isinstance(values, dict): + raise ValueError(f"Configuration root must be a mapping: {path}") + return OpsConfig(environment=environment, values=values) diff --git a/acupedia_ops/common/env.py b/acupedia_ops/common/env.py new file mode 100644 index 0000000..ce01eb1 --- /dev/null +++ b/acupedia_ops/common/env.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +import os +from pathlib import Path +from typing import Mapping + + +class EnvFileError(ValueError): + """Raised when a local .env file contains malformed entries.""" + + +def _strip_quotes(value: str) -> str: + value = value.strip() + if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}: + return value[1:-1] + return value + + +def parse_env_file(path: Path) -> dict[str, str]: + """Parse a deliberately small, predictable dotenv subset. + + Supported syntax: + NAME=value + export NAME=value + blank lines + # comments + + Shell expansion and command substitution are intentionally not supported. + """ + values: dict[str, str] = {} + + if not path.exists(): + return values + + for line_number, raw_line in enumerate( + path.read_text(encoding="utf-8").splitlines(), + start=1, + ): + line = raw_line.strip() + + if not line or line.startswith("#"): + continue + + if line.startswith("export "): + line = line[len("export "):].lstrip() + + if "=" not in line: + raise EnvFileError( + f"Invalid .env entry at {path}:{line_number}: expected NAME=value" + ) + + key, raw_value = line.split("=", 1) + key = key.strip() + if not key or not key.replace("_", "").isalnum() or key[0].isdigit(): + raise EnvFileError( + f"Invalid environment variable name at {path}:{line_number}: {key!r}" + ) + + values[key] = _strip_quotes(raw_value) + + return values + + +def load_env_file( + path: Path, + *, + override: bool = False, +) -> dict[str, str]: + values = parse_env_file(path) + for key, value in values.items(): + if override or key not in os.environ: + os.environ[key] = value + return values + + +def merged_environment( + *sources: Mapping[str, str] | None, +) -> dict[str, str]: + result = dict(os.environ) + for source in sources: + if source: + result.update({str(k): str(v) for k, v in source.items()}) + return result diff --git a/acupedia_ops/common/logging.py b/acupedia_ops/common/logging.py new file mode 100644 index 0000000..a7d0b2e --- /dev/null +++ b/acupedia_ops/common/logging.py @@ -0,0 +1,4 @@ +import logging + +def configure_logging(level: int = logging.INFO) -> None: + logging.basicConfig(level=level, format="%(asctime)s %(levelname)s %(name)s %(message)s") diff --git a/acupedia_ops/common/paths.py b/acupedia_ops/common/paths.py new file mode 100644 index 0000000..7bd9924 --- /dev/null +++ b/acupedia_ops/common/paths.py @@ -0,0 +1,7 @@ +from pathlib import Path + +def repo_root() -> Path: + return Path(__file__).resolve().parents[2] + +def ansible_root() -> Path: + return repo_root() / "ansible" diff --git a/acupedia_ops/common/process.py b/acupedia_ops/common/process.py new file mode 100644 index 0000000..d7045bc --- /dev/null +++ b/acupedia_ops/common/process.py @@ -0,0 +1,85 @@ +from __future__ import annotations + +import os +import shlex +import shutil +import subprocess +from dataclasses import dataclass +from pathlib import Path +from typing import Mapping, Sequence + + +class CommandNotFoundError(RuntimeError): + pass + + +@dataclass(frozen=True) +class CommandResult: + command: tuple[str, ...] + returncode: int + stdout: str + stderr: str + + +def command_exists(command: str) -> bool: + if "/" in command: + path = Path(command).expanduser() + return path.exists() and os.access(path, os.X_OK) + return shutil.which(command) is not None + + +def quote_command(command: Sequence[str]) -> str: + return " ".join(shlex.quote(str(part)) for part in command) + + +def require_command(command: str) -> None: + if not command_exists(command): + raise CommandNotFoundError(f"Required command not found: {command}") + + +def _effective_env(env: Mapping[str, str] | None) -> dict[str, str] | None: + if env is None: + return None + effective = dict(os.environ) + effective.update({str(key): str(value) for key, value in env.items()}) + return effective + + +def run_command( + command: Sequence[str], + *, + cwd: Path | None = None, + env: Mapping[str, str] | None = None, + capture: bool = False, + check: bool = True, +) -> CommandResult: + if not command: + raise ValueError("Command cannot be empty") + + require_command(str(command[0])) + + completed = subprocess.run( + [str(part) for part in command], + cwd=str(cwd) if cwd else None, + env=_effective_env(env), + check=False, + text=True, + capture_output=capture, + ) + + result = CommandResult( + command=tuple(str(part) for part in command), + returncode=completed.returncode, + stdout=completed.stdout or "", + stderr=completed.stderr or "", + ) + + if check and completed.returncode != 0: + raise subprocess.CalledProcessError( + completed.returncode, + list(result.command), + output=result.stdout, + stderr=result.stderr, + ) + + return result diff --git a/acupedia_ops/common/workspace_paths.py b/acupedia_ops/common/workspace_paths.py new file mode 100644 index 0000000..8c4938b --- /dev/null +++ b/acupedia_ops/common/workspace_paths.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import os +import shlex +from pathlib import Path +from typing import Sequence + + +WORKSPACE_BASE_ENV = "ACUPEDIA_WORKSPACE_BASE_PATH" + + +def workspace_base_path( + value: str | Path | None = None, + *, + required: bool = True, +) -> Path | None: + """Return the AccuPedia workspace base path. + + Resolution order: + 1. explicit value + 2. ACUPEDIA_WORKSPACE_BASE_PATH + + The workspace base path itself must be absolute. This removes any + dependency on the caller's current working directory. + """ + raw = str(value).strip() if value is not None else os.environ.get( + WORKSPACE_BASE_ENV, + "", + ).strip() + + if not raw: + if required: + raise RuntimeError( + f"{WORKSPACE_BASE_ENV} is required for relative AccuPedia paths." + ) + return None + + path = Path(raw).expanduser() + if not path.is_absolute(): + raise ValueError( + f"{WORKSPACE_BASE_ENV} must be an absolute path: {raw!r}" + ) + + return path.resolve() + + +def resolve_workspace_path( + value: str | Path, + *, + base_path: Path | None = None, +) -> Path: + """Resolve an AccuPedia path deterministically. + + Absolute paths are used as-is. + Relative paths are always resolved against ACUPEDIA_WORKSPACE_BASE_PATH, + never against the process current working directory. + """ + path = Path(value).expanduser() + + if path.is_absolute(): + return path.resolve() + + base = base_path or workspace_base_path(required=True) + assert base is not None + return (base / path).resolve() + + +def resolve_env_path( + env_name: str, + *, + required: bool = True, + base_path: Path | None = None, +) -> Path | None: + raw = os.environ.get(env_name, "").strip() + + if not raw: + if required: + raise RuntimeError(f"Missing required environment variable: {env_name}") + return None + + return resolve_workspace_path(raw, base_path=base_path) + + +def resolve_command( + raw_command: str, + *, + base_path: Path | None = None, +) -> list[str]: + """Parse a command and resolve a relative executable path against workspace. + + Only the executable token is path-resolved when it clearly names a path + (contains '/' or begins with '.'). Remaining arguments are preserved. + """ + command = shlex.split(raw_command) + if not command: + raise ValueError("Command cannot be empty") + + executable = command[0] + if "/" in executable or executable.startswith("."): + command[0] = str( + resolve_workspace_path( + executable, + base_path=base_path, + ) + ) + + return command diff --git a/acupedia_ops/data/__init__.py b/acupedia_ops/data/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/acupedia_ops/data/content/__init__.py b/acupedia_ops/data/content/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/acupedia_ops/data/content/normalize_content.py b/acupedia_ops/data/content/normalize_content.py new file mode 100644 index 0000000..915b63c --- /dev/null +++ b/acupedia_ops/data/content/normalize_content.py @@ -0,0 +1,2 @@ +def normalize_content(*args, **kwargs): + raise NotImplementedError("Content normalization is not implemented yet") diff --git a/acupedia_ops/data/content/sanitize_json.py b/acupedia_ops/data/content/sanitize_json.py new file mode 100644 index 0000000..b4609cb --- /dev/null +++ b/acupedia_ops/data/content/sanitize_json.py @@ -0,0 +1,2 @@ +def sanitize_json(*args, **kwargs): + raise NotImplementedError("JSON sanitization is not implemented yet") diff --git a/acupedia_ops/data/content/validate_content_refs.py b/acupedia_ops/data/content/validate_content_refs.py new file mode 100644 index 0000000..253c103 --- /dev/null +++ b/acupedia_ops/data/content/validate_content_refs.py @@ -0,0 +1,2 @@ +def validate_content_refs(*args, **kwargs): + raise NotImplementedError("Content reference validation is not implemented yet") diff --git a/acupedia_ops/data/image/__init__.py b/acupedia_ops/data/image/__init__.py new file mode 100644 index 0000000..f908b8c --- /dev/null +++ b/acupedia_ops/data/image/__init__.py @@ -0,0 +1 @@ +from .clean_image_borders import BorderCleanupResult, clean_image, process_path diff --git a/acupedia_ops/data/image/clean_image_borders.py b/acupedia_ops/data/image/clean_image_borders.py new file mode 100644 index 0000000..3c85bd7 --- /dev/null +++ b/acupedia_ops/data/image/clean_image_borders.py @@ -0,0 +1,133 @@ +from __future__ import annotations +import shutil +import tempfile +import zipfile +from dataclasses import dataclass +from pathlib import Path +import cv2 +import numpy as np + +SUPPORTED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff"} + +@dataclass(frozen=True) +class BorderCleanupResult: + processed: int + skipped: int + copied: int + output: Path + +def _estimate_background(image: np.ndarray, sample_size: int = 20) -> np.ndarray: + h, w = image.shape[:2] + s = min(sample_size, max(1, h // 4), max(1, w // 4)) + patches = [image[:s, :s], image[:s, w-s:], image[h-s:, :s], image[h-s:, w-s:]] + pixels = np.concatenate([p.reshape(-1, image.shape[2]) for p in patches], axis=0) + return np.median(pixels, axis=0).astype(np.uint8) + +def _background_distance(image: np.ndarray, background: np.ndarray) -> np.ndarray: + img = image.astype(np.int16) + bg = background.astype(np.int16) + img_f = img.astype(np.float32, copy=False) + bg_f = np.asarray(bg, dtype=np.float32) + delta = img_f - bg_f + return np.sqrt(np.sum(delta * delta, axis=2)) + +def _detect_full_edge_lines(image: np.ndarray, background: np.ndarray, *, max_edge_px: int, difference_threshold: float, line_coverage: float) -> np.ndarray: + h, w = image.shape[:2] + non_background = _background_distance(image, background) > difference_threshold + mask = np.zeros((h, w), dtype=np.uint8) + edge_x = min(max_edge_px, max(1, w // 10)) + edge_y = min(max_edge_px, max(1, h // 10)) + for x in range(edge_x): + if float(np.mean(non_background[:, x])) >= line_coverage: mask[:, x] = 255 + for x in range(w-edge_x, w): + if float(np.mean(non_background[:, x])) >= line_coverage: mask[:, x] = 255 + for y in range(edge_y): + if float(np.mean(non_background[y, :])) >= line_coverage: mask[y, :] = 255 + for y in range(h-edge_y, h): + if float(np.mean(non_background[y, :])) >= line_coverage: mask[y, :] = 255 + return mask + +def _detect_edge_connected_artifacts(image: np.ndarray, background: np.ndarray, *, border_fraction: float, difference_threshold: float, max_component_depth_fraction: float) -> np.ndarray: + h, w = image.shape[:2] + candidate = (_background_distance(image, background) > difference_threshold).astype(np.uint8) + bx, by = max(2, int(w * border_fraction)), max(2, int(h * border_fraction)) + border_region = np.zeros((h, w), dtype=np.uint8) + border_region[:, :bx] = 1; border_region[:, w-bx:] = 1 + border_region[:by, :] = 1; border_region[h-by:, :] = 1 + candidate *= border_region + count, labels, stats, _ = cv2.connectedComponentsWithStats(candidate, connectivity=8) + output = np.zeros((h, w), dtype=np.uint8) + max_dx, max_dy = max(3, int(w * max_component_depth_fraction)), max(3, int(h * max_component_depth_fraction)) + for component_id in range(1, count): + x, y, cw, ch, _ = stats[component_id] + x2, y2 = x + cw, y + ch + shallow = ((x == 0 and x2 <= max_dx) or (x2 >= w and x >= w-max_dx) or (y == 0 and y2 <= max_dy) or (y2 >= h and y >= h-max_dy)) + if shallow: output[labels == component_id] = 255 + return output + +def _write_image(path: Path, image: np.ndarray) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + ext = path.suffix.lower() + if ext in {".jpg", ".jpeg"}: ok = cv2.imwrite(str(path), image, [cv2.IMWRITE_JPEG_QUALITY, 98]) + elif ext == ".png": ok = cv2.imwrite(str(path), image, [cv2.IMWRITE_PNG_COMPRESSION, 3]) + elif ext == ".webp": ok = cv2.imwrite(str(path), image, [cv2.IMWRITE_WEBP_QUALITY, 98]) + else: ok = cv2.imwrite(str(path), image) + if not ok: raise RuntimeError(f"Unable to write image: {path}") + +def clean_image(input_path: Path, output_path: Path, *, border_fraction: float = 0.035, difference_threshold: float = 18.0, max_component_depth_fraction: float = 0.025, max_edge_px: int = 12, line_coverage: float = 0.35) -> bool: + input_path, output_path = Path(input_path), Path(output_path) + image = cv2.imread(str(input_path), cv2.IMREAD_COLOR) + if image is None: return False + original_shape = image.shape + background = _estimate_background(image) + mask = cv2.bitwise_or( + _detect_edge_connected_artifacts(image, background, border_fraction=border_fraction, difference_threshold=difference_threshold, max_component_depth_fraction=max_component_depth_fraction), + _detect_full_edge_lines(image, background, max_edge_px=max_edge_px, difference_threshold=difference_threshold, line_coverage=line_coverage), + ) + cleaned = image.copy() + cleaned[mask > 0] = background + if cleaned.shape != original_shape: raise RuntimeError(f"Image dimensions changed unexpectedly: {input_path}") + _write_image(output_path, cleaned) + return True + +def _process_directory(input_dir: Path, output_dir: Path, **options: object) -> BorderCleanupResult: + processed = skipped = copied = 0 + for source in sorted(input_dir.rglob("*")): + if not source.is_file(): continue + target = output_dir / source.relative_to(input_dir) + if source.suffix.lower() not in SUPPORTED_EXTENSIONS: + target.parent.mkdir(parents=True, exist_ok=True); shutil.copy2(source, target); copied += 1; continue + if clean_image(source, target, **options): processed += 1 + else: skipped += 1 + return BorderCleanupResult(processed, skipped, copied, output_dir) + +def _extract_zip(zip_path: Path, destination: Path) -> None: + with zipfile.ZipFile(zip_path, "r") as archive: + root = destination.resolve() + for member in archive.infolist(): + resolved = (destination / member.filename).resolve() + if resolved != root and root not in resolved.parents: raise ValueError(f"Unsafe ZIP entry rejected: {member.filename}") + archive.extractall(destination) + +def _create_zip(source_dir: Path, output_zip: Path) -> None: + output_zip.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(output_zip, "w", zipfile.ZIP_DEFLATED) as archive: + for path in sorted(source_dir.rglob("*")): + if path.is_file(): archive.write(path, path.relative_to(source_dir)) + +def process_path(input_path: Path, output_path: Path, *, border_fraction: float = 0.035, difference_threshold: float = 18.0, max_component_depth_fraction: float = 0.025, max_edge_px: int = 12, line_coverage: float = 0.35) -> BorderCleanupResult: + input_path, output_path = Path(input_path).resolve(), Path(output_path).resolve() + options = dict(border_fraction=border_fraction, difference_threshold=difference_threshold, max_component_depth_fraction=max_component_depth_fraction, max_edge_px=max_edge_px, line_coverage=line_coverage) + if input_path.is_dir(): return _process_directory(input_path, output_path, **options) + if not input_path.is_file(): raise FileNotFoundError(f"Input not found: {input_path}") + if input_path.suffix.lower() in SUPPORTED_EXTENSIONS: + ok = clean_image(input_path, output_path, **options) + return BorderCleanupResult(1 if ok else 0, 0 if ok else 1, 0, output_path) + if input_path.suffix.lower() == ".zip": + if output_path.suffix.lower() != ".zip": raise ValueError("ZIP input requires a .zip output path") + with tempfile.TemporaryDirectory(prefix="acupedia-ops-image-clean-") as temp: + temp_root = Path(temp); extracted = temp_root / "input"; cleaned = temp_root / "output" + extracted.mkdir(); cleaned.mkdir(); _extract_zip(input_path, extracted) + result = _process_directory(extracted, cleaned, **options); _create_zip(cleaned, output_path) + return BorderCleanupResult(result.processed, result.skipped, result.copied, output_path) + raise ValueError("Input must be a supported image, directory, or ZIP archive") diff --git a/acupedia_ops/data/image/normalize_images.py b/acupedia_ops/data/image/normalize_images.py new file mode 100644 index 0000000..e126d36 --- /dev/null +++ b/acupedia_ops/data/image/normalize_images.py @@ -0,0 +1,2 @@ +def normalize_images(*args, **kwargs): + raise NotImplementedError("Image normalization is not implemented yet") diff --git a/acupedia_ops/data/image/resize_images.py b/acupedia_ops/data/image/resize_images.py new file mode 100644 index 0000000..31e5f38 --- /dev/null +++ b/acupedia_ops/data/image/resize_images.py @@ -0,0 +1,2 @@ +def resize_images(*args, **kwargs): + raise NotImplementedError("Image resizing is not implemented yet") diff --git a/acupedia_ops/data/templates/__init__.py b/acupedia_ops/data/templates/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/acupedia_ops/data/templates/add_display_order.py b/acupedia_ops/data/templates/add_display_order.py new file mode 100644 index 0000000..a1f9921 --- /dev/null +++ b/acupedia_ops/data/templates/add_display_order.py @@ -0,0 +1,2 @@ +def add_display_order(*args, **kwargs): + raise NotImplementedError("Display-order augmentation is not implemented yet") diff --git a/acupedia_ops/data/templates/validate_templates.py b/acupedia_ops/data/templates/validate_templates.py new file mode 100644 index 0000000..a663ed5 --- /dev/null +++ b/acupedia_ops/data/templates/validate_templates.py @@ -0,0 +1,2 @@ +def validate_templates(*args, **kwargs): + raise NotImplementedError("Template validation is not implemented yet") diff --git a/acupedia_ops/deployment/__init__.py b/acupedia_ops/deployment/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/acupedia_ops/deployment/backend.py b/acupedia_ops/deployment/backend.py new file mode 100644 index 0000000..57a02f7 --- /dev/null +++ b/acupedia_ops/deployment/backend.py @@ -0,0 +1,5 @@ +from acupedia_ops.ansible.runner import run_playbook +from acupedia_ops.common.config import load_config + +def deploy_backend(environment: str) -> None: + c=load_config(environment); run_playbook(playbook="backend.yml", inventory=environment, extra_vars=c.values.get("backend", {})) diff --git a/acupedia_ops/deployment/database.py b/acupedia_ops/deployment/database.py new file mode 100644 index 0000000..3cadd1b --- /dev/null +++ b/acupedia_ops/deployment/database.py @@ -0,0 +1,5 @@ +from acupedia_ops.ansible.runner import run_playbook +from acupedia_ops.common.config import load_config + +def deploy_database(environment: str) -> None: + c=load_config(environment); run_playbook(playbook="database.yml", inventory=environment, extra_vars=c.values.get("database", {})) diff --git a/acupedia_ops/deployment/gitea_runner.py b/acupedia_ops/deployment/gitea_runner.py new file mode 100644 index 0000000..c158e5a --- /dev/null +++ b/acupedia_ops/deployment/gitea_runner.py @@ -0,0 +1,85 @@ +from __future__ import annotations + +import os +import subprocess +from pathlib import Path +from typing import Sequence + + +def _repo_root() -> Path: + return Path(__file__).resolve().parents[2] + + +def _ansible_playbook() -> str: + return os.environ.get("ANSIBLE_PLAYBOOK_BIN", "ansible-playbook") + + +def provision_runner( + *, + inventory: Path, + registration_token: str, + limit: str | None = None, + extra_vars: Sequence[str] = (), + force_reregister: bool = False, +) -> None: + repo_root = _repo_root() + playbook = repo_root / "ansible" / "playbooks" / "gitea-runner.yml" + + command = [ + _ansible_playbook(), + "-i", + str(inventory), + str(playbook), + "--extra-vars", + f"gitea_runner_registration_token={registration_token}", + ] + + if force_reregister: + command.extend( + [ + "--extra-vars", + "gitea_runner_force_reregister=true", + ] + ) + + for value in extra_vars: + command.extend(["--extra-vars", value]) + + if limit: + command.extend(["--limit", limit]) + + subprocess.run(command, cwd=repo_root, check=True) + + +def remove_runner( + *, + inventory: Path, + limit: str | None = None, + remove_data: bool = False, + extra_vars: Sequence[str] = (), +) -> None: + repo_root = _repo_root() + playbook = repo_root / "ansible" / "playbooks" / "gitea-runner-remove.yml" + + command = [ + _ansible_playbook(), + "-i", + str(inventory), + str(playbook), + ] + + if remove_data: + command.extend( + [ + "--extra-vars", + "gitea_runner_remove_data=true", + ] + ) + + for value in extra_vars: + command.extend(["--extra-vars", value]) + + if limit: + command.extend(["--limit", limit]) + + subprocess.run(command, cwd=repo_root, check=True) diff --git a/acupedia_ops/deployment/infra.py b/acupedia_ops/deployment/infra.py new file mode 100644 index 0000000..0a6b1ca --- /dev/null +++ b/acupedia_ops/deployment/infra.py @@ -0,0 +1,5 @@ +from acupedia_ops.ansible.runner import run_playbook +from acupedia_ops.common.config import load_config + +def deploy_infra(environment: str) -> None: + c=load_config(environment); run_playbook(playbook="infra.yml", inventory=environment, extra_vars=c.values.get("infra", {})) diff --git a/acupedia_ops/deployment/mobile.py b/acupedia_ops/deployment/mobile.py new file mode 100644 index 0000000..fd0363f --- /dev/null +++ b/acupedia_ops/deployment/mobile.py @@ -0,0 +1,2 @@ +def deploy_mobile(environment: str) -> None: + raise NotImplementedError("Mobile deployment is not implemented yet") diff --git a/acupedia_ops/local/__init__.py b/acupedia_ops/local/__init__.py new file mode 100644 index 0000000..8530e11 --- /dev/null +++ b/acupedia_ops/local/__init__.py @@ -0,0 +1,3 @@ +from acupedia_ops.local.workspace import LocalWorkspace, load_local_workspace + +__all__ = ["LocalWorkspace", "load_local_workspace"] diff --git a/acupedia_ops/local/bootstrap.py b/acupedia_ops/local/bootstrap.py new file mode 100644 index 0000000..a30c580 --- /dev/null +++ b/acupedia_ops/local/bootstrap.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import os +from pathlib import Path +from typing import Sequence + +from acupedia_ops.bootstrap.api_cli import run_api_bootstrap +from acupedia_ops.local.workspace import LocalWorkspace + + +def _require(path: Path | None, description: str) -> Path: + if path is None: + raise RuntimeError(f"{description} is not configured") + if not path.exists(): + raise FileNotFoundError(f"{description} not found: {path}") + return path + + +def build_local_bootstrap_args( + workspace: LocalWorkspace, + target: str, + *, + publish_content: bool = False, +) -> list[str]: + defaults = workspace.bootstrap + + if target == "content": + config = _require(defaults.content_config, "Content config") + modules_root = _require(defaults.modules_root, "Content modules root") + args = [ + "--config", + str(config), + "--modules-root", + str(modules_root), + ] + if publish_content: + args.append("--publish-content") + return args + + if target == "media": + manifest = _require(defaults.media_manifest, "Media manifest") + media_root = _require(defaults.media_root, "Media root") + return [ + "--manifest", + str(manifest), + "--media-root", + str(media_root), + ] + + if target == "commerce": + if defaults.commerce_plans is None: + return [] + plans = _require(defaults.commerce_plans, "Commerce plans") + return ["--plans", str(plans)] + + if target == "all": + config = _require(defaults.content_config, "Content config") + modules_root = _require(defaults.modules_root, "Content modules root") + manifest = _require(defaults.media_manifest, "Media manifest") + media_root = _require(defaults.media_root, "Media root") + args = [ + "--content-config", + str(config), + "--content-modules-root", + str(modules_root), + "--media-manifest", + str(manifest), + "--media-media-root", + str(media_root), + ] + if defaults.commerce_plans is not None: + plans = _require(defaults.commerce_plans, "Commerce plans") + args.extend(["--commerce-plans", str(plans)]) + if publish_content: + args.append("--content-publish-content") + return args + + if target in {"auth", "validate"}: + return [] + + raise ValueError(f"Unsupported local bootstrap target: {target}") + + +def local_bootstrap( + workspace: LocalWorkspace, + *, + target: str | None = None, + publish_content: bool = False, + extra_args: Sequence[str] = (), +) -> None: + selected = target or workspace.bootstrap.default_target + generated_args = build_local_bootstrap_args( + workspace, + selected, + publish_content=publish_content, + ) + run_api_bootstrap( + target=selected, + api_root=workspace.path("api"), + extra_args=[*generated_args, *extra_args], + ) diff --git a/acupedia_ops/local/database.py b/acupedia_ops/local/database.py new file mode 100644 index 0000000..d8814a7 --- /dev/null +++ b/acupedia_ops/local/database.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +import os + +from acupedia_ops.bootstrap.api_cli import resolve_api_root +from acupedia_ops.common.process import run_command +from acupedia_ops.common.workspace_paths import ( + resolve_workspace_path, + workspace_base_path, +) +from acupedia_ops.local.workspace import LocalWorkspace + + +def reset_local_database( + workspace: LocalWorkspace, + *, + execute: bool, + extra_args: tuple[str, ...] = (), +) -> None: + """Invoke the backend-owned reset CLI. + + Dry-run is the backend default. `execute=True` adds --execute. + + The reset implementation intentionally remains in acupedia-api because it + owns the ORM/schema semantics and reset safety checks. + """ + api_root = resolve_api_root(workspace.path("api")) + + configured_python = os.environ.get("ACUPEDIA_API_PYTHON", "").strip() + if configured_python: + python = str( + resolve_workspace_path( + configured_python, + base_path=workspace.base_path, + ) + ) + else: + python = str(api_root / ".venv" / "bin" / "python") + + if not workspace.database_reset_command: + command = [ + python, + "-m", + "app.cli.reset", + "--scope", + "all", + ] + else: + command = list(workspace.database_reset_command) + + if execute and "--execute" not in command: + command.append("--execute") + + command.extend(extra_args) + run_command(command, cwd=api_root) diff --git a/acupedia_ops/local/git_status.py b/acupedia_ops/local/git_status.py new file mode 100644 index 0000000..ec843fc --- /dev/null +++ b/acupedia_ops/local/git_status.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +from acupedia_ops.common.process import run_command + + +@dataclass(frozen=True) +class RepositoryStatus: + path: Path + is_git_repo: bool + branch: str | None + dirty: bool | None + revision: str | None + + +def repository_status(path: Path) -> RepositoryStatus: + if not (path / ".git").exists(): + return RepositoryStatus( + path=path, + is_git_repo=False, + branch=None, + dirty=None, + revision=None, + ) + + branch_result = run_command( + ["git", "branch", "--show-current"], + cwd=path, + capture=True, + check=False, + ) + revision_result = run_command( + ["git", "rev-parse", "--short", "HEAD"], + cwd=path, + capture=True, + check=False, + ) + dirty_result = run_command( + ["git", "status", "--porcelain"], + cwd=path, + capture=True, + check=False, + ) + + return RepositoryStatus( + path=path, + is_git_repo=True, + branch=branch_result.stdout.strip() or None, + dirty=bool(dirty_result.stdout.strip()), + revision=revision_result.stdout.strip() or None, + ) diff --git a/acupedia_ops/local/infrastructure.py b/acupedia_ops/local/infrastructure.py new file mode 100644 index 0000000..04cc94e --- /dev/null +++ b/acupedia_ops/local/infrastructure.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import shutil +from pathlib import Path +from typing import Sequence + +from acupedia_ops.common.process import CommandResult, run_command +from acupedia_ops.local.workspace import LocalWorkspace + + +def _compose_command() -> list[str]: + if shutil.which("docker"): + result = run_command( + ["docker", "compose", "version"], + capture=True, + check=False, + ) + if result.returncode == 0: + return ["docker", "compose"] + + if shutil.which("docker-compose"): + return ["docker-compose"] + + raise RuntimeError( + "Docker Compose is required. Install Docker with the compose plugin " + "or docker-compose." + ) + + +def _base(workspace: LocalWorkspace) -> list[str]: + if not workspace.infra.compose_file.exists(): + raise FileNotFoundError( + "Local compose file not found: " + f"{workspace.infra.compose_file}. " + "Set ACUPEDIA_LOCAL_COMPOSE_FILE or configure config/local.yaml." + ) + + return [ + *_compose_command(), + "--project-name", + workspace.infra.project_name, + "--file", + str(workspace.infra.compose_file), + ] + + +def infra_up( + workspace: LocalWorkspace, + *, + build: bool = False, + services: Sequence[str] = (), +) -> None: + command = [*_base(workspace), "up", "--detach"] + if build: + command.append("--build") + command.extend(services) + run_command(command, cwd=workspace.infra.compose_file.parent) + + +def infra_down( + workspace: LocalWorkspace, + *, + volumes: bool = False, + remove_orphans: bool = True, +) -> None: + command = [*_base(workspace), "down"] + if volumes: + command.append("--volumes") + if remove_orphans: + command.append("--remove-orphans") + run_command(command, cwd=workspace.infra.compose_file.parent) + + +def infra_restart( + workspace: LocalWorkspace, + *, + services: Sequence[str] = (), +) -> None: + command = [*_base(workspace), "restart", *services] + run_command(command, cwd=workspace.infra.compose_file.parent) + + +def infra_status(workspace: LocalWorkspace) -> CommandResult: + return run_command( + [*_base(workspace), "ps"], + cwd=workspace.infra.compose_file.parent, + capture=True, + check=False, + ) + + +def infra_logs( + workspace: LocalWorkspace, + *, + services: Sequence[str] = (), + follow: bool = False, + tail: int = 200, +) -> None: + command = [*_base(workspace), "logs", "--tail", str(tail)] + if follow: + command.append("--follow") + command.extend(services) + run_command(command, cwd=workspace.infra.compose_file.parent) diff --git a/acupedia_ops/local/services.py b/acupedia_ops/local/services.py new file mode 100644 index 0000000..5ee27a0 --- /dev/null +++ b/acupedia_ops/local/services.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from typing import Iterable + +from acupedia_ops.common.process import run_command +from acupedia_ops.local.workspace import LocalWorkspace + + +def setup_component( + workspace: LocalWorkspace, + component: str, +) -> None: + config = workspace.components[component] + if not config.setup_command: + raise RuntimeError( + f"No setup command configured for local component: {component}" + ) + run_command(config.setup_command, cwd=workspace.path(component)) + + +def run_component( + workspace: LocalWorkspace, + component: str, +) -> None: + config = workspace.components[component] + if not config.run_command: + raise RuntimeError( + f"No run command configured for local component: {component}" + ) + run_command(config.run_command, cwd=workspace.path(component)) + + +def setup_components( + workspace: LocalWorkspace, + components: Iterable[str], +) -> None: + for component in components: + setup_component(workspace, component) diff --git a/acupedia_ops/local/validation.py b/acupedia_ops/local/validation.py new file mode 100644 index 0000000..6aac0f7 --- /dev/null +++ b/acupedia_ops/local/validation.py @@ -0,0 +1,102 @@ +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +from acupedia_ops.local.workspace import LocalWorkspace + + +@dataclass(frozen=True) +class ValidationIssue: + level: str + component: str + message: str + + +def validate_workspace(workspace: LocalWorkspace) -> list[ValidationIssue]: + issues: list[ValidationIssue] = [] + + for component, path in workspace.paths.items(): + if not path.exists(): + issues.append( + ValidationIssue( + level="error", + component=component, + message=f"path does not exist: {path}", + ) + ) + elif not path.is_dir(): + issues.append( + ValidationIssue( + level="error", + component=component, + message=f"path is not a directory: {path}", + ) + ) + + for component, config in workspace.components.items(): + path = workspace.paths[component] + if not path.is_dir(): + continue + for marker in config.required_markers: + if not (path / marker).exists(): + issues.append( + ValidationIssue( + level="error", + component=component, + message=f"missing expected repository marker: {marker}", + ) + ) + + if workspace.paths["api"].is_dir(): + if not (workspace.paths["api"] / "app").is_dir(): + issues.append( + ValidationIssue( + level="error", + component="api", + message="missing app/ package", + ) + ) + + if workspace.paths["content"].is_dir(): + if not workspace.bootstrap.content_config.exists(): + issues.append( + ValidationIssue( + level="warning", + component="content", + message=( + "bootstrap content config not found: " + f"{workspace.bootstrap.content_config}" + ), + ) + ) + if not workspace.bootstrap.modules_root.exists(): + issues.append( + ValidationIssue( + level="error", + component="content", + message=( + "bootstrap modules root not found: " + f"{workspace.bootstrap.modules_root}" + ), + ) + ) + + if not workspace.infra.compose_file.exists(): + issues.append( + ValidationIssue( + level="warning", + component="infra", + message=( + "local compose file not found: " + f"{workspace.infra.compose_file}. " + "infra-* commands will remain unavailable until it exists." + ), + ) + ) + + return issues + + +def has_errors(issues: list[ValidationIssue]) -> bool: + return any(issue.level == "error" for issue in issues) diff --git a/acupedia_ops/local/workspace.py b/acupedia_ops/local/workspace.py new file mode 100644 index 0000000..365fda9 --- /dev/null +++ b/acupedia_ops/local/workspace.py @@ -0,0 +1,237 @@ +from __future__ import annotations + +import os +from dataclasses import dataclass +from pathlib import Path + +import yaml + +from acupedia_ops.common.env import load_env_file +from acupedia_ops.common.paths import repo_root +from acupedia_ops.common.workspace_paths import ( + resolve_workspace_path, + workspace_base_path, +) + + +PATH_VARIABLES: dict[str, str] = { + "api": "ACUPEDIA_API_PATH", + "mobile": "ACUPEDIA_MOBILE_PATH", + "web": "ACUPEDIA_WEB_PORTAL_PATH", + "admin": "ACUPEDIA_ADMIN_PORTAL_PATH", + "content": "ACUPEDIA_CONTENT_PATH", + "ops": "ACUPEDIA_OPS_PATH", +} + + +@dataclass(frozen=True) +class ComponentConfig: + name: str + path_env: str + required_markers: tuple[str, ...] + setup_command: tuple[str, ...] + run_command: tuple[str, ...] + + +@dataclass(frozen=True) +class LocalInfraConfig: + compose_file: Path + project_name: str + + +@dataclass(frozen=True) +class BootstrapDefaults: + default_target: str + content_config: Path + modules_root: Path + media_manifest: Path | None + media_root: Path | None + commerce_plans: Path | None + + +@dataclass(frozen=True) +class LocalWorkspace: + base_path: Path + root: Path + components: dict[str, ComponentConfig] + paths: dict[str, Path] + infra: LocalInfraConfig + bootstrap: BootstrapDefaults + database_reset_command: tuple[str, ...] + + def path(self, component: str) -> Path: + try: + return self.paths[component] + except KeyError as exc: + raise KeyError(f"Unknown workspace component: {component}") from exc + + +def _as_command(value: object, *, field: str) -> tuple[str, ...]: + if value is None: + return () + if not isinstance(value, list) or not all(isinstance(v, str) for v in value): + raise ValueError(f"{field} must be a YAML list of strings") + return tuple(value) + + +def _as_markers(value: object, *, field: str) -> tuple[str, ...]: + if value is None: + return () + if not isinstance(value, list) or not all(isinstance(v, str) for v in value): + raise ValueError(f"{field} must be a YAML list of strings") + return tuple(value) + + +def _resolve_relative(base: Path, raw: str | None) -> Path | None: + """Resolve config-relative content paths against the supplied repo root.""" + if raw is None or not str(raw).strip(): + return None + + path = Path(str(raw)).expanduser() + if path.is_absolute(): + return path.resolve() + + return (base / path).resolve() + + +def load_local_workspace( + *, + env_file: Path | None = None, + config_file: Path | None = None, +) -> LocalWorkspace: + ops_checkout = repo_root() + load_env_file(env_file or (ops_checkout / ".env"), override=False) + + base = workspace_base_path(required=True) + assert base is not None + + paths: dict[str, Path] = {} + missing_vars: list[str] = [] + + for component, env_name in PATH_VARIABLES.items(): + value = os.environ.get(env_name, "").strip() + if not value: + missing_vars.append(env_name) + continue + paths[component] = resolve_workspace_path(value, base_path=base) + + if missing_vars: + raise RuntimeError( + "Missing local workspace path variable(s): " + ", ".join(missing_vars) + ) + + # config/local.yaml belongs to the ops repository. Prefer the resolved + # ACUPEDIA_OPS_PATH rather than whichever checkout happened to launch us. + config_path = config_file or (paths["ops"] / "config" / "local.yaml") + if not config_path.exists(): + raise FileNotFoundError(f"Local configuration not found: {config_path}") + + raw = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {} + if not isinstance(raw, dict): + raise ValueError("config/local.yaml root must be a mapping") + + component_raw = raw.get("components", {}) + if not isinstance(component_raw, dict): + raise ValueError("local.components must be a mapping") + + components: dict[str, ComponentConfig] = {} + for name, path_env in PATH_VARIABLES.items(): + if name in {"content", "ops"}: + continue + + item = component_raw.get(name, {}) + if not isinstance(item, dict): + raise ValueError(f"components.{name} must be a mapping") + + components[name] = ComponentConfig( + name=name, + path_env=path_env, + required_markers=_as_markers( + item.get("required_markers"), + field=f"components.{name}.required_markers", + ), + setup_command=_as_command( + item.get("setup_command"), + field=f"components.{name}.setup_command", + ), + run_command=_as_command( + item.get("run_command"), + field=f"components.{name}.run_command", + ), + ) + + infra_raw = raw.get("infrastructure", {}) + if not isinstance(infra_raw, dict): + raise ValueError("infrastructure must be a mapping") + + compose_override = os.environ.get("ACUPEDIA_LOCAL_COMPOSE_FILE", "").strip() + if compose_override: + # Environment path follows workspace-base semantics. + compose_file = resolve_workspace_path( + compose_override, + base_path=base, + ) + else: + # Config path remains relative to the ops repository. + compose_file = _resolve_relative( + paths["ops"], + str(infra_raw.get("compose_file", "docker-compose.local.yml")), + ) + + assert compose_file is not None + + infra = LocalInfraConfig( + compose_file=compose_file, + project_name=str(infra_raw.get("project_name", "acupedia-local")), + ) + + bootstrap_raw = raw.get("bootstrap", {}) + if not isinstance(bootstrap_raw, dict): + raise ValueError("bootstrap must be a mapping") + + content_root = paths["content"] + content_config = _resolve_relative( + content_root, + str(bootstrap_raw.get("content_config", "config.json")), + ) + modules_root = _resolve_relative( + content_root, + str(bootstrap_raw.get("modules_root", ".")), + ) + assert content_config is not None + assert modules_root is not None + + bootstrap = BootstrapDefaults( + default_target=str(bootstrap_raw.get("default_target", "content")), + content_config=content_config, + modules_root=modules_root, + media_manifest=_resolve_relative( + content_root, + bootstrap_raw.get("media_manifest"), + ), + media_root=_resolve_relative( + content_root, + bootstrap_raw.get("media_root"), + ), + commerce_plans=_resolve_relative( + content_root, + bootstrap_raw.get("commerce_plans"), + ), + ) + + database_raw = raw.get("database", {}) + if not isinstance(database_raw, dict): + raise ValueError("database must be a mapping") + + return LocalWorkspace( + base_path=base, + root=paths["ops"], + components=components, + paths=paths, + infra=infra, + bootstrap=bootstrap, + database_reset_command=_as_command( + database_raw.get("reset_command"), + field="database.reset_command", + ), + ) diff --git a/ansible/ansible.cfg b/ansible/ansible.cfg new file mode 100644 index 0000000..adf9073 --- /dev/null +++ b/ansible/ansible.cfg @@ -0,0 +1,4 @@ +[defaults] +host_key_checking = True +retry_files_enabled = False +interpreter_python = auto_silent diff --git a/ansible/inventories/dev/hosts.yml b/ansible/inventories/dev/hosts.yml new file mode 100644 index 0000000..f4c353e --- /dev/null +++ b/ansible/inventories/dev/hosts.yml @@ -0,0 +1,5 @@ +--- +all: + children: + backend: + hosts: {} diff --git a/ansible/inventories/gitea-runners.example.yml b/ansible/inventories/gitea-runners.example.yml new file mode 100644 index 0000000..f5bca20 --- /dev/null +++ b/ansible/inventories/gitea-runners.example.yml @@ -0,0 +1,22 @@ +all: + children: + gitea_runners: + hosts: + ci-runner-01: + ansible_host: 10.10.0.21 + gitea_runner_name: ci-runner-01 + gitea_runner_labels: + - "ubuntu-latest:docker://node:20-bookworm" + - "python:docker://python:3.13-bookworm" + + deploy-runner-01: + ansible_host: 10.10.0.22 + gitea_runner_name: deploy-runner-01 + gitea_runner_labels: + - "deployment:host" + - "ansible:host" + gitea_runner_docker_enabled: false + + vars: + ansible_user: ops + gitea_runner_instance_url: "https://gitea.example.com" diff --git a/ansible/inventories/prod/hosts.yml b/ansible/inventories/prod/hosts.yml new file mode 100644 index 0000000..f4c353e --- /dev/null +++ b/ansible/inventories/prod/hosts.yml @@ -0,0 +1,5 @@ +--- +all: + children: + backend: + hosts: {} diff --git a/ansible/inventories/staging/hosts.yml b/ansible/inventories/staging/hosts.yml new file mode 100644 index 0000000..f4c353e --- /dev/null +++ b/ansible/inventories/staging/hosts.yml @@ -0,0 +1,5 @@ +--- +all: + children: + backend: + hosts: {} diff --git a/ansible/playbooks/backend.yml b/ansible/playbooks/backend.yml new file mode 100644 index 0000000..d4ca7d4 --- /dev/null +++ b/ansible/playbooks/backend.yml @@ -0,0 +1,7 @@ +--- +- name: Deploy AccuPedia backend + hosts: backend + gather_facts: true + tasks: + - ansible.builtin.debug: + msg: "Backend deployment steps must be defined for the target environment." diff --git a/ansible/playbooks/database.yml b/ansible/playbooks/database.yml new file mode 100644 index 0000000..384353d --- /dev/null +++ b/ansible/playbooks/database.yml @@ -0,0 +1,7 @@ +--- +- name: Deploy AccuPedia database changes + hosts: backend + gather_facts: true + tasks: + - ansible.builtin.debug: + msg: "Database migration command must be defined for the target environment." diff --git a/ansible/playbooks/gitea-runner-remove.yml b/ansible/playbooks/gitea-runner-remove.yml new file mode 100644 index 0000000..9aaece2 --- /dev/null +++ b/ansible/playbooks/gitea-runner-remove.yml @@ -0,0 +1,9 @@ +--- +- name: Remove Gitea Actions runners + hosts: gitea_runners + become: true + tasks: + - name: Include Gitea runner removal tasks + ansible.builtin.include_role: + name: gitea_runner + tasks_from: remove.yml diff --git a/ansible/playbooks/gitea-runner.yml b/ansible/playbooks/gitea-runner.yml new file mode 100644 index 0000000..c4d60e5 --- /dev/null +++ b/ansible/playbooks/gitea-runner.yml @@ -0,0 +1,6 @@ +--- +- name: Provision Gitea Actions runners + hosts: gitea_runners + become: true + roles: + - role: gitea_runner diff --git a/ansible/playbooks/infra.yml b/ansible/playbooks/infra.yml new file mode 100644 index 0000000..92b0322 --- /dev/null +++ b/ansible/playbooks/infra.yml @@ -0,0 +1,7 @@ +--- +- name: Provision AccuPedia infrastructure + hosts: all + gather_facts: true + tasks: + - ansible.builtin.debug: + msg: "Infrastructure tasks must be explicitly defined before use." diff --git a/ansible/roles/.gitkeep b/ansible/roles/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/ansible/roles/gitea_runner/defaults/main.yml b/ansible/roles/gitea_runner/defaults/main.yml new file mode 100644 index 0000000..ddab5c7 --- /dev/null +++ b/ansible/roles/gitea_runner/defaults/main.yml @@ -0,0 +1,35 @@ +--- +gitea_runner_version: "0.2.11" +gitea_runner_arch: "amd64" +gitea_runner_os: "linux" + +gitea_runner_user: "gitea-runner" +gitea_runner_group: "gitea-runner" +gitea_runner_home: "/var/lib/gitea-runner" +gitea_runner_work_dir: "/var/lib/gitea-runner/work" +gitea_runner_config_dir: "/etc/gitea-runner" +gitea_runner_config_file: "/etc/gitea-runner/config.yaml" +gitea_runner_binary: "/usr/local/bin/act_runner" + +gitea_runner_instance_url: "" +gitea_runner_registration_token: "" +gitea_runner_name: "{{ inventory_hostname }}" +gitea_runner_labels: + - "ubuntu-latest:docker://node:20-bookworm" +gitea_runner_scope: "instance" + +gitea_runner_capacity: 1 +gitea_runner_fetch_interval: "2s" +gitea_runner_fetch_timeout: "5s" +gitea_runner_insecure: false +gitea_runner_container_network: "bridge" +gitea_runner_docker_enabled: true +gitea_runner_docker_socket: "/var/run/docker.sock" +gitea_runner_docker_privileged: false + +gitea_runner_service_name: "gitea-act-runner" +gitea_runner_service_enabled: true +gitea_runner_service_state: "started" + +gitea_runner_download_url: "https://dl.gitea.com/act_runner/{{ gitea_runner_version }}/act_runner-{{ gitea_runner_version }}-{{ gitea_runner_os }}-{{ gitea_runner_arch }}" +gitea_runner_force_reregister: false diff --git a/ansible/roles/gitea_runner/handlers/main.yml b/ansible/roles/gitea_runner/handlers/main.yml new file mode 100644 index 0000000..7d5a861 --- /dev/null +++ b/ansible/roles/gitea_runner/handlers/main.yml @@ -0,0 +1,7 @@ +--- +- name: Restart gitea runner + ansible.builtin.systemd: + name: "{{ gitea_runner_service_name }}" + state: restarted + daemon_reload: true + when: gitea_runner_service_enabled diff --git a/ansible/roles/gitea_runner/tasks/main.yml b/ansible/roles/gitea_runner/tasks/main.yml new file mode 100644 index 0000000..17ac6fd --- /dev/null +++ b/ansible/roles/gitea_runner/tasks/main.yml @@ -0,0 +1,132 @@ +--- +- name: Validate required runner settings + ansible.builtin.assert: + that: + - gitea_runner_instance_url | length > 0 + - gitea_runner_registration_token | length > 0 + - gitea_runner_name | length > 0 + - gitea_runner_labels | length > 0 + fail_msg: "Gitea runner instance URL, registration token, name and labels are required." + +- name: Install base packages + ansible.builtin.package: + name: + - ca-certificates + - curl + state: present + +- name: Ensure Docker is installed + ansible.builtin.package: + name: docker.io + state: present + when: gitea_runner_docker_enabled + +- name: Ensure Docker service is enabled and running + ansible.builtin.systemd: + name: docker + enabled: true + state: started + when: gitea_runner_docker_enabled + +- name: Create runner group + ansible.builtin.group: + name: "{{ gitea_runner_group }}" + system: true + state: present + +- name: Create runner user + ansible.builtin.user: + name: "{{ gitea_runner_user }}" + group: "{{ gitea_runner_group }}" + home: "{{ gitea_runner_home }}" + create_home: true + shell: /usr/sbin/nologin + system: true + +- name: Add runner user to Docker group + ansible.builtin.user: + name: "{{ gitea_runner_user }}" + groups: docker + append: true + when: gitea_runner_docker_enabled + +- name: Create runner directories + ansible.builtin.file: + path: "{{ item }}" + state: directory + owner: "{{ gitea_runner_user }}" + group: "{{ gitea_runner_group }}" + mode: "0750" + loop: + - "{{ gitea_runner_home }}" + - "{{ gitea_runner_work_dir }}" + - "{{ gitea_runner_home }}/cache" + - "{{ gitea_runner_config_dir }}" + +- name: Download act_runner + ansible.builtin.get_url: + url: "{{ gitea_runner_download_url }}" + dest: "{{ gitea_runner_binary }}" + mode: "0755" + owner: root + group: root + notify: Restart gitea runner + +- name: Render runner configuration + ansible.builtin.template: + src: config.yaml.j2 + dest: "{{ gitea_runner_config_file }}" + owner: root + group: "{{ gitea_runner_group }}" + mode: "0640" + notify: Restart gitea runner + +- name: Remove runner registration when force re-registering + ansible.builtin.file: + path: "{{ gitea_runner_home }}/.runner" + state: absent + when: gitea_runner_force_reregister + notify: Restart gitea runner + +- name: Check current runner registration + ansible.builtin.stat: + path: "{{ gitea_runner_home }}/.runner" + register: gitea_runner_registration + +- name: Register runner with Gitea + ansible.builtin.command: + argv: + - "{{ gitea_runner_binary }}" + - register + - "--no-interactive" + - "--instance" + - "{{ gitea_runner_instance_url }}" + - "--token" + - "{{ gitea_runner_registration_token }}" + - "--name" + - "{{ gitea_runner_name }}" + - "--labels" + - "{{ gitea_runner_labels | join(',') }}" + args: + chdir: "{{ gitea_runner_home }}" + creates: "{{ gitea_runner_home }}/.runner" + become_user: "{{ gitea_runner_user }}" + no_log: true + when: not gitea_runner_registration.stat.exists + notify: Restart gitea runner + +- name: Install systemd service + ansible.builtin.template: + src: gitea-act-runner.service.j2 + dest: "/etc/systemd/system/{{ gitea_runner_service_name }}.service" + owner: root + group: root + mode: "0644" + notify: Restart gitea runner + +- name: Ensure runner service state + ansible.builtin.systemd: + name: "{{ gitea_runner_service_name }}" + enabled: "{{ gitea_runner_service_enabled }}" + state: "{{ gitea_runner_service_state }}" + daemon_reload: true diff --git a/ansible/roles/gitea_runner/tasks/remove.yml b/ansible/roles/gitea_runner/tasks/remove.yml new file mode 100644 index 0000000..b6f9fc1 --- /dev/null +++ b/ansible/roles/gitea_runner/tasks/remove.yml @@ -0,0 +1,33 @@ +--- +- name: Stop and disable runner service + ansible.builtin.systemd: + name: "{{ gitea_runner_service_name }}" + enabled: false + state: stopped + daemon_reload: true + failed_when: false + +- name: Remove systemd service + ansible.builtin.file: + path: "/etc/systemd/system/{{ gitea_runner_service_name }}.service" + state: absent + +- name: Remove act_runner binary + ansible.builtin.file: + path: "{{ gitea_runner_binary }}" + state: absent + +- name: Remove runner configuration + ansible.builtin.file: + path: "{{ gitea_runner_config_dir }}" + state: absent + +- name: Remove runner home + ansible.builtin.file: + path: "{{ gitea_runner_home }}" + state: absent + when: gitea_runner_remove_data | default(false) | bool + +- name: Reload systemd + ansible.builtin.systemd: + daemon_reload: true diff --git a/ansible/roles/gitea_runner/templates/config.yaml.j2 b/ansible/roles/gitea_runner/templates/config.yaml.j2 new file mode 100644 index 0000000..c095d7b --- /dev/null +++ b/ansible/roles/gitea_runner/templates/config.yaml.j2 @@ -0,0 +1,31 @@ +log: + level: info + +runner: + file: "{{ gitea_runner_home }}/.runner" + capacity: {{ gitea_runner_capacity }} + envs: {} + timeout: 3h + shutdown_timeout: 0s + insecure: {{ gitea_runner_insecure | lower }} + fetch_timeout: {{ gitea_runner_fetch_timeout }} + fetch_interval: {{ gitea_runner_fetch_interval }} + labels: +{% for label in gitea_runner_labels %} + - "{{ label }}" +{% endfor %} + +cache: + enabled: true + dir: "{{ gitea_runner_home }}/cache" + +container: + network: "{{ gitea_runner_container_network }}" + privileged: {{ gitea_runner_docker_privileged | lower }} + options: + workdir_parent: + valid_volumes: [] + docker_host: "unix://{{ gitea_runner_docker_socket }}" + +host: + workdir_parent: "{{ gitea_runner_work_dir }}" diff --git a/ansible/roles/gitea_runner/templates/gitea-act-runner.service.j2 b/ansible/roles/gitea_runner/templates/gitea-act-runner.service.j2 new file mode 100644 index 0000000..772961a --- /dev/null +++ b/ansible/roles/gitea_runner/templates/gitea-act-runner.service.j2 @@ -0,0 +1,21 @@ +[Unit] +Description=Gitea Actions act_runner +After=network-online.target docker.service +Wants=network-online.target +{% if gitea_runner_docker_enabled %} +Requires=docker.service +{% endif %} + +[Service] +Type=simple +User={{ gitea_runner_user }} +Group={{ gitea_runner_group }} +WorkingDirectory={{ gitea_runner_home }} +Environment=HOME={{ gitea_runner_home }} +ExecStart={{ gitea_runner_binary }} daemon --config {{ gitea_runner_config_file }} +Restart=always +RestartSec=5 +NoNewPrivileges=true + +[Install] +WantedBy=multi-user.target diff --git a/config/dev.yaml b/config/dev.yaml new file mode 100644 index 0000000..dd07f8e --- /dev/null +++ b/config/dev.yaml @@ -0,0 +1,6 @@ +environment: dev +backend: + application_name: accupedia-api +database: + run_migrations: true +infra: {} diff --git a/config/local.yaml b/config/local.yaml new file mode 100644 index 0000000..5e41833 --- /dev/null +++ b/config/local.yaml @@ -0,0 +1,84 @@ +# Local development orchestration. +# +# Repository locations are read from .env; this file describes how each +# repository is operated locally. + +components: + api: + required_markers: + - pyproject.toml + - app + setup_command: + - uv + - sync + run_command: + - uv + - run + - uvicorn + - app.main:app + - --reload + - --host + - 127.0.0.1 + - --port + - "8000" + + mobile: + required_markers: + - package.json + setup_command: + - npm + - install + run_command: + - npx + - expo + - start + + web: + required_markers: + - package.json + setup_command: + - npm + - install + run_command: + - npm + - run + - dev + + admin: + required_markers: + - package.json + setup_command: + - npm + - install + run_command: + - npm + - run + - dev + +infrastructure: + # This can be overridden with ACUPEDIA_LOCAL_COMPOSE_FILE. + compose_file: docker-compose.local.yml + project_name: acupedia-local + +bootstrap: + # "content" is intentionally the safe/local default. "all" additionally + # requires a configured media manifest and storage environment. + default_target: content + + # These paths are relative to ACUPEDIA_CONTENT_PATH unless absolute. + content_config: config.json + modules_root: . + + # Configure these when local media seeding is required. + media_manifest: + media_root: + + # Leave empty to let acupedia-api use its bundled plans.json. + commerce_plans: + +database: + # Empty means use: + # -m app.cli.reset --scope all + # + # You may provide an explicit command if the API reset interface changes. + reset_command: [] diff --git a/config/prod.yaml b/config/prod.yaml new file mode 100644 index 0000000..0beb569 --- /dev/null +++ b/config/prod.yaml @@ -0,0 +1,6 @@ +environment: prod +backend: + application_name: accupedia-api +database: + run_migrations: true +infra: {} diff --git a/config/staging.yaml b/config/staging.yaml new file mode 100644 index 0000000..f1d266a --- /dev/null +++ b/config/staging.yaml @@ -0,0 +1,6 @@ +environment: staging +backend: + application_name: accupedia-api +database: + run_migrations: true +infra: {} diff --git a/docker-compose.local.example.yml b/docker-compose.local.example.yml new file mode 100644 index 0000000..6d5f05b --- /dev/null +++ b/docker-compose.local.example.yml @@ -0,0 +1,49 @@ +# Example only. Copy to docker-compose.local.yml and align image versions, +# ports and credentials with your acupedia-api local configuration. +# +# acupedia-ops deliberately does not hard-code infrastructure image versions +# that belong to your environment baseline. + +services: + postgres: + image: ${ACUPEDIA_POSTGRES_IMAGE:?Set ACUPEDIA_POSTGRES_IMAGE} + restart: unless-stopped + environment: + POSTGRES_DB: ${POSTGRES_DB:-acupedia} + POSTGRES_USER: ${POSTGRES_USER:-acupedia} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD} + ports: + - "${POSTGRES_PORT:-5432}:5432" + volumes: + - acupedia-postgres-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-acupedia} -d ${POSTGRES_DB:-acupedia}"] + interval: 5s + timeout: 5s + retries: 20 + + redis: + image: ${ACUPEDIA_REDIS_IMAGE:?Set ACUPEDIA_REDIS_IMAGE} + restart: unless-stopped + ports: + - "${REDIS_PORT:-6379}:6379" + volumes: + - acupedia-redis-data:/data + + minio: + image: ${ACUPEDIA_MINIO_IMAGE:?Set ACUPEDIA_MINIO_IMAGE} + restart: unless-stopped + command: server /data --console-address ":9001" + environment: + MINIO_ROOT_USER: ${MINIO_ACCESS_KEY:?Set MINIO_ACCESS_KEY} + MINIO_ROOT_PASSWORD: ${MINIO_SECRET_KEY:?Set MINIO_SECRET_KEY} + ports: + - "${MINIO_PORT:-9000}:9000" + - "${MINIO_CONSOLE_PORT:-9001}:9001" + volumes: + - acupedia-minio-data:/data + +volumes: + acupedia-postgres-data: + acupedia-redis-data: + acupedia-minio-data: diff --git a/docs/gitea-runner-lifecycle.md b/docs/gitea-runner-lifecycle.md new file mode 100644 index 0000000..df7244c --- /dev/null +++ b/docs/gitea-runner-lifecycle.md @@ -0,0 +1,72 @@ +# Gitea Actions runner lifecycle + +`acupedia-ops` owns provisioning and lifecycle management of Gitea Actions runners. + +Application repositories own only their `.gitea/workflows/*.yml` definitions. + +## Inventory + +Copy: + +```bash +cp ansible/inventories/gitea-runners.example.yml ansible/inventories/gitea-runners.yml +``` + +Edit the host addresses, SSH user, Gitea URL and runner labels. + +Do not store the registration token in Git. + +## Provision + +Using an environment variable: + +```bash +export GITEA_RUNNER_REGISTRATION_TOKEN='...' + +acupedia-ops runner provision --inventory ansible/inventories/gitea-runners.yml +``` + +Provision only one runner: + +```bash +acupedia-ops runner provision --inventory ansible/inventories/gitea-runners.yml --limit ci-runner-01 +``` + +Force re-registration: + +```bash +acupedia-ops runner provision --inventory ansible/inventories/gitea-runners.yml --limit ci-runner-01 --force-reregister +``` + +## Remove + +```bash +acupedia-ops runner remove --inventory ansible/inventories/gitea-runners.yml --limit ci-runner-01 +``` + +Remove registration/config plus runner data: + +```bash +acupedia-ops runner remove --inventory ansible/inventories/gitea-runners.yml --limit ci-runner-01 --remove-data +``` + +## Recommended runner classes + +CI runner: + +```yaml +gitea_runner_labels: + - "ubuntu-latest:docker://node:20-bookworm" + - "python:docker://python:3.13-bookworm" +``` + +Deployment runner: + +```yaml +gitea_runner_labels: + - "deployment:host" + - "ansible:host" +gitea_runner_docker_enabled: false +``` + +Do not give normal CI runners production credentials. diff --git a/docs/local-development.md b/docs/local-development.md new file mode 100644 index 0000000..e4e5e4c --- /dev/null +++ b/docs/local-development.md @@ -0,0 +1,196 @@ +# Local development + +`acupedia-ops local ...` coordinates the local AccuPedia workspace. It does not +replace the native development tools used by each repository. + +## Workspace model + +Recommended layout: + +```text +/home/amit/Work/Project/acupedia/ +├── acupedia-api/ +├── acupedia-mobile-ui/ +├── acupedia-web-portal/ +├── acupedia-admin-portal/ +├── acupedia-content/ +└── acupedia-ops/ +``` + +Copy `.env.example` to `.env`: + +```dotenv +ACUPEDIA_WORKSPACE_BASE_PATH=/home/amit/Work/Project/acupedia + +ACUPEDIA_API_PATH=acupedia-api +ACUPEDIA_MOBILE_PATH=acupedia-mobile-ui +ACUPEDIA_WEB_PORTAL_PATH=acupedia-web-portal +ACUPEDIA_ADMIN_PORTAL_PATH=acupedia-admin-portal +ACUPEDIA_CONTENT_PATH=acupedia-content +ACUPEDIA_OPS_PATH=acupedia-ops + +ACUPEDIA_LOCAL_COMPOSE_FILE=acupedia-ops/docker-compose.local.yml +ACUPEDIA_API_BOOTSTRAP_COMMAND=acupedia-api/.venv/bin/acupedia-bootstrap +ACUPEDIA_API_PYTHON=acupedia-api/.venv/bin/python +``` + +`ACUPEDIA_WORKSPACE_BASE_PATH` is the canonical local workspace root. + +All relative `ACUPEDIA_*_PATH` values are resolved against that base path, +never against the process current working directory. + +For example: + +```text +ACUPEDIA_WORKSPACE_BASE_PATH=/home/amit/Work/Project/acupedia +ACUPEDIA_API_PATH=acupedia-api + +resolves to: + +/home/amit/Work/Project/acupedia/acupedia-api +``` + +Absolute component paths remain supported and are used as-is. + +The workspace base path must itself be absolute. This is intentional: local +operations should not change meaning based on the directory from which the CLI +was launched. + +## Local machine versus deployment environment + +The `.env` describes local workspace topology and local runtime secrets. + +It is not the dev/staging/prod deployment selector. + +```text +.env + -> where local repositories live + +config/local.yaml + -> how repositories are operated locally + +docker-compose.local.yml + -> local stateful dependencies + +--env dev|staging|prod + -> explicit remote environment selection + +Ansible inventories/config + -> remote environment hosts/settings +``` + +## Validate + +```bash +acupedia-ops local validate +``` + +This verifies repository locations and expected repository markers. + +## Setup + +Validation only: + +```bash +acupedia-ops local setup +``` + +Install dependencies using the commands in `config/local.yaml`: + +```bash +acupedia-ops local setup --install +``` + +One component: + +```bash +acupedia-ops local setup --component api --install +``` + +## Local infrastructure + +Copy the example Compose file and align versions/settings with the API local +environment: + +```bash +cp docker-compose.local.example.yml docker-compose.local.yml +``` + +Then: + +```bash +acupedia-ops local infra-up +acupedia-ops local infra-status +acupedia-ops local logs +acupedia-ops local infra-down +``` + +Delete volumes only when explicitly intended: + +```bash +acupedia-ops local infra-down --volumes +``` + +## Bootstrap + +The actual bootstrap remains owned by `acupedia-api`. + +Default local content bootstrap: + +```bash +acupedia-ops local bootstrap +``` + +Publish seeded content: + +```bash +acupedia-ops local bootstrap content --publish-content +``` + +Other targets: + +```bash +acupedia-ops local bootstrap auth +acupedia-ops local bootstrap commerce +acupedia-ops local bootstrap media +acupedia-ops local bootstrap validate +acupedia-ops local bootstrap all +``` + +Additional backend bootstrap CLI options can be forwarded after `--`. + +## Database reset + +Dry-run: + +```bash +acupedia-ops local reset-db +``` + +Execute: + +```bash +acupedia-ops local reset-db --execute +``` + +`ACUPEDIA_API_PYTHON`, when relative, is resolved against +`ACUPEDIA_WORKSPACE_BASE_PATH`. + +## Run application components + +```bash +acupedia-ops local run api +acupedia-ops local run mobile +acupedia-ops local run web +acupedia-ops local run admin +``` + +These are foreground processes. Run multiple components in separate terminals, +tmux, or an IDE rather than turning `acupedia-ops` into a process supervisor. + +## Workspace status + +```bash +acupedia-ops local status +acupedia-ops local status --json +``` diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..718f904 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,30 @@ +[build-system] +requires = ["setuptools>=75", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "acupedia-ops" +version = "0.2.0" +description = "Operational data-processing and deployment tooling for AccuPedia" +readme = "README.md" +requires-python = ">=3.11" +dependencies = [ + "numpy>=2.0,<3.0", + "opencv-python-headless>=4.10,<5.0", + "PyYAML>=6.0,<7.0", +] + +[project.optional-dependencies] +deployment = ["ansible-runner>=2.4,<3.0"] +dev = ["pytest>=8.0,<9.0"] + +[project.scripts] +acupedia-ops = "acupedia_ops.cli:main" + +[tool.setuptools.packages.find] +where = ["."] +include = ["acupedia_ops*"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +pythonpath = ["."] diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..5cb5a3f --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +numpy>=2.0,<3.0 +opencv-python-headless>=4.10,<5.0 +PyYAML>=6.0,<7.0 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/bootstrap/__init__.py b/tests/bootstrap/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/bootstrap/test_api_cli.py b/tests/bootstrap/test_api_cli.py new file mode 100644 index 0000000..dace307 --- /dev/null +++ b/tests/bootstrap/test_api_cli.py @@ -0,0 +1,22 @@ +from pathlib import Path + +import pytest + +from acupedia_ops.bootstrap.api_cli import resolve_api_root, run_api_bootstrap + + +def test_resolve_api_root(tmp_path: Path) -> None: + api = tmp_path / "api" + (api / "app").mkdir(parents=True) + (api / "pyproject.toml").write_text("", encoding="utf-8") + + assert resolve_api_root(api) == api.resolve() + + +def test_rejects_unknown_target(tmp_path: Path) -> None: + api = tmp_path / "api" + (api / "app").mkdir(parents=True) + (api / "pyproject.toml").write_text("", encoding="utf-8") + + with pytest.raises(ValueError): + run_api_bootstrap(target="unknown", api_root=api) diff --git a/tests/common/__init__.py b/tests/common/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/common/test_config.py b/tests/common/test_config.py new file mode 100644 index 0000000..e3409d4 --- /dev/null +++ b/tests/common/test_config.py @@ -0,0 +1,12 @@ +from pathlib import Path + +from acupedia_ops.common.config import load_config + + +def test_load_config(tmp_path: Path) -> None: + (tmp_path / "dev.yaml").write_text( + "backend:\n application_name: accupedia-api\n", + encoding="utf-8", + ) + config = load_config("dev", config_root=tmp_path) + assert config.values["backend"]["application_name"] == "accupedia-api" diff --git a/tests/common/test_workspace_paths.py b/tests/common/test_workspace_paths.py new file mode 100644 index 0000000..684e52e --- /dev/null +++ b/tests/common/test_workspace_paths.py @@ -0,0 +1,49 @@ +from pathlib import Path + +import pytest + +from acupedia_ops.common.workspace_paths import ( + resolve_command, + resolve_workspace_path, + workspace_base_path, +) + + +def test_workspace_base_must_be_absolute(monkeypatch) -> None: + monkeypatch.setenv("ACUPEDIA_WORKSPACE_BASE_PATH", "relative/workspace") + with pytest.raises(ValueError): + workspace_base_path() + + +def test_relative_path_uses_workspace_base(tmp_path: Path) -> None: + base = (tmp_path / "workspace").resolve() + base.mkdir() + + assert resolve_workspace_path( + "acupedia-api", + base_path=base, + ) == (base / "acupedia-api").resolve() + + +def test_absolute_path_is_preserved(tmp_path: Path) -> None: + absolute = (tmp_path / "api").resolve() + + assert resolve_workspace_path( + absolute, + base_path=tmp_path / "other", + ) == absolute + + +def test_command_executable_path_uses_workspace_base(tmp_path: Path) -> None: + base = (tmp_path / "workspace").resolve() + base.mkdir() + + command = resolve_command( + "acupedia-api/.venv/bin/acupedia-bootstrap --flag value", + base_path=base, + ) + + assert command[0] == str( + (base / "acupedia-api/.venv/bin/acupedia-bootstrap").resolve() + ) + assert command[1:] == ["--flag", "value"] diff --git a/tests/data/image/test_clean_image_borders.py b/tests/data/image/test_clean_image_borders.py new file mode 100644 index 0000000..06db625 --- /dev/null +++ b/tests/data/image/test_clean_image_borders.py @@ -0,0 +1,11 @@ +from pathlib import Path +import cv2 +import numpy as np +from acupedia_ops.data.image.clean_image_borders import clean_image + +def test_clean_image_preserves_dimensions(tmp_path: Path) -> None: + source=tmp_path/"source.png"; target=tmp_path/"target.png" + image=np.full((200,300,3),255,dtype=np.uint8); image[:,0:3]=190; image[0:3,:]=190; image[:,297:300]=190 + cv2.circle(image,(150,100),30,(0,0,0),3); assert cv2.imwrite(str(source),image) + assert clean_image(source,target) + cleaned=cv2.imread(str(target)); assert cleaned is not None; assert cleaned.shape==image.shape; assert int(cleaned[100,120].mean())<100 diff --git a/tests/deployment/__init__.py b/tests/deployment/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/deployment/test_gitea_runner.py b/tests/deployment/test_gitea_runner.py new file mode 100644 index 0000000..69b5682 --- /dev/null +++ b/tests/deployment/test_gitea_runner.py @@ -0,0 +1,8 @@ +from pathlib import Path + +from acupedia_ops.deployment import gitea_runner + + +def test_repo_root_contains_ansible(): + root = gitea_runner._repo_root() + assert (root / "ansible").exists() diff --git a/tests/local/__init__.py b/tests/local/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/local/test_bootstrap_args.py b/tests/local/test_bootstrap_args.py new file mode 100644 index 0000000..a4374bb --- /dev/null +++ b/tests/local/test_bootstrap_args.py @@ -0,0 +1,49 @@ +from pathlib import Path + +from acupedia_ops.local.bootstrap import build_local_bootstrap_args +from acupedia_ops.local.workspace import ( + BootstrapDefaults, + LocalInfraConfig, + LocalWorkspace, +) + + +def test_content_bootstrap_args(tmp_path: Path) -> None: + content = tmp_path / "content" + content.mkdir() + config = content / "config.json" + config.write_text("{}", encoding="utf-8") + + workspace = LocalWorkspace( + base_path=tmp_path, + root=tmp_path, + components={}, + paths={"api": tmp_path / "api"}, + infra=LocalInfraConfig( + compose_file=tmp_path / "compose.yml", + project_name="test", + ), + bootstrap=BootstrapDefaults( + default_target="content", + content_config=config, + modules_root=content, + media_manifest=None, + media_root=None, + commerce_plans=None, + ), + database_reset_command=(), + ) + + args = build_local_bootstrap_args( + workspace, + "content", + publish_content=True, + ) + + assert args == [ + "--config", + str(config), + "--modules-root", + str(content), + "--publish-content", + ] diff --git a/tests/local/test_env.py b/tests/local/test_env.py new file mode 100644 index 0000000..f3dc1da --- /dev/null +++ b/tests/local/test_env.py @@ -0,0 +1,16 @@ +from pathlib import Path + +from acupedia_ops.common.env import parse_env_file + + +def test_parse_env_file(tmp_path: Path) -> None: + path = tmp_path / ".env" + path.write_text( + "A=1\nexport B='two words'\n# comment\nC=\"three\"\n", + encoding="utf-8", + ) + assert parse_env_file(path) == { + "A": "1", + "B": "two words", + "C": "three", + } diff --git a/tests/local/test_workspace.py b/tests/local/test_workspace.py new file mode 100644 index 0000000..dd91aaa --- /dev/null +++ b/tests/local/test_workspace.py @@ -0,0 +1,101 @@ +from pathlib import Path + +import pytest + +from acupedia_ops.local.workspace import load_local_workspace + + +@pytest.fixture() +def workspace_environment(tmp_path: Path, monkeypatch): + base = tmp_path / "workspace" + base.mkdir() + + names = { + "ACUPEDIA_API_PATH": "api", + "ACUPEDIA_MOBILE_PATH": "mobile", + "ACUPEDIA_WEB_PORTAL_PATH": "web", + "ACUPEDIA_ADMIN_PORTAL_PATH": "admin", + "ACUPEDIA_CONTENT_PATH": "content", + "ACUPEDIA_OPS_PATH": "ops", + } + + monkeypatch.setenv("ACUPEDIA_WORKSPACE_BASE_PATH", str(base)) + + resolved = {} + for env_name, relative in names.items(): + path = base / relative + path.mkdir() + monkeypatch.setenv(env_name, relative) + resolved[env_name] = path + + (resolved["ACUPEDIA_API_PATH"] / "app").mkdir() + (resolved["ACUPEDIA_API_PATH"] / "pyproject.toml").write_text( + "", + encoding="utf-8", + ) + (resolved["ACUPEDIA_CONTENT_PATH"] / "config.json").write_text( + "{}", + encoding="utf-8", + ) + + config = tmp_path / "local.yaml" + config.write_text( + """ +components: + api: + required_markers: [pyproject.toml, app] + setup_command: [uv, sync] + run_command: [uv, run, uvicorn] + mobile: {} + web: {} + admin: {} +infrastructure: + compose_file: docker-compose.local.yml +bootstrap: + content_config: config.json + modules_root: . +database: + reset_command: [] +""".strip(), + encoding="utf-8", + ) + + return base, resolved, config + + +def test_workspace_loads_relative_paths_from_base( + workspace_environment, +) -> None: + base, resolved, config = workspace_environment + + workspace = load_local_workspace( + env_file=Path("/nonexistent"), + config_file=config, + ) + + assert workspace.base_path == base.resolve() + assert workspace.path("api") == resolved["ACUPEDIA_API_PATH"].resolve() + assert workspace.path("mobile") == resolved["ACUPEDIA_MOBILE_PATH"].resolve() + assert workspace.bootstrap.content_config == ( + resolved["ACUPEDIA_CONTENT_PATH"] / "config.json" + ).resolve() + + +def test_compose_env_override_resolves_from_workspace_base( + workspace_environment, + monkeypatch, +) -> None: + base, _, config = workspace_environment + monkeypatch.setenv( + "ACUPEDIA_LOCAL_COMPOSE_FILE", + "ops/docker-compose.local.yml", + ) + + workspace = load_local_workspace( + env_file=Path("/nonexistent"), + config_file=config, + ) + + assert workspace.infra.compose_file == ( + base / "ops" / "docker-compose.local.yml" + ).resolve()