diff --git a/Dockerfile b/Dockerfile index 3b0db98..257c5e0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,13 +4,18 @@ # dbt's manifest: the measures' definitions and the compiled SQL of their event # models. The API serves the measures from it and the indicator cycle creates -# the views. Compiling needs no data; the SQL is SQLite's, the image's default -# engine. +# the views. The manifest built here is SQLite's, the image's default engine; +# the same environments compile it again at start-up against MySQL/MariaDB, +# PostgreSQL or SQL Server when *_DATABASE_URL points there (docker-entrypoint.sh), +# because those adapters open a connection to compile. dbt-mysql needs an +# older dbt-core, so it gets an environment of its own. FROM python:3.12-slim AS manifest COPY --from=ghcr.io/astral-sh/uv:0.7.9 /uv /uvx /bin/ WORKDIR /app/Transformation COPY Transformation/ ./ -RUN uv sync && uv run --no-sync dbt compile --profiles-dir . --profile tea +RUN uv sync --group sqlite --group sqlserver --group postgres \ + && UV_PROJECT_ENVIRONMENT=.venv-mysql uv sync --only-group mysql \ + && uv run --no-sync dbt compile --profiles-dir . --profile cacu --target sqlite --no-introspect FROM python:3.12-slim @@ -46,10 +51,11 @@ ENV WEBAPI_REPORT_DIR=/data/reportes ENV INDICADORES_DIR=/data/indicadores ENV MLFLOW_DISABLE_AGENT_HINT=1 # Without it the measure routes (//indicadores, //fhir) aren't -# registered. On another engine, mount a manifest compiled with that dbt target -# and point this at it. -COPY --from=manifest /app/Transformation/target/manifest.json /app/Transformation/target/manifest.json +# registered. The entrypoint replaces it with one compiled against the +# deployment's engine when that engine isn't SQLite (webapi.dbt_manifest). +COPY --from=manifest /app/Transformation /app/Transformation ENV DBT_MANIFEST=/app/Transformation/target/manifest.json +ENV TRANSFORMATION_DIR=/app/Transformation RUN chmod +x /app/WebApi/docker-entrypoint.sh diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 46bdf4c..204fef9 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -16,14 +16,24 @@ for url in "$CACU_DATABASE_URL" "$CAMA_DATABASE_URL" "$TEA_DATABASE_URL" "$GOVER esac done +cd /app/WebApi + +# dbt's manifest for the deployment's engine: the image's is SQLite's; on +# another engine it's compiled now, against the configured databases, into +# /data (webapi.dbt_manifest prints the path to use, or nothing to keep the +# image's). +if compiled="$(uv run --no-sync python -m webapi.dbt_manifest)"; then + [ -n "$compiled" ] && export DBT_MANIFEST="$compiled" +else + echo "dbt manifest: compilation failed; the measure routes will stay unregistered" >&2 +fi + # The live indicator worker (webapi.recomputation) shares the image; the # API container runs the migrations, so the worker starts after it. if [ "$1" = "indicadores" ]; then - cd /app/WebApi exec uv run --no-sync python -m webapi.recomputation fi -cd /app/WebApi # --no-sync: the environment was synced at build time; syncing at startup # would try to reach the package index (and pull dev deps). for domain in cacu cama tea governance; do diff --git a/tests/test_dbt_manifest.py b/tests/test_dbt_manifest.py new file mode 100644 index 0000000..f0bdf1e --- /dev/null +++ b/tests/test_dbt_manifest.py @@ -0,0 +1,53 @@ +"""The dbt target and environment derived from the deployment's database URLs (`webapi.dbt_manifest`). + +No dbt runs here: only the mapping the entrypoint relies on to compile the manifest against the right engine. +No fixtures.""" + +import pytest + +from webapi.dbt_manifest import dbt_executable, environment, target_of + +URLS_MSSQL = { + "cacu": "mssql+pymssql://usuario:clave@servidor:1433/isss_cacu", + "cama": "mssql+pymssql://usuario:clave@servidor:1433/isss_cama", + "tea": "mssql+pymssql://usuario:clave@servidor:1433/isss_tea", +} + + +def test_sqlite_urls_keep_the_image_manifest(): + """SQLite URLs give the `sqlite` target, which the entrypoint treats as "keep the image's manifest". Fails if + `target_of` stops recognising SQLite or maps it elsewhere.""" + urls = {d: f"sqlite:////data/{d}.db" for d in ("cacu", "cama", "tea")} + assert target_of(urls) == "sqlite" + assert environment(urls, "sqlite")["TEA_DB_PATH"] == "/data/tea.db" + + +@pytest.mark.parametrize("scheme, target", [("mssql+pymssql", "sqlserver"), ("postgresql+psycopg2", "postgres"), + ("mysql+pymysql", "mysql"), ("mariadb+pymysql", "mysql")]) +def test_each_engine_maps_to_its_dbt_target(scheme, target): + """Every engine the platform runs on has a dbt target. Fails if a backend name is dropped from `TARGETS`.""" + urls = {d: f"{scheme}://u:p@h:1/{d}" for d in ("cacu", "cama", "tea")} + assert target_of(urls) == target + + +def test_mixed_engines_are_refused(): + """One manifest serves the three domains, so their databases must share an engine. Fails if `target_of` + silently picks one of several engines.""" + urls = {**URLS_MSSQL, "tea": "sqlite:////data/tea.db"} + with pytest.raises(ValueError, match="one engine"): + target_of(urls) + + +def test_environment_feeds_profiles_yml(): + """The server, port, credentials and each domain's database name reach dbt through the variables + `Transformation/profiles.yml` reads. Fails if a variable name changes on either side.""" + env = environment(URLS_MSSQL, "sqlserver") + assert env == {"CACU_DBT_DATABASE": "isss_cacu", "CAMA_DBT_DATABASE": "isss_cama", "TEA_DBT_DATABASE": "isss_tea", + "DBT_HOST": "servidor", "DBT_PORT": "1433", "DBT_USER": "usuario", "DBT_PASSWORD": "clave"} + + +def test_mysql_has_its_own_environment(tmp_path): + """dbt-mysql pins an older dbt-core, so the image keeps it in `.venv-mysql`. Fails if the executable lookup + stops distinguishing MySQL.""" + assert dbt_executable(tmp_path, "mysql") == tmp_path / ".venv-mysql" / "bin" / "dbt" + assert dbt_executable(tmp_path, "sqlserver") == tmp_path / ".venv" / "bin" / "dbt" diff --git a/webapi/dbt_manifest.py b/webapi/dbt_manifest.py new file mode 100644 index 0000000..41a2952 --- /dev/null +++ b/webapi/dbt_manifest.py @@ -0,0 +1,83 @@ +"""dbt's manifest for the deployment's engine. + +The measures are served from `manifest.json` (`DBT_MANIFEST`), whose compiled SQL is the dialect of the dbt target it +was compiled with. The image ships SQLite's; on another engine the entrypoint runs this module, which compiles the +project in `TRANSFORMATION_DIR` against the configured databases (the adapters for MySQL, PostgreSQL and SQL Server +open a connection to compile) and prints the path of the manifest to serve. On SQLite it prints nothing: the image's +manifest is the right one. + +The three domains must share one engine: one manifest covers every domain's models. +""" + +import os +import subprocess +import sys +from pathlib import Path + +from sqlalchemy.engine import make_url + +DOMAINS = ("cacu", "cama", "tea") +TARGETS = {"sqlite": "sqlite", "mssql": "sqlserver", "postgresql": "postgres", "mysql": "mysql", "mariadb": "mysql"} + + +def target_of(urls: dict[str, str]) -> str: + """The dbt target the domains' database URLs share. `ValueError` for an engine dbt has no target for, or when + the domains don't share one engine.""" + targets = {domain: TARGETS.get(make_url(url).get_backend_name()) for domain, url in urls.items()} + if unknown := [domain for domain, target in targets.items() if target is None]: + raise ValueError(f"no dbt target for the engine of {', '.join(unknown)}") + if len(set(targets.values())) != 1: + raise ValueError("the domains' databases must be on one engine: one manifest serves the three domains") + return next(iter(targets.values())) + + +def environment(urls: dict[str, str], target: str) -> dict[str, str]: + """What `Transformation/profiles.yml` reads: the server and credentials from CaCu's URL (one server for the three + domains), each domain's database name, and on SQLite each domain's file.""" + env: dict[str, str] = {} + for domain, url in urls.items(): + parsed = make_url(url) + if target == "sqlite": + env[f"{domain.upper()}_DB_PATH"] = parsed.database or f"{domain}.db" + else: + env[f"{domain.upper()}_DBT_DATABASE"] = parsed.database or domain + first = make_url(urls["cacu"]) + if target != "sqlite": + env["DBT_HOST"] = first.host or "localhost" + if first.port: + env["DBT_PORT"] = str(first.port) + env["DBT_USER"] = first.username or "" + env["DBT_PASSWORD"] = first.password or "" + return env + + +def dbt_executable(root: Path, target: str) -> Path: + """dbt-mysql runs on an older dbt-core, so it lives in its own environment next to the main one.""" + return root / (".venv-mysql" if target == "mysql" else ".venv") / "bin" / "dbt" + + +def compile_manifest(root: Path, target: str, env: dict[str, str], out_dir: Path) -> Path: + """Compiles every model with placeholders for the question's parameters (`--no-introspect`: the target's + tables needn't exist yet) and returns the manifest's path.""" + out_dir.mkdir(parents=True, exist_ok=True) + command = [str(dbt_executable(root, target)), "compile", "--project-dir", str(root), "--profiles-dir", str(root), + "--profile", "cacu", "--target", target, "--no-introspect", "--target-path", str(out_dir)] + subprocess.run(command, check=True, env={**os.environ, **env}, stdout=sys.stderr) + return out_dir / "manifest.json" + + +def main() -> int: + from persistance.settings import settings + + urls = {domain: getattr(settings, f"{domain}_database_url") for domain in DOMAINS} + target = target_of(urls) + if target == "sqlite": + return 0 + root = Path(os.environ.get("TRANSFORMATION_DIR") or Path(__file__).resolve().parents[2] / "Transformation") + out_dir = Path(os.environ.get("DBT_MANIFEST_DIR", "/data/dbt")) + print(compile_manifest(root, target, environment(urls, target), out_dir)) + return 0 + + +if __name__ == "__main__": + sys.exit(main())