Compare commits
81 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 55da6cd28b | |||
| 9b631928ad | |||
| c326f4901d | |||
| 37c456c5ef | |||
| edd3093d5d | |||
| 323240dd30 | |||
| 326502f90c | |||
| 2c5568f5d1 | |||
| 87a0893ee4 | |||
| 82f7a18a9f | |||
| b4db5f9b2c | |||
| 06f1cadc4b | |||
| b61a4863d1 | |||
| 6c1d098619 | |||
| 4063a9824b | |||
| f26d32a010 | |||
| b61843b639 | |||
| 80049112aa | |||
| ec5d945f71 | |||
| 54b1995681 | |||
| 52bcf34720 | |||
| d92d1697b8 | |||
| 983680ead3 | |||
| 3300ec3048 | |||
| 8a2ce3bbb4 | |||
| eda8dde354 | |||
| 08f240cde9 | |||
| 80b3d23b75 | |||
| b401f98f19 | |||
| 9e5aa20092 | |||
| 88b22b9491 | |||
| d7624c7e0f | |||
| c9b60b190b | |||
| 4ef38c18e2 | |||
| f830003abd | |||
| 3a18af9516 | |||
| 29186909cc | |||
| c7caf56f83 | |||
| 0a4deea370 | |||
| 25955b80e8 | |||
| 8b0b121aaa | |||
| 11c648ac36 | |||
| ae4638e4dd | |||
| 51bcdbdfe3 | |||
| 4212c4d0b5 | |||
| d59c20432e | |||
| d8d834f308 | |||
| f6e8b09dd0 | |||
| 2131ff60a5 | |||
| a4c3d6c1b0 | |||
| e3e774fca4 | |||
| 09691afc76 | |||
| 70c9506b97 | |||
| 7222cbdb49 | |||
| 7e25dde319 | |||
| 052fb23fab | |||
| b515746406 | |||
| 3438a3135b | |||
| 88bbc6155f | |||
| e434e085fe | |||
| e4967347f5 | |||
| 4793cf01f0 | |||
| 8fa2be8aab | |||
| de4485094f | |||
| 074fdb5305 | |||
| 135f23e898 | |||
| d3f7aeb537 | |||
| 1e878b8942 | |||
| dffd33a7bc | |||
| 9c89c9e10d | |||
| 7dbb4b75fc | |||
| 05980899a2 | |||
| cb9115c435 | |||
| 26cf994d1a | |||
| 806302ee5d | |||
| 0dd5c035bc | |||
| e2ed1e9dfb | |||
| 1c53276b55 | |||
| 326250ffb3 | |||
| cddf91185b | |||
| df921f13cd |
@@ -1,9 +1,2 @@
|
|||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
|
||||||
.venv/
|
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
.coverage
|
|
||||||
*.egg-info/
|
|
||||||
.env
|
|
||||||
uv.lock
|
|
||||||
*.db
|
|
||||||
|
|||||||
-24
@@ -1,24 +0,0 @@
|
|||||||
# Build context is the ISSSTELEON repo root (see root docker-compose.yml)
|
|
||||||
# so this Dockerfile can COPY its sibling Core/, Persistance/ and models/.
|
|
||||||
FROM python:3.12-slim
|
|
||||||
|
|
||||||
RUN pip install --no-cache-dir uv
|
|
||||||
|
|
||||||
WORKDIR /app
|
|
||||||
COPY Core/ Core/
|
|
||||||
COPY Persistance/ Persistance/
|
|
||||||
COPY models/ models/
|
|
||||||
COPY WebApi/ WebApi/
|
|
||||||
|
|
||||||
RUN cd Persistance && uv sync --no-dev
|
|
||||||
RUN cd WebApi && uv sync --no-dev
|
|
||||||
|
|
||||||
ENV CACU_DATABASE_URL=sqlite:////data/cacu.db
|
|
||||||
ENV CAMA_DATABASE_URL=sqlite:////data/cama.db
|
|
||||||
ENV TEA_DATABASE_URL=sqlite:////data/tea.db
|
|
||||||
ENV AUTH_DATABASE_URL=sqlite:////data/auth.db
|
|
||||||
|
|
||||||
RUN chmod +x /app/WebApi/docker-entrypoint.sh
|
|
||||||
|
|
||||||
EXPOSE 5000
|
|
||||||
ENTRYPOINT ["/app/WebApi/docker-entrypoint.sh"]
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
set -e
|
|
||||||
|
|
||||||
case "${AUTH_LITE_ENABLED-false}" in
|
|
||||||
true|false)
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
echo "AUTH_LITE_ENABLED must be exactly 'true' or 'false'" >&2
|
|
||||||
exit 1
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
case "${AUTH_LITE_SEED_DEMO_USERS-false}" in
|
|
||||||
true|false)
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
echo "AUTH_LITE_SEED_DEMO_USERS must be exactly 'true' or 'false'" >&2
|
|
||||||
exit 1
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
mkdir -p /data
|
|
||||||
|
|
||||||
cd /app/Persistance
|
|
||||||
uv run alembic -c persistance/cacu/alembic.ini upgrade head
|
|
||||||
uv run alembic -c persistance/cama/alembic.ini upgrade head
|
|
||||||
uv run alembic -c persistance/tea/alembic.ini upgrade head
|
|
||||||
|
|
||||||
if [ "${AUTH_LITE_ENABLED-false}" = "true" ]; then
|
|
||||||
uv run alembic -c persistance/auth/alembic.ini upgrade head
|
|
||||||
fi
|
|
||||||
|
|
||||||
cd /app/WebApi
|
|
||||||
if [ "${AUTH_LITE_ENABLED-false}" = "true" ] && [ "${AUTH_LITE_SEED_DEMO_USERS-false}" = "true" ]; then
|
|
||||||
uv run python -m webapi.auth_demo_seed --ensure
|
|
||||||
fi
|
|
||||||
exec uv run python main.py
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
from webapi import create_app
|
|
||||||
|
|
||||||
app = create_app()
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
app.run(host="0.0.0.0", port=5000)
|
|
||||||
+19
-18
@@ -1,26 +1,27 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "webapi"
|
name = "webapi"
|
||||||
version = "0.1.0"
|
version = "0.0.0"
|
||||||
description = "Flask REST API fronting Persistance (reads) and models (train/predict) for CaCu, CaMa and TEA."
|
description = "FastAPI: FHIR routes, control routes, the auth dependency."
|
||||||
requires-python = ">=3.11"
|
requires-python = ">=3.12"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"flask>=3.0",
|
"core",
|
||||||
"persistance",
|
"persistance",
|
||||||
"models",
|
"fastapi[standard]",
|
||||||
|
"dagster-graphql",
|
||||||
|
"authlib>=1.6",
|
||||||
|
"fastapi-users[sqlalchemy]>=15",
|
||||||
|
"aiosqlite>=0.20",
|
||||||
|
"asyncpg>=0.30",
|
||||||
|
"requests",
|
||||||
]
|
]
|
||||||
|
|
||||||
[tool.uv.sources]
|
|
||||||
persistance = { path = "../Persistance", editable = true }
|
|
||||||
models = { path = "../models", editable = true }
|
|
||||||
|
|
||||||
[build-system]
|
[build-system]
|
||||||
requires = ["hatchling"]
|
requires = ["uv_build>=0.12,<0.13"]
|
||||||
build-backend = "hatchling.build"
|
build-backend = "uv_build"
|
||||||
|
|
||||||
[tool.hatch.build.targets.wheel]
|
[tool.uv.build-backend]
|
||||||
packages = ["webapi"]
|
module-name = "webapi"
|
||||||
|
module-root = ""
|
||||||
[dependency-groups]
|
[tool.uv.sources]
|
||||||
dev = [
|
core = { workspace = true }
|
||||||
"pytest>=8.0.0",
|
persistance = { workspace = true }
|
||||||
]
|
|
||||||
|
|||||||
@@ -1,63 +0,0 @@
|
|||||||
import os
|
|
||||||
import tempfile
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
|
||||||
def client():
|
|
||||||
db_path = tempfile.NamedTemporaryFile(suffix=".db", delete=False).name
|
|
||||||
isolation = pytest.MonkeyPatch()
|
|
||||||
isolation.setenv("CACU_DATABASE_URL", f"sqlite:///{db_path}")
|
|
||||||
isolation.setenv("AUTH_LITE_ENABLED", "false")
|
|
||||||
|
|
||||||
from core.cacu.base import CaCuModel
|
|
||||||
from core.cacu.models import Paciente
|
|
||||||
from persistance.db import get_cacu_engine
|
|
||||||
from persistance.settings import settings
|
|
||||||
|
|
||||||
isolation.setattr(settings, "cacu_database_url", f"sqlite:///{db_path}")
|
|
||||||
get_cacu_engine.cache_clear()
|
|
||||||
engine = get_cacu_engine()
|
|
||||||
try:
|
|
||||||
CaCuModel.metadata.create_all(engine)
|
|
||||||
|
|
||||||
from sqlmodel import Session
|
|
||||||
|
|
||||||
with Session(engine) as session:
|
|
||||||
session.add(Paciente(pac_id_hospital="H-1", pac_sexo="Femenino"))
|
|
||||||
session.commit()
|
|
||||||
|
|
||||||
from webapi import create_app
|
|
||||||
|
|
||||||
app = create_app()
|
|
||||||
app.config.update(TESTING=True)
|
|
||||||
with app.test_client() as client:
|
|
||||||
yield client
|
|
||||||
finally:
|
|
||||||
engine.dispose()
|
|
||||||
get_cacu_engine.cache_clear()
|
|
||||||
os.unlink(db_path)
|
|
||||||
isolation.undo()
|
|
||||||
|
|
||||||
|
|
||||||
def test_health(client):
|
|
||||||
response = client.get("/health")
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert response.get_json() == {"status": "ok"}
|
|
||||||
|
|
||||||
|
|
||||||
def test_get_paciente(client):
|
|
||||||
response = client.get("/cacu/pacientes/1")
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert response.get_json()["pac_id_hospital"] == "H-1"
|
|
||||||
|
|
||||||
|
|
||||||
def test_get_paciente_not_found(client):
|
|
||||||
response = client.get("/cacu/pacientes/999")
|
|
||||||
assert response.status_code == 404
|
|
||||||
|
|
||||||
|
|
||||||
def test_predict_not_implemented(client):
|
|
||||||
response = client.post("/cacu/predict")
|
|
||||||
assert response.status_code == 501
|
|
||||||
@@ -1,500 +0,0 @@
|
|||||||
import json
|
|
||||||
from contextlib import closing
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from alembic import command
|
|
||||||
from alembic.config import Config
|
|
||||||
from sqlalchemy import text
|
|
||||||
from werkzeug.security import check_password_hash, generate_password_hash
|
|
||||||
|
|
||||||
from persistance.db import get_auth_engine
|
|
||||||
from persistance.settings import settings
|
|
||||||
from webapi import create_app, parse_auth_lite_enabled
|
|
||||||
from webapi.auth_bootstrap import bootstrap, main
|
|
||||||
from webapi.auth_token import TOKEN_MAX_AGE, issue_token, serializer
|
|
||||||
|
|
||||||
ALEMBIC_INI = Path(__file__).resolve().parents[2] / "Persistance/persistance/auth/alembic.ini"
|
|
||||||
TEST_SECRET = "fictitious-test-secret-only"
|
|
||||||
TEST_PASSWORD = "fictitious-password-only"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def storage(tmp_path, monkeypatch):
|
|
||||||
path = tmp_path / "auth.sqlite"
|
|
||||||
monkeypatch.setattr(settings, "auth_database_url", f"sqlite:///{path.as_posix()}")
|
|
||||||
monkeypatch.setenv("AUTH_LITE_ENABLED", "true")
|
|
||||||
monkeypatch.setenv("AUTH_LITE_SECRET_KEY", TEST_SECRET)
|
|
||||||
get_auth_engine.cache_clear()
|
|
||||||
try:
|
|
||||||
command.upgrade(Config(str(ALEMBIC_INI)), "head")
|
|
||||||
yield path
|
|
||||||
finally:
|
|
||||||
if get_auth_engine.cache_info().currsize:
|
|
||||||
get_auth_engine().dispose()
|
|
||||||
get_auth_engine.cache_clear()
|
|
||||||
path.unlink(missing_ok=True)
|
|
||||||
assert not path.exists()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def client(storage):
|
|
||||||
with get_auth_engine().begin() as connection:
|
|
||||||
connection.execute(text("INSERT INTO user(username,password_hash) VALUES (:name,:hash)"),
|
|
||||||
{"name": "sample.user", "hash": generate_password_hash(TEST_PASSWORD, method="scrypt")})
|
|
||||||
connection.execute(text("INSERT INTO user_role(user_id,role_code) VALUES (1,'TEA'),(1,'CAMA')"))
|
|
||||||
app = create_app()
|
|
||||||
app.config["TESTING"] = True
|
|
||||||
with app.test_client() as client:
|
|
||||||
yield client
|
|
||||||
|
|
||||||
|
|
||||||
def login(client, **changes):
|
|
||||||
return client.post("/auth/login", json={"username": "sample.user", "password": TEST_PASSWORD, **changes})
|
|
||||||
|
|
||||||
|
|
||||||
def bearer(token):
|
|
||||||
return {"Authorization": f"Bearer {token}"}
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("value,expected", [(None, False), ("false", False), ("true", True)])
|
|
||||||
def test_flag(value, expected):
|
|
||||||
assert parse_auth_lite_enabled(value) is expected
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("value", ["1", "0", "yes", "no", "on", "off", "TRUE", "False", "", " true "])
|
|
||||||
def test_invalid_flag(value, monkeypatch):
|
|
||||||
with pytest.raises(ValueError, match="AUTH_LITE_ENABLED"):
|
|
||||||
parse_auth_lite_enabled(value)
|
|
||||||
monkeypatch.setenv("AUTH_LITE_ENABLED", value)
|
|
||||||
with pytest.raises(ValueError, match="AUTH_LITE_ENABLED"):
|
|
||||||
create_app()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("flag", [None, "false"])
|
|
||||||
@pytest.mark.parametrize("isolated_config", ["none", "secret", "url"])
|
|
||||||
def test_disabled_never_touches_storage(flag, isolated_config, monkeypatch, tmp_path):
|
|
||||||
import persistance.db as db
|
|
||||||
import persistance.auth.repository as repository
|
|
||||||
from webapi import auth_token
|
|
||||||
|
|
||||||
def forbidden(*args, **kwargs):
|
|
||||||
pytest.fail("Auth storage was touched while disabled")
|
|
||||||
|
|
||||||
monkeypatch.delenv("AUTH_LITE_ENABLED", raising=False)
|
|
||||||
if flag is not None:
|
|
||||||
monkeypatch.setenv("AUTH_LITE_ENABLED", flag)
|
|
||||||
monkeypatch.delenv("AUTH_LITE_SECRET_KEY", raising=False)
|
|
||||||
monkeypatch.delenv("AUTH_DATABASE_URL", raising=False)
|
|
||||||
if isolated_config == "secret":
|
|
||||||
monkeypatch.setenv("AUTH_LITE_SECRET_KEY", TEST_SECRET)
|
|
||||||
if isolated_config == "url":
|
|
||||||
monkeypatch.setenv("AUTH_DATABASE_URL", "invalid://unusable")
|
|
||||||
path = tmp_path / "never-created.sqlite"
|
|
||||||
monkeypatch.setattr(settings, "auth_database_url", f"sqlite:///{path.as_posix()}")
|
|
||||||
for name in ("get_auth_engine", "get_auth_session"):
|
|
||||||
monkeypatch.setattr(db, name, forbidden)
|
|
||||||
for name in ("get_user_by_username", "get_user_with_roles_by_id", "get_auth_session"):
|
|
||||||
monkeypatch.setattr(repository, name, forbidden)
|
|
||||||
monkeypatch.setattr(auth_token, "validate_auth_storage", forbidden)
|
|
||||||
from persistance.cacu import paciente_repository as cacu
|
|
||||||
from persistance.cama import paciente_repository as cama
|
|
||||||
from persistance.tea import pacientes_repository as tea
|
|
||||||
for repo in (cacu, cama, tea):
|
|
||||||
monkeypatch.setattr(repo, "get", lambda key: None)
|
|
||||||
app = create_app()
|
|
||||||
assert "auth" not in app.blueprints
|
|
||||||
assert {"cacu", "cama", "tea"} <= set(app.blueprints)
|
|
||||||
with app.test_client() as client:
|
|
||||||
assert client.get("/health").status_code == 200
|
|
||||||
assert client.post("/auth/login", json={}).status_code == 404
|
|
||||||
assert client.get("/auth/me").status_code == 404
|
|
||||||
for domain in ("cacu", "cama", "tea"):
|
|
||||||
response = client.get(f"/{domain}/pacientes/999")
|
|
||||||
assert response.status_code == 404
|
|
||||||
assert response.json == {"error": "not found"}
|
|
||||||
assert client.post(f"/{domain}/predict").status_code == 501
|
|
||||||
assert not path.exists()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("secret", [None, "", " "])
|
|
||||||
def test_enabled_requires_secret(storage, monkeypatch, secret):
|
|
||||||
monkeypatch.delenv("AUTH_LITE_SECRET_KEY", raising=False)
|
|
||||||
if secret is not None:
|
|
||||||
monkeypatch.setenv("AUTH_LITE_SECRET_KEY", secret)
|
|
||||||
with pytest.raises(ValueError, match="AUTH_LITE_SECRET_KEY"):
|
|
||||||
create_app()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("kind", ["missing", "unmigrated", "corrupt", "invalid_url", "inaccessible"])
|
|
||||||
def test_enabled_requires_migrated_storage(tmp_path, monkeypatch, kind):
|
|
||||||
import sqlite3
|
|
||||||
monkeypatch.setenv("AUTH_LITE_ENABLED", "true")
|
|
||||||
monkeypatch.setenv("AUTH_LITE_SECRET_KEY", TEST_SECRET)
|
|
||||||
path = tmp_path / "unusable.sqlite"
|
|
||||||
if kind == "unmigrated":
|
|
||||||
with closing(sqlite3.connect(path)) as connection:
|
|
||||||
connection.execute("CREATE TABLE unrelated(id INTEGER)")
|
|
||||||
connection.commit()
|
|
||||||
elif kind == "corrupt":
|
|
||||||
path.write_text("not a database", encoding="utf-8")
|
|
||||||
elif kind == "inaccessible":
|
|
||||||
path = tmp_path / "missing-parent" / "unusable.sqlite"
|
|
||||||
url = "invalid://unusable" if kind == "invalid_url" else f"sqlite:///{path.as_posix()}"
|
|
||||||
monkeypatch.setattr(settings, "auth_database_url", url)
|
|
||||||
get_auth_engine.cache_clear()
|
|
||||||
try:
|
|
||||||
with pytest.raises(ValueError, match="accessible migrated SQLite"):
|
|
||||||
create_app()
|
|
||||||
if kind in ("missing", "inaccessible"):
|
|
||||||
assert not path.exists()
|
|
||||||
if kind == "unmigrated":
|
|
||||||
with closing(sqlite3.connect(path)) as connection:
|
|
||||||
assert connection.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall() == [("unrelated",)]
|
|
||||||
finally:
|
|
||||||
if get_auth_engine.cache_info().currsize:
|
|
||||||
get_auth_engine().dispose()
|
|
||||||
get_auth_engine.cache_clear()
|
|
||||||
path.unlink(missing_ok=True)
|
|
||||||
|
|
||||||
|
|
||||||
def test_login_and_me(client):
|
|
||||||
response = login(client, username=" SAMPLE.User ")
|
|
||||||
assert response.status_code == 200
|
|
||||||
body = response.json
|
|
||||||
assert set(body) == {"token", "expires_in", "user"}
|
|
||||||
assert body["expires_in"] == TOKEN_MAX_AGE
|
|
||||||
expected = {"id": 1, "username": "sample.user", "roles": ["CAMA", "TEA"]}
|
|
||||||
assert body["user"] == expected
|
|
||||||
assert serializer(TEST_SECRET).loads(body["token"]) == {"user_id": 1, "v": 1}
|
|
||||||
assert "password" not in json.dumps(body) and "hash" not in json.dumps(body)
|
|
||||||
assert response.headers["Cache-Control"] == "no-store"
|
|
||||||
me = client.get("/auth/me", headers=bearer(body["token"]))
|
|
||||||
assert me.status_code == 200 and me.json == {"user": expected}
|
|
||||||
assert me.headers["Cache-Control"] == "no-store"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("condition", ["missing", "wrong_password", "inactive"])
|
|
||||||
def test_generic_credentials(client, condition):
|
|
||||||
changes = {}
|
|
||||||
if condition == "missing":
|
|
||||||
changes["username"] = "absent.user"
|
|
||||||
elif condition == "wrong_password":
|
|
||||||
changes["password"] = "incorrect"
|
|
||||||
else:
|
|
||||||
with get_auth_engine().begin() as connection:
|
|
||||||
connection.execute(text("UPDATE user SET activo=0 WHERE id=1"))
|
|
||||||
response = login(client, **changes)
|
|
||||||
assert response.status_code == 401 and response.json == {"error": "invalid_credentials"}
|
|
||||||
assert response.headers["Cache-Control"] == "no-store"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("body", [None, [], "text", 1, {}, {"username": "sample.user"},
|
|
||||||
{"password": TEST_PASSWORD}, {"username": 1, "password": TEST_PASSWORD},
|
|
||||||
{"username": "sample.user", "password": []},
|
|
||||||
*[{"username": name, "password": TEST_PASSWORD} for name in ("", "ab", "bad!", "ábc", "x" * 65)],
|
|
||||||
{"username": "sample.user", "password": ""}, {"username": "sample.user", "password": "x" * 129}])
|
|
||||||
def test_invalid_login_body(client, body):
|
|
||||||
response = client.post("/auth/login", data=json.dumps(body), content_type="application/json")
|
|
||||||
assert response.status_code == 400 and response.json == {"error": "invalid_request"}
|
|
||||||
assert response.headers["Cache-Control"] == "no-store"
|
|
||||||
|
|
||||||
|
|
||||||
def test_no_json_and_malformed_json(client):
|
|
||||||
for kwargs in ({"data": "plain"}, {"data": "{", "content_type": "application/json"}):
|
|
||||||
response = client.post("/auth/login", **kwargs)
|
|
||||||
assert response.status_code == 400
|
|
||||||
assert response.headers["Cache-Control"] == "no-store"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("header", [None, "Basic abc", "Bearer", "Bearer ", "Bearer garbage", "Bearer a b"])
|
|
||||||
def test_bad_authorization(client, header):
|
|
||||||
response = client.get("/auth/me", headers={} if header is None else {"Authorization": header})
|
|
||||||
assert response.status_code == 401 and response.json == {"error": "unauthorized"}
|
|
||||||
assert response.headers["Cache-Control"] == "no-store"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("payload", [None, [], 1, {}, {"user_id": 1}, {"user_id": 1, "v": 2},
|
|
||||||
{"user_id": 1, "v": True}, {"user_id": 1, "v": 1, "roles": []},
|
|
||||||
*[{"user_id": value, "v": 1} for value in (None, "1", True, 0, -1, 1.0, 2**63)]])
|
|
||||||
def test_bad_signed_payload(client, payload):
|
|
||||||
response = client.get("/auth/me", headers=bearer(serializer(TEST_SECRET).dumps(payload)))
|
|
||||||
assert response.status_code == 401 and response.json == {"error": "unauthorized"}
|
|
||||||
|
|
||||||
|
|
||||||
def test_altered_and_wrong_secret(client):
|
|
||||||
token = issue_token(TEST_SECRET, 1)
|
|
||||||
pieces = token.split(".")
|
|
||||||
pieces[-1] = ("A" if pieces[-1][0] != "A" else "B") + pieces[-1][1:]
|
|
||||||
for invalid in (".".join(pieces), issue_token("different-fictitious-secret", 1)):
|
|
||||||
assert client.get("/auth/me", headers=bearer(invalid)).status_code == 401
|
|
||||||
|
|
||||||
|
|
||||||
def test_expired_deterministically(client, monkeypatch):
|
|
||||||
from itsdangerous import TimestampSigner
|
|
||||||
monkeypatch.setattr(TimestampSigner, "get_timestamp", lambda self: 100000)
|
|
||||||
token = issue_token(TEST_SECRET, 1)
|
|
||||||
monkeypatch.setattr(TimestampSigner, "get_timestamp", lambda self: 100000 + TOKEN_MAX_AGE)
|
|
||||||
assert client.get("/auth/me", headers=bearer(token)).status_code == 200
|
|
||||||
monkeypatch.setattr(TimestampSigner, "get_timestamp", lambda self: 100001 + TOKEN_MAX_AGE)
|
|
||||||
response = client.get("/auth/me", headers=bearer(token))
|
|
||||||
assert response.status_code == 401 and response.json == {"error": "unauthorized"}
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("change", ["inactive", "deleted", "roles"])
|
|
||||||
def test_me_revalidates(client, change):
|
|
||||||
token = login(client).json["token"]
|
|
||||||
with get_auth_engine().begin() as connection:
|
|
||||||
if change == "inactive":
|
|
||||||
connection.execute(text("UPDATE user SET activo=0 WHERE id=1"))
|
|
||||||
elif change == "deleted":
|
|
||||||
connection.execute(text("DELETE FROM user WHERE id=1"))
|
|
||||||
else:
|
|
||||||
connection.execute(text("DELETE FROM user_role WHERE user_id=1"))
|
|
||||||
connection.execute(text("INSERT INTO user_role(user_id,role_code) VALUES (1,'CACU')"))
|
|
||||||
response = client.get("/auth/me", headers=bearer(token))
|
|
||||||
if change == "roles":
|
|
||||||
assert response.status_code == 200 and response.json["user"]["roles"] == ["CACU"]
|
|
||||||
else:
|
|
||||||
assert response.status_code == 401 and response.json == {"error": "unauthorized"}
|
|
||||||
|
|
||||||
|
|
||||||
def test_enabled_clinical_routes_are_independent(client, monkeypatch):
|
|
||||||
from persistance.cacu import paciente_repository as cacu
|
|
||||||
from persistance.cama import paciente_repository as cama
|
|
||||||
from persistance.tea import pacientes_repository as tea
|
|
||||||
for domain, repo in (("cacu", cacu), ("cama", cama), ("tea", tea)):
|
|
||||||
monkeypatch.setattr(repo, "get", lambda key: None)
|
|
||||||
assert client.get(f"/{domain}/pacientes/999").status_code == 404
|
|
||||||
assert client.post(f"/{domain}/predict").status_code == 501
|
|
||||||
assert client.get("/health").status_code == 200
|
|
||||||
assert client.get("/auth/login").headers["Cache-Control"] == "no-store"
|
|
||||||
assert client.get("/auth/missing").headers["Cache-Control"] == "no-store"
|
|
||||||
|
|
||||||
|
|
||||||
def test_bootstrap_creation_repeat_and_update(storage, monkeypatch, capsys):
|
|
||||||
from webapi import auth_bootstrap
|
|
||||||
monkeypatch.setattr(auth_bootstrap, "getpass", lambda prompt: TEST_PASSWORD)
|
|
||||||
assert main(["--username", " NEW.User ", "--roles", "TEA", "CAMA", "CAMA"]) == 0
|
|
||||||
from persistance.auth.repository import get_user_by_username, get_user_with_roles_by_id
|
|
||||||
user = get_user_by_username("new.user")
|
|
||||||
assert user.password_hash.startswith("scrypt:") and check_password_hash(user.password_hash, TEST_PASSWORD)
|
|
||||||
assert get_user_with_roles_by_id(user.id)[1] == ["CAMA", "TEA"]
|
|
||||||
old_hash = user.password_hash
|
|
||||||
assert main(["--username", "new.user", "--roles", "ADMIN"]) == 1
|
|
||||||
assert get_user_by_username("new.user").password_hash == old_hash
|
|
||||||
with get_auth_engine().begin() as connection:
|
|
||||||
connection.execute(text("UPDATE user SET activo=0 WHERE id=:id"), {"id": user.id})
|
|
||||||
new_password = "another-fictitious-password"
|
|
||||||
monkeypatch.setattr(auth_bootstrap, "getpass", lambda prompt: new_password)
|
|
||||||
assert main(["--username", "new.user", "--roles", "ADMIN", "--update"]) == 0
|
|
||||||
updated = get_user_by_username("new.user")
|
|
||||||
assert updated.id == user.id and not updated.activo
|
|
||||||
assert check_password_hash(updated.password_hash, new_password)
|
|
||||||
assert get_user_with_roles_by_id(user.id)[1] == ["ADMIN"]
|
|
||||||
output = capsys.readouterr()
|
|
||||||
assert all(value not in output.out + output.err for value in (TEST_PASSWORD, new_password, old_hash, updated.password_hash))
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("username,roles,password", [
|
|
||||||
("bad!", ["CAMA"], TEST_PASSWORD), (None, ["CAMA"], TEST_PASSWORD),
|
|
||||||
("good.user", [], TEST_PASSWORD), ("good.user", ["OTHER"], TEST_PASSWORD),
|
|
||||||
*[("good.user", ["CAMA"], value) for value in (None, "", "short", "x" * 129)]])
|
|
||||||
def test_bootstrap_invalid(storage, username, roles, password):
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
bootstrap(username, roles, password)
|
|
||||||
with get_auth_engine().connect() as connection:
|
|
||||||
assert connection.execute(text("SELECT count(*) FROM user")).scalar_one() == 0
|
|
||||||
|
|
||||||
|
|
||||||
def test_bootstrap_atomic_rollback(storage):
|
|
||||||
from sqlalchemy.exc import IntegrityError
|
|
||||||
from persistance.auth.repository import get_user_by_username, get_user_with_roles_by_id
|
|
||||||
user_id = bootstrap("atomic.user", ["CAMA"], TEST_PASSWORD)
|
|
||||||
original_hash = get_user_by_username("atomic.user").password_hash
|
|
||||||
with get_auth_engine().begin() as connection:
|
|
||||||
connection.execute(text("DELETE FROM role WHERE code='TEA'"))
|
|
||||||
for name, update in (("new.user", False), ("atomic.user", True)):
|
|
||||||
with pytest.raises(IntegrityError):
|
|
||||||
bootstrap(name, ["ADMIN", "TEA"], "different-fictitious-password", update=update)
|
|
||||||
assert get_user_by_username("new.user") is None
|
|
||||||
assert get_user_by_username("atomic.user").password_hash == original_hash
|
|
||||||
assert get_user_with_roles_by_id(user_id)[1] == ["CAMA"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_bootstrap_cli_rejects_role_and_password_argument(storage):
|
|
||||||
for args in (["--username", "sample.user", "--roles", "OTHER"],
|
|
||||||
["--username", "sample.user", "--roles", "CAMA", "--password", "dummy"]):
|
|
||||||
with pytest.raises(SystemExit) as error:
|
|
||||||
main(args)
|
|
||||||
assert error.value.code == 2
|
|
||||||
|
|
||||||
|
|
||||||
def test_bootstrap_cli_invalid_password(storage, monkeypatch, capsys):
|
|
||||||
from webapi import auth_bootstrap
|
|
||||||
monkeypatch.setattr(auth_bootstrap, "getpass", lambda prompt: "short")
|
|
||||||
assert main(["--username", "sample.user", "--roles", "CAMA"]) == 1
|
|
||||||
assert "short" not in capsys.readouterr().out
|
|
||||||
|
|
||||||
|
|
||||||
# Fase J: all demo credentials are consumed from the single seed definition.
|
|
||||||
from webapi import auth_demo_seed as demo
|
|
||||||
|
|
||||||
|
|
||||||
def demo_snapshot():
|
|
||||||
with get_auth_engine().connect() as connection:
|
|
||||||
return (connection.execute(text("SELECT * FROM user ORDER BY id")).fetchall(),
|
|
||||||
connection.execute(text("SELECT * FROM user_role ORDER BY user_id,role_code")).fetchall())
|
|
||||||
|
|
||||||
|
|
||||||
def test_demo_definition():
|
|
||||||
accounts = demo.validate_demo_users()
|
|
||||||
assert [(a["username"], a["roles"]) for a in accounts] == [
|
|
||||||
("admin", ("ADMIN",)), ("cacu", ("CACU",)), ("cama", ("CAMA",)), ("tea", ("TEA",))]
|
|
||||||
|
|
||||||
|
|
||||||
def test_demo_ensure_hashes_roles_http_and_idempotence(storage, capsys):
|
|
||||||
assert demo.main(["--ensure"]) == 0
|
|
||||||
original = demo_snapshot()
|
|
||||||
assert len(original[0]) == 4
|
|
||||||
from persistance.auth.repository import get_user_by_username, get_user_with_roles_by_id
|
|
||||||
app = create_app()
|
|
||||||
with app.test_client() as client:
|
|
||||||
for account in demo.DEMO_USERS:
|
|
||||||
user = get_user_by_username(account["username"])
|
|
||||||
assert user.password_hash != account["password"]
|
|
||||||
assert user.password_hash.startswith("scrypt:")
|
|
||||||
assert check_password_hash(user.password_hash, account["password"])
|
|
||||||
assert get_user_with_roles_by_id(user.id)[1] == list(account["roles"])
|
|
||||||
response = client.post("/auth/login", json={"username": account["username"], "password": account["password"]})
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert response.json["user"]["roles"] == list(account["roles"])
|
|
||||||
assert demo.main(["--ensure"]) == 0
|
|
||||||
assert demo_snapshot() == original
|
|
||||||
output = capsys.readouterr().out
|
|
||||||
assert output.count("-> created") == 4 and output.count("-> skipped") == 4
|
|
||||||
assert all(a["password"] not in output for a in demo.DEMO_USERS)
|
|
||||||
assert all(row.password_hash not in output for row in original[0])
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("roles,active", [(["TEA"], True), (["CAMA", "TEA"], False), (["ADMIN"], False)])
|
|
||||||
def test_demo_partial_preserves_every_existing_field(storage, roles, active):
|
|
||||||
bootstrap(" ADMIN ", roles, TEST_PASSWORD)
|
|
||||||
with get_auth_engine().begin() as connection:
|
|
||||||
connection.execute(text("UPDATE user SET activo=:active WHERE username='admin'"), {"active": active})
|
|
||||||
original = demo_snapshot()
|
|
||||||
result = demo.seed_demo_users()
|
|
||||||
assert [r[2] for r in result] == ["skipped", "created", "created", "created"]
|
|
||||||
after = demo_snapshot()
|
|
||||||
assert after[0][0] == original[0][0]
|
|
||||||
assert [r for r in after[1] if r.user_id == original[0][0].id] == original[1]
|
|
||||||
assert check_password_hash(after[0][0].password_hash, TEST_PASSWORD)
|
|
||||||
|
|
||||||
|
|
||||||
def test_demo_normalizes_before_lookup(storage, monkeypatch):
|
|
||||||
bootstrap("admin", ["TEA"], TEST_PASSWORD)
|
|
||||||
monkeypatch.setattr(demo, "DEMO_USERS", tuple({**a, "username": f" {a['username'].upper()} "} for a in demo.DEMO_USERS))
|
|
||||||
result = demo.seed_demo_users()
|
|
||||||
assert result[0] == ("admin", ("ADMIN",), "skipped")
|
|
||||||
assert len(demo_snapshot()[0]) == 4
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("invalid", [
|
|
||||||
{"username": "bad!"}, {"password": ""}, {"password": "short"},
|
|
||||||
{"roles": ()}, {"roles": ("OTHER",)}, {"roles": ("ADMIN", "ADMIN")},
|
|
||||||
{"roles": "ADMIN"}, {"roles": (None,)}, {"username": None},
|
|
||||||
])
|
|
||||||
@pytest.mark.parametrize("replace", [False, True])
|
|
||||||
def test_demo_invalid_configuration_never_changes_db(storage, monkeypatch, invalid, replace):
|
|
||||||
bootstrap("existing.user", ["TEA"], TEST_PASSWORD)
|
|
||||||
original = demo_snapshot()
|
|
||||||
monkeypatch.setattr(demo, "DEMO_USERS", (*demo.DEMO_USERS[:-1], {**demo.DEMO_USERS[-1], **invalid}))
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
demo.seed_demo_users(replace_all=replace)
|
|
||||||
assert demo_snapshot() == original
|
|
||||||
|
|
||||||
|
|
||||||
def test_demo_duplicate_normalized_username(storage, monkeypatch):
|
|
||||||
monkeypatch.setattr(demo, "DEMO_USERS", (*demo.DEMO_USERS, {**demo.DEMO_USERS[0], "username": " ADMIN "}))
|
|
||||||
with pytest.raises(ValueError, match="duplicate"):
|
|
||||||
demo.seed_demo_users()
|
|
||||||
assert demo_snapshot() == ([], [])
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("replace", [False, True])
|
|
||||||
def test_demo_missing_roles_before_mutation(storage, replace):
|
|
||||||
bootstrap("existing.user", ["ADMIN"], TEST_PASSWORD)
|
|
||||||
with get_auth_engine().begin() as connection:
|
|
||||||
connection.execute(text("DELETE FROM role WHERE code='TEA'"))
|
|
||||||
original = demo_snapshot()
|
|
||||||
with pytest.raises(ValueError, match="roles are missing"):
|
|
||||||
demo.seed_demo_users(replace_all=replace)
|
|
||||||
assert demo_snapshot() == original
|
|
||||||
|
|
||||||
|
|
||||||
def test_demo_replace_confirmed_cascade_schema_and_output(storage, monkeypatch, capsys):
|
|
||||||
bootstrap("foreign.user", ["CAMA", "TEA"], TEST_PASSWORD)
|
|
||||||
monkeypatch.setattr("builtins.input", lambda prompt: "REPLACE")
|
|
||||||
with get_auth_engine().connect() as connection:
|
|
||||||
schema = connection.execute(text("SELECT name,sql FROM sqlite_master ORDER BY name")).fetchall()
|
|
||||||
version = connection.execute(text("SELECT * FROM alembic_version")).fetchall()
|
|
||||||
assert demo.main(["--replace-all"]) == 0
|
|
||||||
users, associations = demo_snapshot()
|
|
||||||
assert {r.username for r in users} == {a["username"] for a in demo.DEMO_USERS}
|
|
||||||
assert len(associations) == 4
|
|
||||||
with get_auth_engine().connect() as connection:
|
|
||||||
assert connection.execute(text("PRAGMA foreign_keys")).scalar_one() == 1
|
|
||||||
assert connection.execute(text("PRAGMA foreign_key_check")).fetchall() == []
|
|
||||||
assert connection.execute(text("SELECT name,sql FROM sqlite_master ORDER BY name")).fetchall() == schema
|
|
||||||
assert connection.execute(text("SELECT * FROM alembic_version")).fetchall() == version
|
|
||||||
assert connection.execute(text("SELECT count(*) FROM role")).scalar_one() == 4
|
|
||||||
assert storage.is_file()
|
|
||||||
output = capsys.readouterr().out
|
|
||||||
assert "WARNING" in output and "replaced" in output
|
|
||||||
assert all(a["password"] not in output for a in demo.DEMO_USERS)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("answer", ["", "replace", " REPLACE", "REPLACE ", "NO", None])
|
|
||||||
def test_demo_cancelled_before_storage(storage, monkeypatch, answer, capsys):
|
|
||||||
bootstrap("foreign.user", ["TEA"], TEST_PASSWORD)
|
|
||||||
original = demo_snapshot()
|
|
||||||
def confirm(prompt):
|
|
||||||
if answer is None:
|
|
||||||
raise EOFError
|
|
||||||
return answer
|
|
||||||
monkeypatch.setattr("builtins.input", confirm)
|
|
||||||
monkeypatch.setattr(demo, "validate_auth_storage", lambda: pytest.fail("cancel touched storage"))
|
|
||||||
assert demo.main(["--replace-all"]) == 0
|
|
||||||
assert demo_snapshot() == original
|
|
||||||
assert "cancelled" in capsys.readouterr().out
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("replace", [False, True])
|
|
||||||
def test_demo_insert_failure_rolls_back_everything(storage, monkeypatch, replace):
|
|
||||||
from sqlmodel import Session
|
|
||||||
bootstrap("foreign.user", ["TEA", "CAMA"], TEST_PASSWORD)
|
|
||||||
original = demo_snapshot()
|
|
||||||
original_flush = Session.flush
|
|
||||||
calls = 0
|
|
||||||
def failing_flush(self, *args, **kwargs):
|
|
||||||
nonlocal calls
|
|
||||||
calls += 1
|
|
||||||
result = original_flush(self, *args, **kwargs)
|
|
||||||
if calls == 5:
|
|
||||||
raise RuntimeError("injected after mutation")
|
|
||||||
return result
|
|
||||||
monkeypatch.setattr(Session, "flush", failing_flush)
|
|
||||||
with pytest.raises(RuntimeError):
|
|
||||||
demo.seed_demo_users(replace_all=replace)
|
|
||||||
assert calls >= 5
|
|
||||||
assert demo_snapshot() == original
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("mode", ["--ensure", "--replace-all"])
|
|
||||||
def test_demo_disabled_never_touches_storage(monkeypatch, mode, capsys):
|
|
||||||
monkeypatch.setenv("AUTH_LITE_ENABLED", "false")
|
|
||||||
monkeypatch.setenv("AUTH_LITE_SEED_DEMO_USERS", "true")
|
|
||||||
monkeypatch.setattr(demo, "validate_auth_storage", lambda: pytest.fail("disabled touched storage"))
|
|
||||||
monkeypatch.setattr("builtins.input", lambda prompt: pytest.fail("disabled requested confirmation"))
|
|
||||||
assert demo.main([mode]) == 0
|
|
||||||
assert "disabled" in capsys.readouterr().out
|
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import hashlib
|
||||||
|
from io import BytesIO
|
||||||
|
from zipfile import ZipFile
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import HTTPException, UploadFile
|
||||||
|
|
||||||
|
from core.domains import Domain
|
||||||
|
from persistance import config
|
||||||
|
from webapi.models import import_models
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("kind", "status", "detail"),
|
||||||
|
[
|
||||||
|
("wrong_sha", 422, "not the one given"),
|
||||||
|
("non_zip", 422, "not a bundle"),
|
||||||
|
("untrusted", 403, "not trusted on this server"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_import_rejects_invalid_uploads(tmp_path, monkeypatch, kind, status, detail):
|
||||||
|
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
|
||||||
|
if kind == "non_zip":
|
||||||
|
data = b"hello"
|
||||||
|
else:
|
||||||
|
buffer = BytesIO()
|
||||||
|
with ZipFile(buffer, "w") as archive:
|
||||||
|
archive.writestr("manifest.json", "{}")
|
||||||
|
data = buffer.getvalue()
|
||||||
|
digest = hashlib.sha256(data).hexdigest()
|
||||||
|
sent = "0" * 64 if kind == "wrong_sha" else digest
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException) as rejected:
|
||||||
|
import_models(Domain.TEA, sent, UploadFile(BytesIO(data), filename="bundle.zip"))
|
||||||
|
assert rejected.value.status_code == status
|
||||||
|
assert detail in rejected.value.detail
|
||||||
|
assert not (tmp_path / "bundles" / f"{digest}.zip").exists()
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
import pytest
|
||||||
|
from dagster import DagsterRunStatus
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from persistance.cluster import Progress
|
||||||
|
from webapi.runs import _locked, cancel_run, shape
|
||||||
|
|
||||||
|
PAYLOAD = {
|
||||||
|
"runId": "run",
|
||||||
|
"jobName": "analyze",
|
||||||
|
"status": "SUCCESS",
|
||||||
|
"startTime": 1.0,
|
||||||
|
"endTime": 4.0,
|
||||||
|
"tags": [{"key": "domain", "value": "cacu"}],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_shape_splits_info_and_warnings():
|
||||||
|
def event(level, message, step_key=None, kind="LogMessageEvent"):
|
||||||
|
return {"__typename": kind, "level": level, "message": message, "stepKey": step_key}
|
||||||
|
|
||||||
|
run = shape(
|
||||||
|
PAYLOAD,
|
||||||
|
[
|
||||||
|
event("INFO", "starting"),
|
||||||
|
event("WARNING", "skipped", "analyze_studies"),
|
||||||
|
event("DEBUG", "debug"),
|
||||||
|
event("INFO", "engine", kind="EngineEvent"),
|
||||||
|
event("INFO", "finished", "analyze_studies"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
assert run.info == ["starting", "analyze_studies: finished"]
|
||||||
|
assert run.warnings == ["analyze_studies: skipped"]
|
||||||
|
assert run.error is None
|
||||||
|
|
||||||
|
warning_only = shape(PAYLOAD, [event("WARNING", "skipped")])
|
||||||
|
assert warning_only.state == "succeeded"
|
||||||
|
assert warning_only.error is None
|
||||||
|
|
||||||
|
steps = [
|
||||||
|
{"stepKey": "waiting", "status": "SKIPPED", "startTime": None, "endTime": None},
|
||||||
|
{"stepKey": "second", "status": "SUCCESS", "startTime": 2, "endTime": 4},
|
||||||
|
{"stepKey": "first", "status": "SUCCESS", "startTime": 0, "endTime": 1},
|
||||||
|
]
|
||||||
|
assert [step.key for step in shape(PAYLOAD | {"stepStats": steps}, []).steps] == [
|
||||||
|
"first", "second", "waiting",
|
||||||
|
] # fmt: skip
|
||||||
|
|
||||||
|
capped = shape(
|
||||||
|
PAYLOAD, [event(level, str(i)) for i in range(201) for level in ("INFO", "WARNING")]
|
||||||
|
)
|
||||||
|
assert capped.info == [str(i) for i in range(1, 201)]
|
||||||
|
assert capped.warnings == [str(i) for i in range(200)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_shape_failure_message_is_the_ops_own_exception():
|
||||||
|
failed = PAYLOAD | {"status": "FAILURE"}
|
||||||
|
step_failure = {
|
||||||
|
"__typename": "ExecutionStepFailureEvent",
|
||||||
|
"error": {
|
||||||
|
"message": "DagsterExecutionStepExecutionError: invocation failed",
|
||||||
|
"causes": [
|
||||||
|
{"message": "intermediate cause"},
|
||||||
|
{"message": " LookupError: no EEG x|2026-01-01\nmore details "},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
assert shape(failed, [step_failure]).error == "LookupError: no EEG x|2026-01-01"
|
||||||
|
run_failure = {"__typename": "RunFailureEvent", "error": {"message": "x" * 501}}
|
||||||
|
assert shape(failed, [step_failure, run_failure]).error == "x" * 500
|
||||||
|
assert shape(failed, []).error == "the run failed"
|
||||||
|
|
||||||
|
|
||||||
|
def test_shape_progress_tag():
|
||||||
|
progress = Progress(
|
||||||
|
phase="analyzing", done=3, total=6, elapsed_s=4, eta_s=4, mode="sync",
|
||||||
|
scheduler=None, updated_at="2026-01-01T00:00:00Z",
|
||||||
|
) # fmt: skip
|
||||||
|
|
||||||
|
def with_tag(value):
|
||||||
|
return PAYLOAD | {"tags": [{"key": "isssteleon/progress", "value": value}]}
|
||||||
|
|
||||||
|
run = shape(with_tag(progress.model_dump_json()), [])
|
||||||
|
assert run.progress is not None
|
||||||
|
assert run.progress.done == 3
|
||||||
|
assert run.progress.phase == "analyzing"
|
||||||
|
assert shape(with_tag("{bad json"), []).progress is None
|
||||||
|
for status, state in (
|
||||||
|
("QUEUED", "queued"),
|
||||||
|
("STARTING", "running"),
|
||||||
|
("CANCELING", "cancelling"),
|
||||||
|
("CANCELED", "cancelled"),
|
||||||
|
):
|
||||||
|
run = shape(PAYLOAD | {"status": status}, [])
|
||||||
|
assert (run.status, run.state) == (status, state)
|
||||||
|
assert shape(PAYLOAD | {"status": "UNKNOWN"}, []).state == "running"
|
||||||
|
|
||||||
|
|
||||||
|
def test_shape_outputs():
|
||||||
|
events = [
|
||||||
|
{
|
||||||
|
"__typename": "ExecutionStepOutputEvent",
|
||||||
|
"stepKey": "preview_study",
|
||||||
|
"outputName": "result",
|
||||||
|
"metadataEntries": [
|
||||||
|
{"label": "result", "jsonString": '{"eeg": {"valid": false}}'},
|
||||||
|
{"label": "text"},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
assert shape(PAYLOAD, events, outputs=True).outputs == {
|
||||||
|
"preview_study.result": {"eeg": {"valid": False}}
|
||||||
|
}
|
||||||
|
assert shape(PAYLOAD, events, outputs=False).outputs is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("initial", [DagsterRunStatus.QUEUED, DagsterRunStatus.STARTED])
|
||||||
|
def test_cancel_returns_the_terminal_or_cancelling_state(initial):
|
||||||
|
class Client:
|
||||||
|
status = initial
|
||||||
|
|
||||||
|
def get_run_status(self, run_id):
|
||||||
|
return self.status
|
||||||
|
|
||||||
|
def terminate_run(self, run_id):
|
||||||
|
self.status = {
|
||||||
|
DagsterRunStatus.QUEUED: DagsterRunStatus.CANCELED,
|
||||||
|
DagsterRunStatus.STARTED: DagsterRunStatus.CANCELING,
|
||||||
|
}[self.status]
|
||||||
|
|
||||||
|
result = cancel_run("r1", client=Client())
|
||||||
|
expected = (
|
||||||
|
("CANCELED", "cancelled")
|
||||||
|
if initial == DagsterRunStatus.QUEUED
|
||||||
|
else ("CANCELING", "cancelling")
|
||||||
|
)
|
||||||
|
assert (result.id, result.status, result.state) == ("r1", *expected)
|
||||||
|
|
||||||
|
|
||||||
|
def test_cancel_a_finished_run_is_409():
|
||||||
|
class Client:
|
||||||
|
def get_run_status(self, run_id):
|
||||||
|
return DagsterRunStatus.SUCCESS
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException) as error:
|
||||||
|
cancel_run("r1", client=Client())
|
||||||
|
assert error.value.status_code == 409
|
||||||
|
assert error.value.detail == "the run already ended: succeeded"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_storage_lock_is_distinguished_from_a_run_failure():
|
||||||
|
assert _locked({"errors": [{"message": "OperationalError: database is locked"}]})
|
||||||
|
assert _locked(
|
||||||
|
{"data": {"logsForRun": {"__typename": "PythonError", "message": "database is locked"}}}
|
||||||
|
)
|
||||||
|
assert not _locked(
|
||||||
|
{"data": {"logsForRun": {"__typename": "EventConnection", "message": "database is locked"}}}
|
||||||
|
)
|
||||||
|
assert not _locked(
|
||||||
|
{"data": {"logsForRun": {"__typename": "PythonError", "message": "unknown error"}}}
|
||||||
|
)
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import sqlite3
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from webapi import sources
|
||||||
|
from webapi.main import app
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(own_platform, monkeypatch):
|
||||||
|
monkeypatch.setenv("SOURCE_ROOTS", str(own_platform / "shared"))
|
||||||
|
(own_platform / "shared" / "reportes" / "2026").mkdir(parents=True)
|
||||||
|
with TestClient(app) as c:
|
||||||
|
yield c
|
||||||
|
|
||||||
|
|
||||||
|
def probe(client, kind, **answers):
|
||||||
|
response = client.post("/ingest/sources/test", json={"type": kind, "answers": answers})
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_dialog_lists_every_kind_with_its_questions(client):
|
||||||
|
found = client.get("/ingest/sources/types").json()
|
||||||
|
assert {"database", "files", "cloud", "web"} <= set(found["groups"])
|
||||||
|
assert found["types"]["sqlserver"]["fields"]["password"]["type"] == "password"
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_unknown_server_and_a_missing_answer_say_so_plainly(client):
|
||||||
|
gone = probe(client, "sqlserver", host="nowhere.invalid", database="P", user="u",
|
||||||
|
password="p") # fmt: skip
|
||||||
|
assert not gone["ok"] and gone["message"].startswith(("No se encontró", "El servidor no"))
|
||||||
|
assert probe(client, "postgresql", host="h")["message"].startswith("falta «Base de datos»")
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_sqlite_file_lists_its_tables_then_shows_rows(client, own_platform):
|
||||||
|
path = own_platform / "shared" / "hospital.db"
|
||||||
|
with sqlite3.connect(path) as con:
|
||||||
|
con.execute("create table pacientes (id int, nombre text)")
|
||||||
|
con.execute("insert into pacientes values (1, 'Ana')")
|
||||||
|
assert probe(client, "sqlite", path=str(path))["tables"] == ["pacientes"]
|
||||||
|
rows = probe(client, "sqlite", path=str(path), table="pacientes")["rows"]
|
||||||
|
assert rows == [{"id": 1, "nombre": "Ana"}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_server_folders_are_browsed_only_under_the_mounted_roots(client, own_platform):
|
||||||
|
roots = client.get("/ingest/sources/browse").json()["entries"]
|
||||||
|
assert [e["name"] for e in roots] == ["shared"]
|
||||||
|
inside = client.get("/ingest/sources/browse", params={"path": roots[0]["path"]}).json()
|
||||||
|
assert [e["name"] for e in inside["entries"]] == ["reportes"]
|
||||||
|
assert client.get("/ingest/sources/browse", params={"path": "/etc"}).status_code == 404
|
||||||
|
escape = str(own_platform / "shared" / ".." / "data")
|
||||||
|
assert client.get("/ingest/sources/browse", params={"path": escape}).status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_folder_uploaded_from_a_computer_is_read_as_spreadsheets_or_documents(client):
|
||||||
|
sent = [("files", ("informes/enero/a.csv", b"folio,resultado\n1,NEGATIVO\n")),
|
||||||
|
("files", ("informes/b.pdf", b"%PDF-1.4 ..."))] # fmt: skip
|
||||||
|
uploaded = client.post("/ingest/uploads", files=sent).json()
|
||||||
|
assert sorted(uploaded["files"]) == ["informes/b.pdf", "informes/enero/a.csv"]
|
||||||
|
more = client.post("/ingest/uploads", files=[("files", ("../../fuera.csv", b"x\n"))],
|
||||||
|
data={"folder": uploaded["bucket_url"]}).json() # fmt: skip
|
||||||
|
assert more["files"] == ["fuera.csv"] and more["bucket_url"] == uploaded["bucket_url"]
|
||||||
|
other = client.post("/ingest/uploads", files=[("files", ("x", b"x"))], data={"folder": "/"})
|
||||||
|
assert other.status_code == 422
|
||||||
|
rows = probe(client, "upload", folder=uploaded["bucket_url"], pattern="**/*.csv",
|
||||||
|
read_as="dlt.sources.filesystem:read_csv")["rows"] # fmt: skip
|
||||||
|
assert rows == [{"folio": 1, "resultado": "NEGATIVO"}]
|
||||||
|
files = probe(client, "upload", folder=uploaded["bucket_url"], pattern="**/*.pdf")["rows"]
|
||||||
|
assert [f["file_name"] for f in files] == ["b.pdf"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_empty_folder_says_what_to_check(client, own_platform):
|
||||||
|
found = probe(client, "server_folder", folder=str(own_platform / "shared" / "reportes"))
|
||||||
|
assert found["ok"] and "Revise la ruta" in found["message"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_sign_in_button_without_an_app_registration_says_who_must_register_one(client):
|
||||||
|
found = client.get("/ingest/sources/oauth/google/start", params={"origin": "http://x"})
|
||||||
|
assert found.status_code == 503 and "GOOGLE_CLIENT_ID" in found.json()["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_signing_in_hands_the_account_to_the_dialog(client, monkeypatch, tmp_path):
|
||||||
|
from authlib.integrations.httpx_client import OAuth2Client, oauth2_client
|
||||||
|
|
||||||
|
httpx = oauth2_client.httpx2
|
||||||
|
|
||||||
|
monkeypatch.setenv("MICROSOFT_CLIENT_ID", "app")
|
||||||
|
monkeypatch.setenv("MICROSOFT_CLIENT_SECRET", "app-secret")
|
||||||
|
exchanged = {}
|
||||||
|
|
||||||
|
def provider(request: httpx.Request) -> httpx.Response:
|
||||||
|
exchanged["body"] = request.content.decode()
|
||||||
|
return httpx.Response(200, json={"access_token": "at", "refresh_token": "rt",
|
||||||
|
"token_type": "Bearer", "expires_in": 3600}) # fmt: skip
|
||||||
|
|
||||||
|
def client_for(found, env, redirect_uri):
|
||||||
|
return OAuth2Client(env["client_id"], env["client_secret"], scope=found.scope,
|
||||||
|
redirect_uri=redirect_uri, code_challenge_method="S256",
|
||||||
|
transport=httpx.MockTransport(provider)) # fmt: skip
|
||||||
|
|
||||||
|
monkeypatch.setattr(sources, "_client", client_for)
|
||||||
|
monkeypatch.setattr(sources, "PENDING", tmp_path / "pending")
|
||||||
|
monkeypatch.setattr(sources, "account", lambda p, token, env: {
|
||||||
|
"user": "ana@hospital.mx", "drive_id": "d1",
|
||||||
|
"oauth2_client_params": {"client_id": env["client_id"], "token": token}}) # fmt: skip
|
||||||
|
start = client.get("/ingest/sources/oauth/microsoft/start",
|
||||||
|
params={"origin": "http://10.0.10.41:5710"}).json() # fmt: skip
|
||||||
|
assert start["url"].startswith("https://login.microsoftonline.com/organizations/")
|
||||||
|
assert "code_challenge=" in start["url"] and "client_id=app" in start["url"]
|
||||||
|
back = client.get("/ingest/sources/oauth/microsoft/callback",
|
||||||
|
params={"state": start["state"], "code": "c0de"}) # fmt: skip
|
||||||
|
assert back.status_code == 200
|
||||||
|
assert '"user": "ana@hospital.mx"' in back.text and '"http://10.0.10.41:5710"' in back.text
|
||||||
|
assert "code_verifier=" in exchanged["body"] and "code=c0de" in exchanged["body"]
|
||||||
|
again = client.get("/ingest/sources/oauth/microsoft/callback",
|
||||||
|
params={"state": start["state"], "code": "c0de"}) # fmt: skip
|
||||||
|
assert again.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_saved_account_shows_who_but_never_its_tokens():
|
||||||
|
from core.pipeline import MASK, Pipeline, redacted, restored
|
||||||
|
|
||||||
|
params = {"client_id": "app", "client_secret": "app-secret-xyz",
|
||||||
|
"token": {"refresh_token": "refresh-xyz"}} # fmt: skip
|
||||||
|
account = {"user": "ana@hospital.mx", "drive_id": "d1", "oauth2_client_params": params}
|
||||||
|
saved = Pipeline(nodes=[{"id": "s", "kind": "source", "guided": {
|
||||||
|
"type": "onedrive", "answers": {"account": account, "folder": "Reportes"}}}]) # fmt: skip
|
||||||
|
shown = redacted(saved)
|
||||||
|
answer = shown.nodes[0].guided.answers["account"]
|
||||||
|
assert answer["user"] == "ana@hospital.mx"
|
||||||
|
dumped = shown.model_dump_json()
|
||||||
|
assert "refresh-xyz" not in dumped and "app-secret-xyz" not in dumped
|
||||||
|
assert answer["oauth2_client_params"]["client_secret"] == MASK
|
||||||
|
back = restored(Pipeline.model_validate(shown.model_dump()), saved).nodes[0]
|
||||||
|
assert (
|
||||||
|
back.args["storage_options"]["oauth2_client_params"]["token"]["refresh_token"]
|
||||||
|
== "refresh-xyz"
|
||||||
|
)
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import pytest
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from pydantic import ValidationError
|
||||||
|
|
||||||
|
from core.domains import Domain
|
||||||
|
from persistance.cluster import FolderTrainingSource
|
||||||
|
from webapi import models
|
||||||
|
from webapi.models import Training, train, training_config
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def sync_execution(monkeypatch):
|
||||||
|
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||||
|
|
||||||
|
|
||||||
|
def test_tea_training_config_schema():
|
||||||
|
config = training_config(Domain.TEA, "example").model_dump()
|
||||||
|
assert (config["domain"], config["name"]) == ("tea", "example")
|
||||||
|
schema = config["json_schema"]
|
||||||
|
assert schema["title"] == "TrainingForm"
|
||||||
|
assert set(schema["properties"]) == {"as_of", "execution", "source"}
|
||||||
|
assert schema["properties"]["as_of"]["title"] == "Datos hasta"
|
||||||
|
assert set(schema["$defs"]) == {
|
||||||
|
"Execution",
|
||||||
|
"TrainingSource",
|
||||||
|
"SiteTrainingSource",
|
||||||
|
"FolderTrainingSource",
|
||||||
|
}
|
||||||
|
execution = schema["$defs"]["Execution"]
|
||||||
|
assert execution["title"] == "Ejecución"
|
||||||
|
assert execution["properties"]["mode"]["title"] == "Modo"
|
||||||
|
assert execution["properties"]["scheduler"]["title"] == "Planificador Dask"
|
||||||
|
source = schema["$defs"]["TrainingSource"]
|
||||||
|
assert source["discriminator"] == {
|
||||||
|
"propertyName": "kind",
|
||||||
|
"mapping": {
|
||||||
|
"site": "#/$defs/SiteTrainingSource",
|
||||||
|
"folder": "#/$defs/FolderTrainingSource",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
assert source["oneOf"] == [
|
||||||
|
{"$ref": "#/$defs/SiteTrainingSource"},
|
||||||
|
{"$ref": "#/$defs/FolderTrainingSource"},
|
||||||
|
]
|
||||||
|
site = schema["$defs"]["SiteTrainingSource"]
|
||||||
|
assert set(site["properties"]) == {"kind"}
|
||||||
|
folder = schema["$defs"]["FolderTrainingSource"]
|
||||||
|
assert folder["properties"]["folder"]["title"] == "Carpeta"
|
||||||
|
assert folder["properties"]["line_hz"]["enum"] == [50, 60]
|
||||||
|
assert (site["title"], folder["title"]) == (
|
||||||
|
"Niños del sitio sin el diagnóstico",
|
||||||
|
"Carpeta de EDF con edades",
|
||||||
|
)
|
||||||
|
assert schema["properties"]["source"]["title"] == "Datos de entrenamiento"
|
||||||
|
assert config["defaults"] == {
|
||||||
|
"execution": {"mode": "sync", "scheduler": None},
|
||||||
|
"source": {"kind": "site"},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_other_domains_have_no_training_source():
|
||||||
|
for domain in ("cacu", "cama"):
|
||||||
|
config = training_config(Domain(domain), "example").model_dump()
|
||||||
|
assert (config["domain"], config["name"]) == (domain, "example")
|
||||||
|
schema = config["json_schema"]
|
||||||
|
assert set(schema["properties"]) == {"as_of", "execution"}
|
||||||
|
assert set(schema["$defs"]) == {"Execution"}
|
||||||
|
assert config["defaults"] == {"execution": {"mode": "sync", "scheduler": None}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_train_validates_the_training_source():
|
||||||
|
with pytest.raises(HTTPException) as rejected:
|
||||||
|
train(Domain.CACU, Training(source={"kind": "site"}))
|
||||||
|
assert rejected.value.status_code == 422
|
||||||
|
assert rejected.value.detail == "cacu models take no training source"
|
||||||
|
|
||||||
|
for source in (
|
||||||
|
{"kind": "folder"},
|
||||||
|
{"kind": "folder", "folder": "../x"},
|
||||||
|
{"kind": "folder", "folder": "hel", "line_hz": 55},
|
||||||
|
{"kind": "site", "folder": "hel"},
|
||||||
|
{"kind": "site", "line_hz": 60},
|
||||||
|
{"kind": "other"},
|
||||||
|
):
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
Training(source=source)
|
||||||
|
assert Training(source={"kind": "site"}).model_dump()["source"] == {"kind": "site"}
|
||||||
|
folder = Training(source={"kind": "folder", "folder": "hel"}).source
|
||||||
|
assert isinstance(folder, FolderTrainingSource)
|
||||||
|
assert folder.line_hz == 50
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"source",
|
||||||
|
[
|
||||||
|
{"kind": "site"},
|
||||||
|
{"kind": "folder", "folder": "hel", "line_hz": 60},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_train_submits_the_selected_source(monkeypatch, source):
|
||||||
|
client = object()
|
||||||
|
|
||||||
|
def submit(actual_client, job, op, config, *, domain):
|
||||||
|
assert actual_client is client
|
||||||
|
assert (job, op, domain) == ("train", "train_models", "tea")
|
||||||
|
assert config["source"] == source
|
||||||
|
return {"run_id": "training"}
|
||||||
|
|
||||||
|
monkeypatch.setattr(models, "submit", submit)
|
||||||
|
assert train(Domain.TEA, Training(source=source), client) == {"run_id": "training"}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from webapi.main import app
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(own_platform, monkeypatch):
|
||||||
|
monkeypatch.setenv("AUTH_ADMIN_EMAIL", "admin@isssteleon.mx")
|
||||||
|
monkeypatch.setenv("AUTH_ADMIN_PASSWORD", "una-clave-larga")
|
||||||
|
with TestClient(app) as c:
|
||||||
|
yield c
|
||||||
|
|
||||||
|
|
||||||
|
def login(client, email, password):
|
||||||
|
return client.post("/auth/login", data={"username": email, "password": password})
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_first_administrator_signs_in_and_adds_a_team(client):
|
||||||
|
assert client.get("/users/me").status_code == 401
|
||||||
|
assert login(client, "admin@isssteleon.mx", "mala").status_code == 400
|
||||||
|
assert login(client, "admin@isssteleon.mx", "una-clave-larga").status_code == 204
|
||||||
|
me = client.get("/users/me").json()
|
||||||
|
assert me["is_superuser"] and me["domains"] == ["cacu", "cama", "tea"]
|
||||||
|
team = {"email": "cacu@isssteleon.mx", "password": "equipo-cacu", "name": "Equipo CaCu",
|
||||||
|
"domains": ["cacu"]} # fmt: skip
|
||||||
|
assert client.post("/users/register", json=team).status_code == 201
|
||||||
|
client.post("/auth/logout")
|
||||||
|
assert login(client, "cacu@isssteleon.mx", "equipo-cacu").status_code == 204
|
||||||
|
assert client.get("/users/me").json()["domains"] == ["cacu"]
|
||||||
|
other = {"email": "x@isssteleon.mx", "password": "otra-clave"}
|
||||||
|
assert client.post("/users/register", json=other).status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_api_answers_without_a_session(client):
|
||||||
|
for path in ("/health", "/domains", "/ingest/schema", "/ingest/sources/types"):
|
||||||
|
assert client.get(path).status_code == 200, path
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_restart_keeps_the_administrator_once_and_the_session_secret(client, own_platform):
|
||||||
|
assert login(client, "admin@isssteleon.mx", "una-clave-larga").status_code == 204
|
||||||
|
secret = (own_platform / "auth_secret").read_text()
|
||||||
|
with TestClient(app):
|
||||||
|
pass
|
||||||
|
assert (own_platform / "auth_secret").read_text() == secret
|
||||||
|
assert client.get("/users/me").status_code == 200
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import socket
|
||||||
|
import sqlite3
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
from contextlib import closing, contextmanager
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from models.tea.jobs import ASSOCIATION, MODELS
|
||||||
|
from synthetic import tea
|
||||||
|
|
||||||
|
ROOT = Path(__file__).parents[2]
|
||||||
|
FIXTURES = ROOT / "tests" / "fixtures"
|
||||||
|
|
||||||
|
|
||||||
|
def _ok(response: httpx.Response):
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
|
def _port() -> int:
|
||||||
|
with socket.socket() as s:
|
||||||
|
s.bind(("127.0.0.1", 0))
|
||||||
|
return s.getsockname()[1]
|
||||||
|
|
||||||
|
|
||||||
|
def _until_up(url: str, process: subprocess.Popen, seconds: int = 180) -> None:
|
||||||
|
deadline = time.monotonic() + seconds
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
assert process.poll() is None, f"{process.args[0]} exited with {process.returncode}"
|
||||||
|
try:
|
||||||
|
if httpx.get(url, timeout=2).status_code == 200:
|
||||||
|
return
|
||||||
|
except httpx.TransportError:
|
||||||
|
pass
|
||||||
|
time.sleep(1)
|
||||||
|
raise TimeoutError(url)
|
||||||
|
|
||||||
|
|
||||||
|
def _wait(api: httpx.Client, run_id: str, seconds: int = 1800) -> None:
|
||||||
|
deadline = time.monotonic() + seconds
|
||||||
|
while (run := _ok(api.get(f"/runs/{run_id}")))["state"] not in ("succeeded", "failed"):
|
||||||
|
assert time.monotonic() < deadline, f"run {run_id} still {run['state']}"
|
||||||
|
time.sleep(2)
|
||||||
|
assert run["state"] == "succeeded", run.get("error")
|
||||||
|
|
||||||
|
|
||||||
|
def _sensor_run(api: httpx.Client, seconds: int = 300) -> str:
|
||||||
|
deadline = time.monotonic() + seconds
|
||||||
|
while not (runs := _ok(api.get("/runs", params={"job": "tea_eeg", "domain": "tea"}))):
|
||||||
|
assert time.monotonic() < deadline, "the sensor started no tea_eeg run"
|
||||||
|
time.sleep(2)
|
||||||
|
return runs[0]["id"]
|
||||||
|
|
||||||
|
|
||||||
|
def _train_tea(api: httpx.Client) -> None:
|
||||||
|
_wait(api, _ok(api.post("/models/tea/analyze", json={}))["run_id"])
|
||||||
|
for names in (list(MODELS), [ASSOCIATION]):
|
||||||
|
training = _ok(
|
||||||
|
api.post(
|
||||||
|
"/models/tea/train",
|
||||||
|
json={
|
||||||
|
"models": names,
|
||||||
|
"source": {"kind": "site"},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
_wait(api, training["run_id"])
|
||||||
|
for name in names:
|
||||||
|
versions = f"/models/tea/{name}/versions"
|
||||||
|
version = _ok(api.get(versions))[-1]["version"]
|
||||||
|
path = f"{versions}/{version}"
|
||||||
|
_ok(
|
||||||
|
api.post(
|
||||||
|
f"{path}/reports/clinical_validation",
|
||||||
|
files={
|
||||||
|
"file": ("synthetic-validation.txt", b"Synthetic hospital test fixture")
|
||||||
|
},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
_ok(api.post(f"{path}/promote"))
|
||||||
|
assert any(
|
||||||
|
v["version"] == version and v["status"] == "champion"
|
||||||
|
for v in _ok(api.get(versions))
|
||||||
|
), name
|
||||||
|
_wait(api, _ok(api.post("/models/tea/score"))["run_id"])
|
||||||
|
risks = _ok(
|
||||||
|
api.get(
|
||||||
|
"/tea/fhir/Patient", params={"_revinclude": "RiskAssessment:subject", "_count": 200}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assert any(e["resource"]["resourceType"] == "RiskAssessment" for e in risks["entry"])
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _platform(data: Path):
|
||||||
|
from mlflow.store.tracking.sqlalchemy_store import SqlAlchemyStore
|
||||||
|
|
||||||
|
(data / "dagster").mkdir(parents=True)
|
||||||
|
(data / "reference").mkdir()
|
||||||
|
shutil.copy(ROOT / "dagster.yaml", data / "dagster")
|
||||||
|
tracking = f"sqlite:///{data / 'mlflow.db'}"
|
||||||
|
SqlAlchemyStore(tracking, (data / "mlflow").as_uri()).engine.dispose()
|
||||||
|
dagster_port, api_port = _port(), _port()
|
||||||
|
env = {
|
||||||
|
**os.environ,
|
||||||
|
"ISSSTELEON_DATA": str(data),
|
||||||
|
"DLT_DATA_DIR": str(data / "dlt"),
|
||||||
|
"DAGSTER_HOME": str(data / "dagster"),
|
||||||
|
"DAGSTER_HOST": "127.0.0.1",
|
||||||
|
"DAGSTER_PORT": str(dagster_port),
|
||||||
|
"MLFLOW_TRACKING_URI": tracking,
|
||||||
|
"MLFLOW_DISABLE_AGENT_HINT": "1",
|
||||||
|
"EXECUTION_MODE": "sync",
|
||||||
|
"TEA_REFERENCE_ROOT": str(data / "reference"),
|
||||||
|
"AUTH_ADMIN_EMAIL": "admin@isssteleon.mx",
|
||||||
|
"AUTH_ADMIN_PASSWORD": "solo-para-pruebas",
|
||||||
|
}
|
||||||
|
webserver = subprocess.Popen(
|
||||||
|
["dagster-webserver", "-m", "models.definitions", "-h", "127.0.0.1",
|
||||||
|
"-p", str(dagster_port)], env=env, cwd=data,
|
||||||
|
) # fmt: skip
|
||||||
|
server = subprocess.Popen(
|
||||||
|
["fastapi", "run", str(ROOT / "WebApi" / "webapi" / "main.py"), "--host", "127.0.0.1",
|
||||||
|
"--port", str(api_port)], env=env, cwd=data,
|
||||||
|
) # fmt: skip
|
||||||
|
daemon = None
|
||||||
|
try:
|
||||||
|
_until_up(f"http://127.0.0.1:{dagster_port}/server_info", webserver)
|
||||||
|
daemon = subprocess.Popen(
|
||||||
|
["dagster-daemon", "run", "-m", "models.definitions"], env=env, cwd=data
|
||||||
|
)
|
||||||
|
_until_up(f"http://127.0.0.1:{api_port}/health", server)
|
||||||
|
with httpx.Client(base_url=f"http://127.0.0.1:{api_port}", timeout=120) as client:
|
||||||
|
yield client
|
||||||
|
finally:
|
||||||
|
for process in (server, daemon, webserver):
|
||||||
|
if process is not None:
|
||||||
|
process.terminate()
|
||||||
|
process.wait(timeout=30)
|
||||||
|
|
||||||
|
|
||||||
|
def _study_files(db: Path, out: Path) -> dict[str, str]:
|
||||||
|
out.mkdir()
|
||||||
|
with closing(sqlite3.connect(db)) as con:
|
||||||
|
edf, report, birth = con.execute(
|
||||||
|
"SELECT eeg_estudio, ord_pdf_blob, pac_fecha_nacimiento FROM eeg "
|
||||||
|
"JOIN pacientes ON pac_id = eeg_pac_id "
|
||||||
|
"JOIN ados2 ON ado_pac_id = eeg_pac_id "
|
||||||
|
"JOIN ordenes_estudio ON ord_id = ado_ord_id ORDER BY eeg_id LIMIT 1"
|
||||||
|
).fetchone()
|
||||||
|
(out / "study.edf").write_bytes(edf)
|
||||||
|
(out / "ados2.pdf").write_bytes(report)
|
||||||
|
return {
|
||||||
|
"TEA_EDF": str(out / "study.edf"),
|
||||||
|
"TEA_ADOS2": str(out / "ados2.pdf"),
|
||||||
|
"TEA_BIRTH": birth,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.webapp
|
||||||
|
def test_the_tea_pages_load_from_the_synthetic_hospital(tmp_path):
|
||||||
|
hospital = tmp_path / "hospital"
|
||||||
|
hospital.mkdir()
|
||||||
|
tea.build(hospital / "hospital_tea.db")
|
||||||
|
files = _study_files(hospital / "hospital_tea.db", tmp_path / "files")
|
||||||
|
concept_map = json.loads((FIXTURES / "concept_maps" / "hospital_tea.json").read_text())
|
||||||
|
drawn = (FIXTURES / "pipelines" / "hospital_tea.json").read_text()
|
||||||
|
pipeline = json.loads(drawn.replace("{hospital}", str(hospital)))
|
||||||
|
with _platform(tmp_path / "platform") as api:
|
||||||
|
_ok(api.put("/ingest/concept-maps/hospital_tea", json=concept_map))
|
||||||
|
_ok(api.put("/ingest/pipelines/tea", json=pipeline))
|
||||||
|
_wait(api, _ok(api.post("/ingest/pipelines/tea/runs", json={}))["run_id"])
|
||||||
|
_wait(api, _sensor_run(api))
|
||||||
|
_train_tea(api)
|
||||||
|
subprocess.run(
|
||||||
|
["npx", "playwright", "test"], cwd=ROOT / "WebApp", check=True,
|
||||||
|
env={**os.environ, **files, "API_URL": str(api.base_url).rstrip("/")},
|
||||||
|
) # fmt: skip
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
import os
|
|
||||||
|
|
||||||
from flask import Flask, request
|
|
||||||
|
|
||||||
from webapi.blueprints.cacu import cacu_bp
|
|
||||||
from webapi.blueprints.cama import cama_bp
|
|
||||||
from webapi.blueprints.tea import tea_bp
|
|
||||||
|
|
||||||
|
|
||||||
def parse_auth_lite_enabled(value: str | None) -> bool:
|
|
||||||
if value is None or value == "false":
|
|
||||||
return False
|
|
||||||
if value == "true":
|
|
||||||
return True
|
|
||||||
raise ValueError("AUTH_LITE_ENABLED must be exactly 'true' or 'false'")
|
|
||||||
|
|
||||||
|
|
||||||
def create_app() -> Flask:
|
|
||||||
app = Flask(__name__)
|
|
||||||
|
|
||||||
@app.get("/health")
|
|
||||||
def health():
|
|
||||||
return {"status": "ok"}
|
|
||||||
|
|
||||||
app.register_blueprint(cacu_bp, url_prefix="/cacu")
|
|
||||||
app.register_blueprint(cama_bp, url_prefix="/cama")
|
|
||||||
app.register_blueprint(tea_bp, url_prefix="/tea")
|
|
||||||
|
|
||||||
if parse_auth_lite_enabled(os.environ.get("AUTH_LITE_ENABLED")):
|
|
||||||
from webapi.auth_token import validate_auth_storage
|
|
||||||
from webapi.blueprints.auth import auth_bp
|
|
||||||
|
|
||||||
secret = os.environ.get("AUTH_LITE_SECRET_KEY")
|
|
||||||
if not secret or not secret.strip():
|
|
||||||
raise ValueError("AUTH_LITE_SECRET_KEY is required when Auth-Lite is enabled")
|
|
||||||
validate_auth_storage()
|
|
||||||
app.config["AUTH_LITE_SECRET_KEY"] = secret
|
|
||||||
app.register_blueprint(auth_bp, url_prefix="/auth")
|
|
||||||
|
|
||||||
@app.after_request
|
|
||||||
def auth_no_store(response):
|
|
||||||
if request.path == "/auth" or request.path.startswith("/auth/"):
|
|
||||||
response.headers["Cache-Control"] = "no-store"
|
|
||||||
return response
|
|
||||||
|
|
||||||
return app
|
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Caller:
|
||||||
|
id: str = "anonymous"
|
||||||
|
|
||||||
|
|
||||||
|
def caller() -> Caller:
|
||||||
|
return Caller()
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
"""Explicit interactive account bootstrap; never accepts a password argument."""
|
|
||||||
import argparse
|
|
||||||
from getpass import getpass
|
|
||||||
|
|
||||||
from sqlalchemy import delete
|
|
||||||
from sqlmodel import select
|
|
||||||
from werkzeug.security import generate_password_hash
|
|
||||||
|
|
||||||
from core.auth.models import User, UserRole
|
|
||||||
from persistance.db import get_auth_engine, get_auth_session
|
|
||||||
from webapi.auth_token import normalize_username, validate_auth_storage, validate_password
|
|
||||||
|
|
||||||
ALLOWED_ROLES = {"ADMIN", "CACU", "CAMA", "TEA"}
|
|
||||||
|
|
||||||
|
|
||||||
def bootstrap(username: str, roles: list[str], password: str, update: bool = False) -> int:
|
|
||||||
username = normalize_username(username)
|
|
||||||
validate_password(password, minimum=8)
|
|
||||||
if not roles or any(role not in ALLOWED_ROLES for role in roles):
|
|
||||||
raise ValueError("at least one role from ADMIN/CACU/CAMA/TEA is required")
|
|
||||||
validate_auth_storage()
|
|
||||||
with get_auth_session() as session:
|
|
||||||
with session.begin():
|
|
||||||
user = session.exec(select(User).where(User.username == username)).first()
|
|
||||||
if user is not None and not update:
|
|
||||||
raise ValueError("user already exists; use --update explicitly")
|
|
||||||
password_hash = generate_password_hash(password, method="scrypt")
|
|
||||||
if user is None:
|
|
||||||
user = User(username=username, password_hash=password_hash)
|
|
||||||
session.add(user)
|
|
||||||
session.flush()
|
|
||||||
else:
|
|
||||||
user.password_hash = password_hash
|
|
||||||
session.add(user)
|
|
||||||
session.exec(delete(UserRole).where(UserRole.user_id == user.id))
|
|
||||||
for role in sorted(set(roles)):
|
|
||||||
session.add(UserRole(user_id=user.id, role_code=role))
|
|
||||||
user_id = user.id
|
|
||||||
return user_id
|
|
||||||
|
|
||||||
|
|
||||||
def main(argv: list[str] | None = None) -> int:
|
|
||||||
parser = argparse.ArgumentParser(description="Bootstrap an Auth-Lite account interactively")
|
|
||||||
parser.add_argument("--username", required=True)
|
|
||||||
parser.add_argument("--roles", nargs="+", required=True, choices=sorted(ALLOWED_ROLES))
|
|
||||||
parser.add_argument("--update", action="store_true")
|
|
||||||
args = parser.parse_args(argv)
|
|
||||||
try:
|
|
||||||
username = normalize_username(args.username)
|
|
||||||
validate_auth_storage()
|
|
||||||
bootstrap(username, args.roles, getpass("Password: "), update=args.update)
|
|
||||||
print("Auth-Lite account saved.")
|
|
||||||
return 0
|
|
||||||
except ValueError as error:
|
|
||||||
print(str(error))
|
|
||||||
return 1
|
|
||||||
except Exception:
|
|
||||||
print("Auth-Lite bootstrap failed; transaction rolled back.")
|
|
||||||
return 1
|
|
||||||
finally:
|
|
||||||
if get_auth_engine.cache_info().currsize:
|
|
||||||
get_auth_engine().dispose()
|
|
||||||
get_auth_engine.cache_clear()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
raise SystemExit(main())
|
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
"""Explicit, transactional demo account provisioning; never suitable for production."""
|
|
||||||
import argparse
|
|
||||||
import os
|
|
||||||
|
|
||||||
from sqlalchemy import delete
|
|
||||||
from sqlmodel import select
|
|
||||||
from werkzeug.security import generate_password_hash
|
|
||||||
|
|
||||||
from core.auth.models import Role, User, UserRole
|
|
||||||
from persistance.db import get_auth_engine, get_auth_session
|
|
||||||
from webapi import parse_auth_lite_enabled
|
|
||||||
from webapi.auth_bootstrap import ALLOWED_ROLES
|
|
||||||
from webapi.auth_token import normalize_username, validate_auth_storage, validate_password
|
|
||||||
|
|
||||||
# DEMO-ONLY credentials. These credentials are intentionally simple and public
|
|
||||||
# for demonstrations. Do not enable the demo seed in production.
|
|
||||||
DEMO_USERS = (
|
|
||||||
{"username": "admin", "password": "Admin1234", "roles": ("ADMIN",)},
|
|
||||||
{"username": "cacu", "password": "Cacu1234", "roles": ("CACU",)},
|
|
||||||
{"username": "cama", "password": "Cama1234", "roles": ("CAMA",)},
|
|
||||||
{"username": "tea", "password": "Tea12345", "roles": ("TEA",)},
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def validate_demo_users():
|
|
||||||
"""Validate the entire editable definition, including skipped accounts."""
|
|
||||||
validated = []
|
|
||||||
usernames = set()
|
|
||||||
if not DEMO_USERS:
|
|
||||||
raise ValueError("demo configuration must contain accounts")
|
|
||||||
for entry in DEMO_USERS:
|
|
||||||
if not isinstance(entry, dict) or set(entry) != {"username", "password", "roles"}:
|
|
||||||
raise ValueError("invalid demo account definition")
|
|
||||||
username = normalize_username(entry["username"])
|
|
||||||
password = validate_password(entry["password"], minimum=8)
|
|
||||||
roles = entry["roles"]
|
|
||||||
if (not isinstance(roles, (tuple, list)) or not roles
|
|
||||||
or any(not isinstance(role, str) or role not in ALLOWED_ROLES for role in roles)
|
|
||||||
or len(set(roles)) != len(roles)):
|
|
||||||
raise ValueError("demo roles must be unique and from ADMIN/CACU/CAMA/TEA")
|
|
||||||
if username in usernames:
|
|
||||||
raise ValueError("duplicate normalized demo username")
|
|
||||||
usernames.add(username)
|
|
||||||
validated.append({"username": username, "password": password, "roles": tuple(roles)})
|
|
||||||
return validated
|
|
||||||
|
|
||||||
|
|
||||||
def seed_demo_users(*, replace_all: bool = False):
|
|
||||||
"""Complete missing accounts, or replace all, in one transaction.
|
|
||||||
|
|
||||||
The explicit CLI requires Auth enabled. The internal function is also usable
|
|
||||||
with migrated temporary storage in tests; it never creates/migrates storage.
|
|
||||||
"""
|
|
||||||
accounts = validate_demo_users()
|
|
||||||
validate_auth_storage()
|
|
||||||
results = []
|
|
||||||
with get_auth_session() as session:
|
|
||||||
with session.begin():
|
|
||||||
required = {role for account in accounts for role in account["roles"]}
|
|
||||||
if not required <= set(session.exec(select(Role.code))):
|
|
||||||
raise ValueError("required demo roles are missing; apply Auth migration first")
|
|
||||||
existing = set(session.exec(select(User.username)))
|
|
||||||
missing = accounts if replace_all else [a for a in accounts if a["username"] not in existing]
|
|
||||||
# Hash every new password before any delete/insert. No plaintext enters DB.
|
|
||||||
hashes = {a["username"]: generate_password_hash(a["password"], method="scrypt") for a in missing}
|
|
||||||
if replace_all:
|
|
||||||
session.exec(delete(User)) # FK ON DELETE CASCADE clears user_role.
|
|
||||||
for account in accounts:
|
|
||||||
username, roles = account["username"], account["roles"]
|
|
||||||
if username not in hashes:
|
|
||||||
results.append((username, roles, "skipped"))
|
|
||||||
continue
|
|
||||||
user = User(username=username, password_hash=hashes[username])
|
|
||||||
session.add(user)
|
|
||||||
session.flush()
|
|
||||||
for role in roles:
|
|
||||||
session.add(UserRole(user_id=user.id, role_code=role))
|
|
||||||
results.append((username, roles, "created"))
|
|
||||||
return results
|
|
||||||
|
|
||||||
|
|
||||||
def main(argv: list[str] | None = None) -> int:
|
|
||||||
parser = argparse.ArgumentParser(description="DEMO ONLY: provision public Auth-Lite accounts")
|
|
||||||
modes = parser.add_mutually_exclusive_group(required=True)
|
|
||||||
modes.add_argument("--ensure", action="store_true", help="create only missing usernames")
|
|
||||||
modes.add_argument("--replace-all", action="store_true", help="delete EVERY Auth user; requires REPLACE")
|
|
||||||
args = parser.parse_args(argv)
|
|
||||||
try:
|
|
||||||
if not parse_auth_lite_enabled(os.environ.get("AUTH_LITE_ENABLED")):
|
|
||||||
print("Auth-Lite is disabled; demo seed skipped.")
|
|
||||||
return 0
|
|
||||||
if args.replace_all:
|
|
||||||
print("WARNING: this will delete every Auth-Lite user.")
|
|
||||||
try:
|
|
||||||
confirmation = input("Type REPLACE to continue: ")
|
|
||||||
except EOFError:
|
|
||||||
confirmation = ""
|
|
||||||
if confirmation != "REPLACE":
|
|
||||||
print("Auth-Lite demo replacement cancelled; no changes.")
|
|
||||||
return 0
|
|
||||||
results = seed_demo_users(replace_all=args.replace_all)
|
|
||||||
print("Auth-Lite demo users replaced." if args.replace_all else "Auth-Lite demo seed:")
|
|
||||||
for username, roles, status in results:
|
|
||||||
print(f"{username} [{','.join(roles)}] -> {status}")
|
|
||||||
return 0
|
|
||||||
except Exception:
|
|
||||||
# Editable configuration and DB exceptions may include sensitive values.
|
|
||||||
print("Auth-Lite demo seed failed; transaction rolled back. Check configuration and migrated storage.")
|
|
||||||
return 1
|
|
||||||
finally:
|
|
||||||
if get_auth_engine.cache_info().currsize:
|
|
||||||
get_auth_engine().dispose()
|
|
||||||
get_auth_engine.cache_clear()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
raise SystemExit(main())
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
"""Auth-Lite token, input and explicit storage validation helpers."""
|
|
||||||
from pathlib import Path
|
|
||||||
import re
|
|
||||||
|
|
||||||
from itsdangerous import BadData, URLSafeTimedSerializer
|
|
||||||
from sqlalchemy import inspect
|
|
||||||
from sqlalchemy.engine import make_url
|
|
||||||
|
|
||||||
TOKEN_MAX_AGE = 28800
|
|
||||||
TOKEN_SALT = "auth-lite-session-v1"
|
|
||||||
|
|
||||||
|
|
||||||
def normalize_username(value: str) -> str:
|
|
||||||
if not isinstance(value, str):
|
|
||||||
raise ValueError("username must be a string")
|
|
||||||
value = value.strip().lower()
|
|
||||||
if not re.fullmatch(r"[a-z0-9._-]{3,64}", value):
|
|
||||||
raise ValueError("username must contain 3-64 characters from [a-z0-9._-]")
|
|
||||||
return value
|
|
||||||
|
|
||||||
|
|
||||||
def validate_password(value: str, minimum: int = 1) -> str:
|
|
||||||
if not isinstance(value, str) or not minimum <= len(value) <= 128:
|
|
||||||
raise ValueError(f"password must contain {minimum}-128 characters")
|
|
||||||
return value
|
|
||||||
|
|
||||||
|
|
||||||
def validate_auth_storage() -> None:
|
|
||||||
from persistance.db import get_auth_engine
|
|
||||||
from persistance.settings import settings
|
|
||||||
|
|
||||||
try:
|
|
||||||
url = make_url(settings.auth_database_url)
|
|
||||||
if url.get_backend_name() != "sqlite":
|
|
||||||
raise ValueError("SQLite required")
|
|
||||||
if not url.database or url.database == ":memory:" or not Path(url.database).is_file():
|
|
||||||
raise ValueError("existing SQLite required")
|
|
||||||
engine = get_auth_engine()
|
|
||||||
if not {"user", "role", "user_role", "alembic_version"} <= set(inspect(engine).get_table_names()):
|
|
||||||
raise ValueError("migration required")
|
|
||||||
# Validate the columns needed by login/bootstrap, without creating schema.
|
|
||||||
from sqlalchemy import text
|
|
||||||
with engine.connect() as connection:
|
|
||||||
connection.execute(text("SELECT id, username, password_hash, activo FROM user LIMIT 0"))
|
|
||||||
connection.execute(text("SELECT code FROM role LIMIT 0"))
|
|
||||||
connection.execute(text("SELECT user_id, role_code FROM user_role LIMIT 0"))
|
|
||||||
except Exception:
|
|
||||||
if get_auth_engine.cache_info().currsize:
|
|
||||||
get_auth_engine().dispose()
|
|
||||||
get_auth_engine.cache_clear()
|
|
||||||
raise ValueError("Auth-Lite storage must be an accessible migrated SQLite database") from None
|
|
||||||
|
|
||||||
|
|
||||||
def serializer(secret: str) -> URLSafeTimedSerializer:
|
|
||||||
return URLSafeTimedSerializer(secret, salt=TOKEN_SALT)
|
|
||||||
|
|
||||||
|
|
||||||
def issue_token(secret: str, user_id: int) -> str:
|
|
||||||
return serializer(secret).dumps({"user_id": user_id, "v": 1})
|
|
||||||
|
|
||||||
|
|
||||||
def read_token(secret: str, token: str) -> int | None:
|
|
||||||
try:
|
|
||||||
payload = serializer(secret).loads(token, max_age=TOKEN_MAX_AGE)
|
|
||||||
except BadData:
|
|
||||||
return None
|
|
||||||
if not isinstance(payload, dict) or set(payload) != {"user_id", "v"}:
|
|
||||||
return None
|
|
||||||
if type(payload["v"]) is not int or payload["v"] != 1:
|
|
||||||
return None
|
|
||||||
user_id = payload["user_id"]
|
|
||||||
return user_id if type(user_id) is int and 0 < user_id <= 9223372036854775807 else None
|
|
||||||
|
|
||||||
|
|
||||||
def user_dto(user, roles: list[str]) -> dict:
|
|
||||||
return {"id": user.id, "username": user.username, "roles": sorted(roles)}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
from flask import Blueprint, current_app, request
|
|
||||||
from werkzeug.security import check_password_hash
|
|
||||||
|
|
||||||
from persistance.auth.repository import get_user_by_username, get_user_with_roles_by_id
|
|
||||||
from webapi.auth_token import (
|
|
||||||
TOKEN_MAX_AGE, issue_token, normalize_username, read_token, user_dto, validate_password,
|
|
||||||
)
|
|
||||||
|
|
||||||
auth_bp = Blueprint("auth", __name__)
|
|
||||||
|
|
||||||
|
|
||||||
@auth_bp.post("/login")
|
|
||||||
def login():
|
|
||||||
body = request.get_json(silent=True)
|
|
||||||
try:
|
|
||||||
if not isinstance(body, dict):
|
|
||||||
raise ValueError("JSON object required")
|
|
||||||
username = normalize_username(body.get("username"))
|
|
||||||
password = validate_password(body.get("password"))
|
|
||||||
except ValueError:
|
|
||||||
return {"error": "invalid_request"}, 400
|
|
||||||
user = get_user_by_username(username)
|
|
||||||
if user is None or not user.activo or not check_password_hash(user.password_hash, password):
|
|
||||||
return {"error": "invalid_credentials"}, 401
|
|
||||||
identity = get_user_with_roles_by_id(user.id)
|
|
||||||
if identity is None or not identity[0].activo:
|
|
||||||
return {"error": "invalid_credentials"}, 401
|
|
||||||
return {
|
|
||||||
"token": issue_token(current_app.config["AUTH_LITE_SECRET_KEY"], user.id),
|
|
||||||
"expires_in": TOKEN_MAX_AGE,
|
|
||||||
"user": user_dto(*identity),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@auth_bp.get("/me")
|
|
||||||
def me():
|
|
||||||
parts = request.headers.get("Authorization", "").split()
|
|
||||||
if len(parts) != 2 or parts[0].lower() != "bearer":
|
|
||||||
return {"error": "unauthorized"}, 401
|
|
||||||
user_id = read_token(current_app.config["AUTH_LITE_SECRET_KEY"], parts[1])
|
|
||||||
identity = get_user_with_roles_by_id(user_id) if user_id is not None else None
|
|
||||||
if identity is None or not identity[0].activo:
|
|
||||||
return {"error": "unauthorized"}, 401
|
|
||||||
return {"user": user_dto(*identity)}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
from flask import Blueprint, jsonify
|
|
||||||
|
|
||||||
from models.cacu import CaCuModel
|
|
||||||
from persistance.cacu import paciente_repository
|
|
||||||
|
|
||||||
cacu_bp = Blueprint("cacu", __name__)
|
|
||||||
|
|
||||||
|
|
||||||
@cacu_bp.get("/pacientes/<int:pac_id>")
|
|
||||||
def get_paciente(pac_id: int):
|
|
||||||
"""Example read route — proves WebApi resolves Persistance's repository API."""
|
|
||||||
paciente = paciente_repository.get(pac_id)
|
|
||||||
if paciente is None:
|
|
||||||
return jsonify({"error": "not found"}), 404
|
|
||||||
return jsonify(paciente.model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@cacu_bp.post("/predict")
|
|
||||||
def predict():
|
|
||||||
"""Example predict route — proves WebApi resolves the models package."""
|
|
||||||
model = CaCuModel()
|
|
||||||
try:
|
|
||||||
return jsonify({"prediction": model.predict(data=None)})
|
|
||||||
except NotImplementedError as exc:
|
|
||||||
return jsonify({"error": str(exc)}), 501
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
from flask import Blueprint, jsonify
|
|
||||||
|
|
||||||
from models.cama import CaMaModel
|
|
||||||
from persistance.cama import paciente_repository
|
|
||||||
|
|
||||||
cama_bp = Blueprint("cama", __name__)
|
|
||||||
|
|
||||||
|
|
||||||
@cama_bp.get("/pacientes/<int:pac_id>")
|
|
||||||
def get_paciente(pac_id: int):
|
|
||||||
paciente = paciente_repository.get(pac_id)
|
|
||||||
if paciente is None:
|
|
||||||
return jsonify({"error": "not found"}), 404
|
|
||||||
return jsonify(paciente.model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@cama_bp.post("/predict")
|
|
||||||
def predict():
|
|
||||||
model = CaMaModel()
|
|
||||||
try:
|
|
||||||
return jsonify({"prediction": model.predict(data=None)})
|
|
||||||
except NotImplementedError as exc:
|
|
||||||
return jsonify({"error": str(exc)}), 501
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
from flask import Blueprint, jsonify
|
|
||||||
|
|
||||||
from models.tea import TeaModel
|
|
||||||
from persistance.tea import pacientes_repository
|
|
||||||
|
|
||||||
tea_bp = Blueprint("tea", __name__)
|
|
||||||
|
|
||||||
|
|
||||||
@tea_bp.get("/pacientes/<string:pac_id>")
|
|
||||||
def get_paciente(pac_id: str):
|
|
||||||
paciente = pacientes_repository.get(pac_id)
|
|
||||||
if paciente is None:
|
|
||||||
return jsonify({"error": "not found"}), 404
|
|
||||||
return jsonify(paciente.model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@tea_bp.post("/predict")
|
|
||||||
def predict():
|
|
||||||
model = TeaModel()
|
|
||||||
try:
|
|
||||||
return jsonify({"prediction": model.predict(data=None)})
|
|
||||||
except NotImplementedError as exc:
|
|
||||||
return jsonify({"error": str(exc)}), 501
|
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from persistance import eeg
|
||||||
|
from persistance.cluster import Execution
|
||||||
|
from persistance.eeg import Scope
|
||||||
|
from webapi.runs import dagster, execution_config, submit
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/tea/eegs", tags=["eeg"])
|
||||||
|
|
||||||
|
|
||||||
|
class Study(BaseModel):
|
||||||
|
id: str
|
||||||
|
person_id: str
|
||||||
|
study_date: str
|
||||||
|
lab_record_id: str | None
|
||||||
|
analysed: bool
|
||||||
|
valid: bool | None
|
||||||
|
level: str | None
|
||||||
|
|
||||||
|
|
||||||
|
class Metric(BaseModel):
|
||||||
|
code: str
|
||||||
|
value: float
|
||||||
|
z: float | None
|
||||||
|
outside: float | None
|
||||||
|
model: str | None
|
||||||
|
|
||||||
|
|
||||||
|
class Analysis(BaseModel):
|
||||||
|
id: str
|
||||||
|
valid: bool | None
|
||||||
|
level: str | None
|
||||||
|
age_months: float | None
|
||||||
|
metrics: list[Metric]
|
||||||
|
checks: list[dict[str, Any]]
|
||||||
|
regions: list[dict[str, Any]]
|
||||||
|
|
||||||
|
|
||||||
|
class AnalyzeRequest(BaseModel):
|
||||||
|
scope: Scope = Scope()
|
||||||
|
execution: Execution | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def studies() -> list[Study]:
|
||||||
|
return [Study(**s) for s in eeg.studies()]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/analyze",
|
||||||
|
description="Starts `tea_eeg`: analyse the EEGs in scope, score the curves, rebuild gold.",
|
||||||
|
)
|
||||||
|
def analyze_eegs(request: AnalyzeRequest, client=Depends(dagster)) -> dict[str, str]:
|
||||||
|
config = {"scope": request.scope.model_dump(), "execution": execution_config(request.execution)}
|
||||||
|
return submit(client, "tea_eeg", "tea_analyze_studies", config, domain="tea")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/summary")
|
||||||
|
def eeg_studies_summary() -> dict[str, int]:
|
||||||
|
return eeg.summary()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{eeg_id}")
|
||||||
|
def study(eeg_id: str) -> Analysis:
|
||||||
|
if (found := eeg.study(eeg_id)) is None:
|
||||||
|
raise HTTPException(404, detail=f"no analysed EEG {eeg_id}")
|
||||||
|
return Analysis(**found)
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
from fastapi import APIRouter, HTTPException
|
||||||
|
|
||||||
|
from persistance import cluster
|
||||||
|
from persistance.cluster import Execution, Health, Mode, Options
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/execution", tags=["execution"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/options")
|
||||||
|
def execution_options() -> Options:
|
||||||
|
return cluster.options()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health")
|
||||||
|
def execution_health(
|
||||||
|
mode: Mode | None = None, scheduler: str | None = None, reference: str | None = None
|
||||||
|
) -> Health:
|
||||||
|
try:
|
||||||
|
return cluster.health(Execution(mode=mode, scheduler=scheduler), reference)
|
||||||
|
except cluster.ExecutionError as e:
|
||||||
|
raise HTTPException(422, detail=str(e)) from e
|
||||||
+716
@@ -0,0 +1,716 @@
|
|||||||
|
import unicodedata
|
||||||
|
from collections import defaultdict
|
||||||
|
from datetime import date, datetime
|
||||||
|
from typing import Annotated, Any
|
||||||
|
from urllib.parse import urlencode
|
||||||
|
|
||||||
|
from dagster_graphql import DagsterGraphQLClient
|
||||||
|
from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request
|
||||||
|
from fastapi.responses import Response
|
||||||
|
from fhir.resources.R4B.bundle import Bundle
|
||||||
|
from fhir.resources.R4B.capabilitystatement import CapabilityStatement
|
||||||
|
from fhir.resources.R4B.operationoutcome import OperationOutcome
|
||||||
|
from fhir.resources.R4B.parameters import Parameters
|
||||||
|
from fhir.resources.R4B.resource import Resource
|
||||||
|
|
||||||
|
from core import catalog
|
||||||
|
from core import fhir as f
|
||||||
|
from core import measures as m
|
||||||
|
from core.domains import Domain, measures, part
|
||||||
|
from core.follow_up import window_start
|
||||||
|
from core.pipeline import ID_PATTERN
|
||||||
|
from core.tea import fhir as tea_fhir
|
||||||
|
from core.tea.follow_up import FILTERS as TEA_FILTERS
|
||||||
|
from persistance import config_log, readers
|
||||||
|
from persistance import fhir as reads
|
||||||
|
from persistance import measures as measure_reads
|
||||||
|
from webapi.ingest import submit
|
||||||
|
from webapi.runs import dagster
|
||||||
|
|
||||||
|
FHIR_JSON = "application/fhir+json"
|
||||||
|
PAGE, MAX_PAGE = 50, 200
|
||||||
|
REVINCLUDES = ("DiagnosticReport:subject", "RiskAssessment:subject", "Observation:subject")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/{domain}/fhir", tags=["fhir"])
|
||||||
|
_OK = {200: {"content": {FHIR_JSON: {"schema": {"type": "object"}}}, "description": "FHIR"}}
|
||||||
|
|
||||||
|
|
||||||
|
def fhir(resource: Resource) -> Response:
|
||||||
|
return Response(resource.model_dump_json(exclude_none=True), media_type=FHIR_JSON)
|
||||||
|
|
||||||
|
|
||||||
|
def outcome(status: int, text: str) -> Response:
|
||||||
|
issue = {"severity": "error", "code": "not-found" if status == 404 else "invalid",
|
||||||
|
"diagnostics": text} # fmt: skip
|
||||||
|
return Response(OperationOutcome(issue=[issue]).model_dump_json(exclude_none=True),
|
||||||
|
status_code=status, media_type=FHIR_JSON) # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def _clinical(domain: Domain):
|
||||||
|
if (found := part(domain, "follow_up")) is None:
|
||||||
|
raise HTTPException(404, f"no clinical resources for {domain.value} yet")
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _cutoff(domain: Domain, asked: date | None) -> date:
|
||||||
|
if asked is not None:
|
||||||
|
return asked
|
||||||
|
return reads.last_data_day(domain.value) or date.today()
|
||||||
|
|
||||||
|
|
||||||
|
def _page(count: int | None, offset: int) -> tuple[int, int]:
|
||||||
|
count = PAGE if count is None else count
|
||||||
|
if not 0 <= count <= MAX_PAGE or offset < 0:
|
||||||
|
raise HTTPException(422, f"_count goes from 0 to {MAX_PAGE}; _offset from 0")
|
||||||
|
return count, offset
|
||||||
|
|
||||||
|
|
||||||
|
def bundle(request: Request, matches: list[Resource], total: int, count: int, offset: int,
|
||||||
|
included: list[Resource] = (), applied: dict | None = None) -> Response: # fmt: skip
|
||||||
|
base = str(request.base_url).rstrip("/") + request.url.path.rsplit("/", 1)[0]
|
||||||
|
|
||||||
|
def link(relation: str, at: int) -> dict:
|
||||||
|
params = {**(applied or {}), "_offset": at, "_count": count}
|
||||||
|
query = [(k, v) for k, v in request.query_params.multi_items() if k not in params]
|
||||||
|
url = request.url.replace(query=urlencode([*query, *params.items()], doseq=True))
|
||||||
|
return {"relation": relation, "url": str(url)}
|
||||||
|
|
||||||
|
links = [link("self", offset)]
|
||||||
|
if offset + count < total:
|
||||||
|
links.append(link("next", offset + count))
|
||||||
|
if offset > 0:
|
||||||
|
links.append(link("previous", max(offset - count, 0)))
|
||||||
|
groups = (("match", matches), ("include", included))
|
||||||
|
entries = [{"fullUrl": f"{base}/{r.get_resource_type()}/{r.id}", "resource": r,
|
||||||
|
"search": {"mode": mode}} for mode, group in groups for r in group] # fmt: skip
|
||||||
|
found = Bundle(type="searchset", total=total, link=links, entry=entries or None)
|
||||||
|
return fhir(found)
|
||||||
|
|
||||||
|
|
||||||
|
def _sliced(found: list, count: int, offset: int) -> list:
|
||||||
|
return found[offset:offset + count] # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
_WINDOW = Query(
|
||||||
|
None,
|
||||||
|
alias="follow-up-window",
|
||||||
|
description="months: the domain's follow-up list over that window up to the cut-off",
|
||||||
|
)
|
||||||
|
_START = Query(
|
||||||
|
None,
|
||||||
|
alias="follow-up-start",
|
||||||
|
description="explicit window start that overrides follow-up-window",
|
||||||
|
)
|
||||||
|
_CUTOFF = Query(None, alias="follow-up-cutoff", description="default: the last day with data")
|
||||||
|
_STATUS = Query(None, alias="follow-up-status")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/Patient/$eeg-summary",
|
||||||
|
responses=_OK,
|
||||||
|
response_class=Response,
|
||||||
|
description="EEG counts for the follow-up list. Without a window or start, "
|
||||||
|
"use the whole history.",
|
||||||
|
)
|
||||||
|
def eeg_summary(
|
||||||
|
request: Request,
|
||||||
|
domain: Domain,
|
||||||
|
window: int | None = _WINDOW,
|
||||||
|
start: date | None = _START,
|
||||||
|
cutoff: date | None = _CUTOFF,
|
||||||
|
status: str | None = _STATUS,
|
||||||
|
) -> Response:
|
||||||
|
fu = _clinical(domain)
|
||||||
|
if not hasattr(fu, "summary"):
|
||||||
|
return outcome(404, f"no EEG summary for {domain.value}")
|
||||||
|
at = _cutoff(domain, cutoff)
|
||||||
|
try:
|
||||||
|
rows, _, _ = _patient_rows(request, domain, fu, at, window, start, cutoff, status,
|
||||||
|
whole_history=True) # fmt: skip
|
||||||
|
except ValueError as exc:
|
||||||
|
return outcome(422, str(exc))
|
||||||
|
counts = fu.summary(rows)
|
||||||
|
parameters = [
|
||||||
|
{"name": name, "valueInteger": counts[name]}
|
||||||
|
for name in ("valid", "not_valid", "normal", "abnormal")
|
||||||
|
]
|
||||||
|
for entry in counts["by_alteration"]:
|
||||||
|
parameters.append({"name": "by_alteration", "part": [
|
||||||
|
{"name": "alteration", "valueCode": entry["alteration"]},
|
||||||
|
{"name": "patients", "valueInteger": entry["patients"]},
|
||||||
|
]}) # fmt: skip
|
||||||
|
return fhir(Parameters(parameter=parameters))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/Patient/{id}", responses=_OK, response_class=Response)
|
||||||
|
def read_patient(domain: Domain, id: str) -> Response:
|
||||||
|
fu = _clinical(domain)
|
||||||
|
(row,) = reads.rows(domain.value, "person", id=id) or [None]
|
||||||
|
if row is None:
|
||||||
|
(link,) = reads.rows(domain.value, "replaced", id=id) or [None]
|
||||||
|
if link is None:
|
||||||
|
raise HTTPException(404, f"no Patient/{id}")
|
||||||
|
return fhir(f.replaced_patient(id, link["replaced_by"]))
|
||||||
|
status = fu.status(row, _cutoff(domain, None))
|
||||||
|
(found,) = _with_identity(domain, [{**row, "status": status}])
|
||||||
|
return fhir(f.patient(found, fu.STATUS_SYSTEM))
|
||||||
|
|
||||||
|
|
||||||
|
def _with_identity(domain: Domain, rows: list[dict]) -> list[dict]:
|
||||||
|
persons = [r["person_id"] for r in rows]
|
||||||
|
names, ids, replaces = {}, {}, {}
|
||||||
|
for r in reads.rows(domain.value, "names", persons=persons):
|
||||||
|
names.setdefault(r["person_id"], []).append(r["text"])
|
||||||
|
for r in reads.rows(domain.value, "identifiers", persons=persons):
|
||||||
|
ids.setdefault(r["person_id"], []).append((r["system"], r["value"]))
|
||||||
|
for r in reads.rows(domain.value, "replaces", persons=persons):
|
||||||
|
replaces.setdefault(r["replaced_by"], []).append(r["person_id"])
|
||||||
|
return [
|
||||||
|
{**r, "names": names.get(p, []), "identifiers": ids.get(p, []),
|
||||||
|
"replaces": replaces.get(p, [])}
|
||||||
|
for r in rows if (p := r["person_id"])
|
||||||
|
] # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def _folded(text: str) -> str:
|
||||||
|
return "".join(c for c in unicodedata.normalize("NFKD", text.casefold())
|
||||||
|
if not unicodedata.combining(c)) # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def _matches(row: dict, name: str | None, identifier: str | None) -> bool:
|
||||||
|
if name:
|
||||||
|
words = _folded(name).split()
|
||||||
|
if not any(all(any(w.startswith(q) for w in _folded(n).split()) for q in words)
|
||||||
|
for n in row["names"]): # fmt: skip
|
||||||
|
return False
|
||||||
|
if identifier:
|
||||||
|
system, _, value = identifier.rpartition("|")
|
||||||
|
if not any((not system or s == system) and v.casefold() == value.strip().casefold()
|
||||||
|
for s, v in row["identifiers"]): # fmt: skip
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/Patient",
|
||||||
|
responses=_OK,
|
||||||
|
response_class=Response,
|
||||||
|
description=(
|
||||||
|
"Patients, or the domain's follow-up list selected by window or start.\n\n"
|
||||||
|
"For TEA, a cutoff or a TEA filter also selects the follow-up list. Patients without\n"
|
||||||
|
"follow-up episodes appear only in the plain search."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def search_patient(
|
||||||
|
request: Request,
|
||||||
|
domain: Domain,
|
||||||
|
_id: str | None = Query(None, alias="_id"),
|
||||||
|
window: int | None = _WINDOW,
|
||||||
|
start: date | None = _START,
|
||||||
|
cutoff: date | None = _CUTOFF,
|
||||||
|
status: str | None = _STATUS,
|
||||||
|
name: str | None = Query(
|
||||||
|
None, description="each word starts a word of her name (case and accents ignored)"
|
||||||
|
),
|
||||||
|
identifier: str | None = Query(
|
||||||
|
None, description="[system|]value: a CURP or record number (case ignored)"
|
||||||
|
),
|
||||||
|
sort: str = Query("-recent", alias="_sort", description="-recent or -risk-<outcome>"),
|
||||||
|
horizon: float | None = Query(None, alias="risk-horizon", description="years"),
|
||||||
|
revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"),
|
||||||
|
include: list[str] = Query([], alias="_include:iterate", description="DiagnosticReport:result"),
|
||||||
|
_count: int | None = Query(None),
|
||||||
|
_offset: int = Query(0),
|
||||||
|
) -> Response:
|
||||||
|
fu = _clinical(domain)
|
||||||
|
count, offset = _page(_count, _offset)
|
||||||
|
at = _cutoff(domain, cutoff)
|
||||||
|
horizon = fu.DEFAULT_HORIZON if horizon is None else horizon
|
||||||
|
try:
|
||||||
|
rows, listed, applied = _patient_rows(
|
||||||
|
request, domain, fu, at, window, start, cutoff, status, sort, _id
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
return outcome(422, str(exc))
|
||||||
|
if name or identifier:
|
||||||
|
found = {r["person_id"] for r in _with_identity(domain, rows)
|
||||||
|
if _matches(r, name, identifier)} # fmt: skip
|
||||||
|
rows = [r for r in rows if r["person_id"] in found]
|
||||||
|
persons = [r["person_id"] for r in rows]
|
||||||
|
risks: dict[str, list[dict]] = {}
|
||||||
|
if domain != Domain.TEA and (listed and sort != "-recent" or
|
||||||
|
"RiskAssessment:subject" in revinclude): # fmt: skip
|
||||||
|
for r in reads.rows(domain.value, "risk", persons=persons):
|
||||||
|
risks.setdefault(r["person_id"], []).append(r)
|
||||||
|
if listed:
|
||||||
|
rows = fu.ordered(rows, sort, risks, horizon)
|
||||||
|
page = _sliced(rows, count, offset)
|
||||||
|
mine = {r["person_id"] for r in page}
|
||||||
|
included = _included(domain, revinclude, include, sorted(mine), at,
|
||||||
|
{p: v for p, v in risks.items() if p in mine}) # fmt: skip
|
||||||
|
patients = [f.patient(r, fu.STATUS_SYSTEM) for r in _with_identity(domain, page)]
|
||||||
|
return bundle(request, patients, len(rows), count, offset, included,
|
||||||
|
applied) # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def _patient_rows(
|
||||||
|
request: Request,
|
||||||
|
domain: Domain,
|
||||||
|
fu,
|
||||||
|
at: date,
|
||||||
|
window: int | None,
|
||||||
|
start: date | None,
|
||||||
|
cutoff: date | None,
|
||||||
|
status: str | None,
|
||||||
|
sort: str = "-recent",
|
||||||
|
_id: str | None = None,
|
||||||
|
*,
|
||||||
|
whole_history: bool = False,
|
||||||
|
) -> tuple[list[dict], bool, dict]:
|
||||||
|
filters = {
|
||||||
|
name: request.query_params.getlist(name)
|
||||||
|
for name in (TEA_FILTERS if domain == Domain.TEA else ())
|
||||||
|
if name in request.query_params
|
||||||
|
}
|
||||||
|
if filters:
|
||||||
|
fu.matches({}, filters)
|
||||||
|
listed = (
|
||||||
|
whole_history
|
||||||
|
or start is not None
|
||||||
|
or window is not None
|
||||||
|
or bool(filters)
|
||||||
|
or (hasattr(fu, "FILTERS") and cutoff is not None)
|
||||||
|
)
|
||||||
|
persons = reads.rows(domain.value, "persons")
|
||||||
|
applied = {}
|
||||||
|
if listed:
|
||||||
|
if sort not in fu.SORTS:
|
||||||
|
raise HTTPException(422, f"_sort is one of {fu.SORTS}")
|
||||||
|
if start is None and window is not None:
|
||||||
|
if window not in fu.WINDOWS:
|
||||||
|
raise HTTPException(422, f"follow-up-window is one of {fu.WINDOWS}")
|
||||||
|
start = window_start(at, window)
|
||||||
|
start = start or date.min
|
||||||
|
params = {"start": start.isoformat(), "cutoff": at.isoformat()}
|
||||||
|
person = {r["person_id"]: r for r in persons}
|
||||||
|
rows = [
|
||||||
|
{**person[r["person_id"]], **r}
|
||||||
|
for r in fu.listed(reads.rows(domain.value, "follow_up", **params), start, at)
|
||||||
|
]
|
||||||
|
applied = {"follow-up-cutoff": at.isoformat(), **filters}
|
||||||
|
else:
|
||||||
|
rows = [{**r, "status": fu.status(r, at)} for r in persons]
|
||||||
|
if _id and (not listed or domain == Domain.TEA):
|
||||||
|
ids = set(_id.split(","))
|
||||||
|
rows = [r for r in rows if r["person_id"] in ids]
|
||||||
|
if status:
|
||||||
|
rows = [r for r in rows if r["status"] in status.split(",")]
|
||||||
|
if filters:
|
||||||
|
rows = [r for r in rows if fu.matches(r, filters)]
|
||||||
|
return rows, listed, applied
|
||||||
|
|
||||||
|
|
||||||
|
def _included(domain: Domain, revinclude: list[str], include: list[str], persons: list[str],
|
||||||
|
at: date, risks: dict[str, list[dict]]) -> list[Resource]: # fmt: skip
|
||||||
|
allowed = _revincludes(domain)
|
||||||
|
unknown = set(revinclude) - set(allowed) | set(include) - {"DiagnosticReport:result"}
|
||||||
|
if unknown:
|
||||||
|
raise HTTPException(422, f"cannot include {sorted(unknown)}")
|
||||||
|
found: list[Resource] = []
|
||||||
|
reports = "DiagnosticReport:subject" in revinclude
|
||||||
|
observations = "Observation:subject" in revinclude or (
|
||||||
|
reports and "DiagnosticReport:result" in include
|
||||||
|
)
|
||||||
|
if reports or observations:
|
||||||
|
for r in _studies(domain, persons, at.isoformat()):
|
||||||
|
kind = r.get_resource_type()
|
||||||
|
if (kind == "DiagnosticReport" and reports) or (kind == "Observation" and observations):
|
||||||
|
found.append(r)
|
||||||
|
if "Condition:subject" in revinclude:
|
||||||
|
found += [f.condition(r) for r in reads.rows(domain.value, "condition", persons=persons,
|
||||||
|
cutoff=at.isoformat())] # fmt: skip
|
||||||
|
if "RiskAssessment:subject" in revinclude:
|
||||||
|
if domain == Domain.TEA:
|
||||||
|
found += _tea_risks(persons, at.isoformat())
|
||||||
|
else:
|
||||||
|
found += _risk_assessments([r for p in persons for r in risks.get(p, [])])
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _revincludes(domain: Domain) -> tuple[str, ...]:
|
||||||
|
return (*REVINCLUDES, "Condition:subject") if domain == Domain.TEA else REVINCLUDES
|
||||||
|
|
||||||
|
|
||||||
|
def _subjects(subject: str | None) -> list[str]:
|
||||||
|
if not subject:
|
||||||
|
raise HTTPException(422, "subject is required (Patient/<id>, comma-separated)")
|
||||||
|
return [s.removeprefix("Patient/") for s in subject.split(",")]
|
||||||
|
|
||||||
|
|
||||||
|
def _studies(domain: Domain, persons: list[str], at: str) -> list[Resource]:
|
||||||
|
found: list[Resource] = []
|
||||||
|
report_facts = _clinical(domain).REPORT_FACTS
|
||||||
|
if domain == Domain.TEA:
|
||||||
|
births = {
|
||||||
|
r["person_id"]: date.fromisoformat(f._day(r["birth_date"])) if r["birth_date"] else None
|
||||||
|
for r in reads.rows(domain.value, "births", persons=persons)
|
||||||
|
}
|
||||||
|
for study in catalog.of_domain(domain.value):
|
||||||
|
spec = catalog.studies()[study]
|
||||||
|
facts = {}
|
||||||
|
if kind := report_facts.get(study):
|
||||||
|
found_facts = reads.rows(domain.value, kind, persons=persons, cutoff=at)
|
||||||
|
facts = {(r["person_id"], str(r["sample_date"])[:10]): r["days"]
|
||||||
|
for r in found_facts} # fmt: skip
|
||||||
|
first = next(e.date for e in spec.events.values() if e.parent is None)
|
||||||
|
for row in reads.instances(study, persons, at):
|
||||||
|
days = facts.get((row["person_id"], str(row[first])[:10]))
|
||||||
|
extra = [] if days is None else [f.ext("days-to-diagnosis", "integer", int(days))]
|
||||||
|
known = f.known(study, row, at)
|
||||||
|
found += f.instance(study, known, extra)
|
||||||
|
if domain == Domain.TEA and study == "ados2":
|
||||||
|
known["evaluation_date"] = date.fromisoformat(f._day(known["evaluation_date"]))
|
||||||
|
found.append(tea_fhir.ados2_observation(known, births.get(row["person_id"])))
|
||||||
|
if domain == Domain.TEA:
|
||||||
|
found += _tea_eeg_studies(persons, at)
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _tea_eeg_studies(persons: list[str], at: str) -> list[Resource]:
|
||||||
|
def rows(kind):
|
||||||
|
return reads.rows("tea", kind, persons=persons, cutoff=at)
|
||||||
|
|
||||||
|
def key(row):
|
||||||
|
return row["person_id"], row["study_date"], row["edf"]
|
||||||
|
|
||||||
|
regions, results = defaultdict(list), defaultdict(list)
|
||||||
|
for row in rows("regions"):
|
||||||
|
regions[(*key(row), row["code"])].append(row)
|
||||||
|
for row in rows("checks"):
|
||||||
|
results[key(row)].append(tea_fhir.eeg_check(row))
|
||||||
|
for row in rows("metrics"):
|
||||||
|
results[key(row)].append(tea_fhir.eeg_metric(row, regions[(*key(row), row["code"])]))
|
||||||
|
found = []
|
||||||
|
for row in rows("eegs"):
|
||||||
|
observations = results[key(row)]
|
||||||
|
found.extend((tea_fhir.eeg_report(row, observations), *observations))
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _tea_risks(persons: list[str], at: str) -> list[Resource]:
|
||||||
|
groups = defaultdict(list)
|
||||||
|
for row in reads.rows("tea", "association_scores", persons=persons, cutoff=at):
|
||||||
|
group = groups[row["person_id"]]
|
||||||
|
if (
|
||||||
|
not group
|
||||||
|
or row["edf"] == group[0]["edf"]
|
||||||
|
and row["study_date"] == group[0]["study_date"]
|
||||||
|
):
|
||||||
|
group.append(row)
|
||||||
|
return [tea_fhir.association_risk(group) for group in groups.values()]
|
||||||
|
|
||||||
|
|
||||||
|
def _risk_assessments(rows: list[dict]) -> list[Resource]:
|
||||||
|
groups: dict[tuple, list[dict]] = {}
|
||||||
|
for r in rows:
|
||||||
|
groups.setdefault((r["model"], r["version"], r["person_id"], str(r["index_date"])),
|
||||||
|
[]).append(r) # fmt: skip
|
||||||
|
return [f.risk_assessment(g[0], g) for g in groups.values()]
|
||||||
|
|
||||||
|
|
||||||
|
def _clinical_search(kind: str, build, request, domain, subject, count, offset):
|
||||||
|
fu = _clinical(domain)
|
||||||
|
count, offset = _page(count, offset)
|
||||||
|
params: dict = {"persons": _subjects(subject)}
|
||||||
|
if kind != "risk":
|
||||||
|
params["cutoff"] = _cutoff(domain, None).isoformat()
|
||||||
|
if kind == "procedure":
|
||||||
|
params["types"] = list(fu.PROCEDURES)
|
||||||
|
if kind == "risk" and domain == Domain.TEA:
|
||||||
|
found = _tea_risks(params["persons"], _cutoff(domain, None).isoformat())
|
||||||
|
else:
|
||||||
|
found = build(reads.rows(domain.value, kind, **params))
|
||||||
|
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
|
||||||
|
|
||||||
|
|
||||||
|
SUBJECT = "Patient/<id>, comma-separated"
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/DiagnosticReport",
|
||||||
|
responses=_OK,
|
||||||
|
response_class=Response,
|
||||||
|
description=(
|
||||||
|
"The domain's reports (each study of the catalog with a report), "
|
||||||
|
"as known by the last\n"
|
||||||
|
"day with data."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def search_diagnostic_report(request: Request, domain: Domain,
|
||||||
|
subject: str | None = Query(None, description=SUBJECT),
|
||||||
|
_count: int | None = Query(None),
|
||||||
|
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||||
|
return _study_search("DiagnosticReport", request, domain, subject, _count, _offset)
|
||||||
|
|
||||||
|
|
||||||
|
def _study_search(kind: str, request, domain, subject, count, offset) -> Response:
|
||||||
|
_clinical(domain)
|
||||||
|
count, offset = _page(count, offset)
|
||||||
|
persons, at = _subjects(subject), _cutoff(domain, None).isoformat()
|
||||||
|
found = [r for r in _studies(domain, persons, at) if r.get_resource_type() == kind]
|
||||||
|
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/Encounter",
|
||||||
|
responses=_OK,
|
||||||
|
response_class=Response,
|
||||||
|
description="Consultations: each study of the catalog without a report, as an encounter.",
|
||||||
|
)
|
||||||
|
def search_encounter(request: Request, domain: Domain,
|
||||||
|
subject: str | None = Query(None, description=SUBJECT),
|
||||||
|
_count: int | None = Query(None),
|
||||||
|
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||||
|
return _study_search("Encounter", request, domain, subject, _count, _offset)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/Observation",
|
||||||
|
responses=_OK,
|
||||||
|
response_class=Response,
|
||||||
|
description="Every result of the domain's reports, one per field of the catalog.",
|
||||||
|
)
|
||||||
|
def search_observation(request: Request, domain: Domain,
|
||||||
|
subject: str | None = Query(None, description=SUBJECT),
|
||||||
|
_count: int | None = Query(None),
|
||||||
|
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||||
|
return _study_search("Observation", request, domain, subject, _count, _offset)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/Condition",
|
||||||
|
responses=_OK,
|
||||||
|
response_class=Response,
|
||||||
|
description="What clinical notes diagnosed (CaMa: and each recurrence).",
|
||||||
|
)
|
||||||
|
def search_condition(request: Request, domain: Domain,
|
||||||
|
subject: str | None = Query(None, description=SUBJECT),
|
||||||
|
_count: int | None = Query(None),
|
||||||
|
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||||
|
|
||||||
|
def build(rows):
|
||||||
|
return [f.condition(r) for r in rows]
|
||||||
|
|
||||||
|
return _clinical_search("condition", build, request, domain, subject, _count, _offset)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/Procedure",
|
||||||
|
responses=_OK,
|
||||||
|
response_class=Response,
|
||||||
|
description=(
|
||||||
|
"The procedures the domain's timeline infers (CaCu: colposcopies "
|
||||||
|
"and treatments;\n"
|
||||||
|
"CaMa: each treatment, by its kind)."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def search_procedure(request: Request, domain: Domain,
|
||||||
|
subject: str | None = Query(None, description=SUBJECT),
|
||||||
|
_count: int | None = Query(None),
|
||||||
|
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||||
|
|
||||||
|
def build(rows):
|
||||||
|
return [f.procedure(r, domain.value) for r in rows]
|
||||||
|
|
||||||
|
return _clinical_search("procedure", build, request, domain, subject, _count, _offset)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/RiskAssessment",
|
||||||
|
responses=_OK,
|
||||||
|
response_class=Response,
|
||||||
|
description="The champion models' risks, one per model and index date.",
|
||||||
|
)
|
||||||
|
def search_risk_assessment(request: Request, domain: Domain,
|
||||||
|
subject: str | None = Query(None, description=SUBJECT),
|
||||||
|
_count: int | None = Query(None),
|
||||||
|
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||||
|
return _clinical_search("risk", _risk_assessments, request, domain, subject, _count, _offset)
|
||||||
|
|
||||||
|
|
||||||
|
def _measure(domain: Domain, key: str) -> m.Measure:
|
||||||
|
found = measures(domain)
|
||||||
|
for code, measure in found.items():
|
||||||
|
if key in (code, f.measure_id(code), f.measure_url(code)):
|
||||||
|
return measure
|
||||||
|
raise HTTPException(404, f"no {domain.value} Measure {key}")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/Measure/{id}", responses=_OK, response_class=Response)
|
||||||
|
def read_measure(domain: Domain, id: str) -> Response:
|
||||||
|
return fhir(f.measure(_measure(domain, id), domain.value))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/Measure",
|
||||||
|
responses=_OK,
|
||||||
|
response_class=Response,
|
||||||
|
description="Every measure of the domain (none for a domain without them yet).",
|
||||||
|
)
|
||||||
|
def search_measure(request: Request, domain: Domain, _count: int | None = Query(None),
|
||||||
|
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||||
|
count, offset = _page(_count, _offset)
|
||||||
|
found = [f.measure(x, domain.value) for x in measures(domain).values()]
|
||||||
|
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/MeasureReport",
|
||||||
|
responses=_OK,
|
||||||
|
response_class=Response,
|
||||||
|
description="The measure's summary report for each period asked for, evaluated over gold.",
|
||||||
|
)
|
||||||
|
def search_measure_report(
|
||||||
|
request: Request,
|
||||||
|
domain: Domain,
|
||||||
|
measure: str = Query(alias="measure", description="the Measure's id or canonical URL"),
|
||||||
|
periods: str = Query(
|
||||||
|
alias="reporting-period",
|
||||||
|
description="semesters (2025-S1) or months (2025-03), comma-separated",
|
||||||
|
),
|
||||||
|
as_of: datetime | None = Query(
|
||||||
|
None, alias="as-of", description="count only what was known by then"
|
||||||
|
),
|
||||||
|
event_cutoff: date | None = Query(
|
||||||
|
None, alias="event-cutoff", description="durations count to this day"
|
||||||
|
),
|
||||||
|
_count: int | None = Query(None),
|
||||||
|
_offset: int = Query(0),
|
||||||
|
) -> Response:
|
||||||
|
found = _measure(domain, measure.split("|")[0])
|
||||||
|
count, offset = _page(_count, _offset)
|
||||||
|
try:
|
||||||
|
asked = [(p.strip(), m.Period.parse(p.strip())) for p in periods.split(",") if p.strip()]
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(422, f"reporting-period: {e}") from e
|
||||||
|
rows = measure_reads.rows(domain.value, found.rows, **found.params)
|
||||||
|
reports = []
|
||||||
|
page = _sliced(asked, count, offset)
|
||||||
|
results = m.evaluate_periods(found, rows, [p for _, p in page], as_of, event_cutoff)
|
||||||
|
for (text, period), result in zip(page, results, strict=True):
|
||||||
|
report = m.report(found, period, result, as_of)
|
||||||
|
report.id = f"{f.measure_id(found.id)}-{text.lower()}"
|
||||||
|
reports.append(report)
|
||||||
|
return bundle(request, reports, len(asked), count, offset)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"",
|
||||||
|
responses=_OK,
|
||||||
|
response_class=Response,
|
||||||
|
status_code=202,
|
||||||
|
description=(
|
||||||
|
"A standard hospital's Bundle: checked as FHIR, kept as sent in "
|
||||||
|
"the sender's inbox,\n"
|
||||||
|
"and placed by the sender's pipeline (a run starts; follow it at "
|
||||||
|
"the Location)."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def post_bundle(
|
||||||
|
domain: Domain,
|
||||||
|
bundle: Annotated[dict[str, Any], Body(description="a FHIR R4 batch or transaction Bundle")],
|
||||||
|
sender: str = Query(
|
||||||
|
pattern=ID_PATTERN,
|
||||||
|
max_length=40,
|
||||||
|
description="the sender's pipeline (its fhir nodes read this inbox)",
|
||||||
|
),
|
||||||
|
client: DagsterGraphQLClient = Depends(dagster),
|
||||||
|
) -> Response:
|
||||||
|
try:
|
||||||
|
parsed = Bundle.model_validate(bundle)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(422, f"not a valid R4 Bundle: {e}") from e
|
||||||
|
if parsed.type not in ("batch", "transaction", "collection"):
|
||||||
|
raise HTTPException(422, "send a batch, transaction or collection Bundle")
|
||||||
|
if not config_log.latest_version(sender):
|
||||||
|
raise HTTPException(404, f"no pipeline {sender} to place what it sends")
|
||||||
|
readers.receive(sender, bundle)
|
||||||
|
run_id = submit(client, sender)
|
||||||
|
entries = [{"response": {"status": "202 Accepted", "location":
|
||||||
|
f"{e.resource.get_resource_type()}/{e.resource.id}"}}
|
||||||
|
for e in parsed.entry or [] if e.resource is not None] # fmt: skip
|
||||||
|
answer = Bundle(type="batch-response", entry=entries or None)
|
||||||
|
found = fhir(answer)
|
||||||
|
found.status_code = 202
|
||||||
|
found.headers["Location"] = f"/runs/{run_id}"
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/metadata",
|
||||||
|
responses=_OK,
|
||||||
|
response_class=Response,
|
||||||
|
description=(
|
||||||
|
"What this base serves: built from the routes above, so it cannot drift from them."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def metadata(request: Request, domain: Domain) -> Response:
|
||||||
|
resources: dict[str, dict] = {}
|
||||||
|
system: list[dict] = []
|
||||||
|
fu = part(domain, "follow_up")
|
||||||
|
clinical = fu is not None
|
||||||
|
for route in router.routes:
|
||||||
|
path = route.path.removeprefix(router.prefix)
|
||||||
|
if not path:
|
||||||
|
if clinical:
|
||||||
|
system = [{"code": "batch"}, {"code": "transaction"}]
|
||||||
|
continue
|
||||||
|
_, kind, *rest = path.split("/")
|
||||||
|
if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport"
|
||||||
|
and not clinical): # fmt: skip
|
||||||
|
continue
|
||||||
|
if rest and rest[0].startswith("$"):
|
||||||
|
continue
|
||||||
|
entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []})
|
||||||
|
if kind == "Patient" and not rest:
|
||||||
|
entry |= {"searchInclude": ["DiagnosticReport:result"],
|
||||||
|
"searchRevInclude": list(_revincludes(domain))} # fmt: skip
|
||||||
|
if domain == Domain.TEA:
|
||||||
|
entry["searchParam"] += [
|
||||||
|
{"name": name, "type": spec[0]} for name, spec in TEA_FILTERS.items()
|
||||||
|
]
|
||||||
|
entry["interaction"].append({"code": "read" if rest else "search-type"})
|
||||||
|
for param in route.dependant.query_params:
|
||||||
|
name = param.alias
|
||||||
|
if name.startswith("_") and name != "_id":
|
||||||
|
continue
|
||||||
|
declared = f.SEARCH_PARAMETERS.get(name)
|
||||||
|
entry["searchParam"].append({
|
||||||
|
"name": name,
|
||||||
|
"type": declared[1] if declared else _STANDARD[name],
|
||||||
|
**({"definition": f"{f.BASE}/SearchParameter/{name}"} if declared else {}),
|
||||||
|
}) # fmt: skip
|
||||||
|
statement = CapabilityStatement.model_validate({
|
||||||
|
"resourceType": "CapabilityStatement",
|
||||||
|
"status": "active",
|
||||||
|
"date": date.today().isoformat(),
|
||||||
|
"kind": "instance",
|
||||||
|
"fhirVersion": f.FHIR_VERSION,
|
||||||
|
"format": ["json"],
|
||||||
|
"implementation": {"description": f"ISSSTELEON {domain.value}",
|
||||||
|
"url": str(request.base_url).rstrip("/") + f"/{domain.value}/fhir"},
|
||||||
|
"rest": [{"mode": "server",
|
||||||
|
"resource": [{k: v for k, v in r.items() if v} for r in resources.values()],
|
||||||
|
**({"interaction": system} if system else {})}],
|
||||||
|
}) # fmt: skip
|
||||||
|
return fhir(statement)
|
||||||
|
|
||||||
|
|
||||||
|
_STANDARD = {
|
||||||
|
"_id": "token",
|
||||||
|
"subject": "reference",
|
||||||
|
"measure": "reference",
|
||||||
|
"follow-up-start": "date",
|
||||||
|
"name": "string",
|
||||||
|
"identifier": "token",
|
||||||
|
}
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
from typing import Annotated, Any
|
||||||
|
|
||||||
|
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Path, Query
|
||||||
|
from fhir.resources.R4B.conceptmap import ConceptMap
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from core import concept_map
|
||||||
|
from core.pipeline import ID_PATTERN, Pipeline, Source, redacted, restored
|
||||||
|
from core.schema import ENTITIES
|
||||||
|
from persistance import config_log, nodes
|
||||||
|
from webapi.runs import dagster
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/ingest", tags=["ingest"])
|
||||||
|
PipelineId = Annotated[str, Path(pattern=ID_PATTERN, max_length=40)]
|
||||||
|
NodeId = Annotated[str, Path(pattern=ID_PATTERN, max_length=40)]
|
||||||
|
Rows = list[dict[str, Any]]
|
||||||
|
|
||||||
|
|
||||||
|
def _from_source(call, *args):
|
||||||
|
try:
|
||||||
|
return call(*args)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
raise HTTPException(422, detail=f"{type(e).__name__}: {e}") from e
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/schema",
|
||||||
|
description="What the canvas draws with: every node kind's form, and the platform entities.",
|
||||||
|
)
|
||||||
|
def schema() -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"pipeline": Pipeline.model_json_schema(),
|
||||||
|
"entities": {name: model.model_json_schema() for name, model in ENTITIES.items()},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/sources/preview",
|
||||||
|
description="The first rows a source node would load.",
|
||||||
|
)
|
||||||
|
def source_preview(node: Source, limit: Annotated[int, Query(ge=1, le=200)] = 20) -> Rows:
|
||||||
|
return [nodes.shown(r) for r in _from_source(nodes.preview, node, limit)]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/pipelines")
|
||||||
|
def pipelines() -> Rows:
|
||||||
|
return config_log.pipelines()
|
||||||
|
|
||||||
|
|
||||||
|
class SavedPipeline(BaseModel):
|
||||||
|
version: int
|
||||||
|
pipeline: Pipeline
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/pipelines/{pipeline_id}",
|
||||||
|
description="A saved pipeline (latest by default), with its secrets masked.",
|
||||||
|
)
|
||||||
|
def pipeline(pipeline_id: PipelineId, version: int | None = None) -> SavedPipeline:
|
||||||
|
if not config_log.latest_version(pipeline_id):
|
||||||
|
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
||||||
|
found, saved = config_log.get(pipeline_id, version)
|
||||||
|
return SavedPipeline(version=found, pipeline=redacted(saved))
|
||||||
|
|
||||||
|
|
||||||
|
@router.put(
|
||||||
|
"/pipelines/{pipeline_id}",
|
||||||
|
description=(
|
||||||
|
"Saves a new version. Masked secrets sent back are kept as they "
|
||||||
|
"were saved; every\n"
|
||||||
|
"ConceptMap a node names must exist."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def save_pipeline(pipeline_id: PipelineId, drawn: Pipeline) -> dict[str, int]:
|
||||||
|
named = {n.concept_map for n in drawn.nodes if getattr(n, "concept_map", None)}
|
||||||
|
if missing := sorted(m for m in named if not config_log.latest_version(m, "concept_maps")):
|
||||||
|
raise HTTPException(422, detail=f"no concept maps {missing}")
|
||||||
|
previous = config_log.get(pipeline_id)[1] if config_log.latest_version(pipeline_id) else None
|
||||||
|
try:
|
||||||
|
complete = restored(drawn, previous)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(422, detail=str(e)) from e
|
||||||
|
return {"version": config_log.save(pipeline_id, complete)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/concept-maps/{map_id}",
|
||||||
|
description="A site's codes in platform terms (FHIR R4B ConceptMap), latest version.",
|
||||||
|
)
|
||||||
|
def get_concept_map(map_id: PipelineId) -> dict[str, Any]:
|
||||||
|
if not config_log.latest_version(map_id, "concept_maps"):
|
||||||
|
raise HTTPException(404, detail=f"no concept map {map_id}")
|
||||||
|
return config_log.concept_map(map_id).model_dump(mode="json", exclude_none=True)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put(
|
||||||
|
"/concept-maps/{map_id}",
|
||||||
|
description=(
|
||||||
|
"Saves a new version of a ConceptMap. Its groups target the "
|
||||||
|
"systems platform fields\n"
|
||||||
|
"take codes from, and only codes those fields allow "
|
||||||
|
"(core.concept_map)."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def save_concept_map(map_id: PipelineId, doc: dict[str, Any]) -> dict[str, int]:
|
||||||
|
try:
|
||||||
|
found = ConceptMap.model_validate({**doc, "resourceType": "ConceptMap"})
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(422, detail=str(e)) from e
|
||||||
|
if problems := concept_map.problems(found):
|
||||||
|
raise HTTPException(422, detail=problems)
|
||||||
|
return {"version": config_log.save(map_id, found, "concept_maps")}
|
||||||
|
|
||||||
|
|
||||||
|
class RunRequest(BaseModel):
|
||||||
|
version: int | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/pipelines/{pipeline_id}/runs",
|
||||||
|
description="Starts the `ingest` job for this pipeline; follow it at /runs/{run_id}.",
|
||||||
|
)
|
||||||
|
def start_run(
|
||||||
|
pipeline_id: PipelineId,
|
||||||
|
request: RunRequest,
|
||||||
|
client: DagsterGraphQLClient = Depends(dagster),
|
||||||
|
) -> dict[str, str]:
|
||||||
|
if not config_log.latest_version(pipeline_id):
|
||||||
|
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
||||||
|
return {"run_id": submit(client, pipeline_id, request.version)}
|
||||||
|
|
||||||
|
|
||||||
|
def submit(client: DagsterGraphQLClient, pipeline_id: str, version: int | None = None) -> str:
|
||||||
|
config = {"pipeline": pipeline_id, "version": version}
|
||||||
|
try:
|
||||||
|
return client.submit_job_execution(
|
||||||
|
"ingest", run_config={"ops": {"run_pipeline": {"config": config}}}
|
||||||
|
)
|
||||||
|
except DagsterGraphQLClientError as e:
|
||||||
|
raise HTTPException(502, detail=str(e)) from e
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/pipelines/{pipeline_id}/nodes/{node_id}/rows",
|
||||||
|
description="What a node produced in the last run (empty if it produced nothing yet).",
|
||||||
|
)
|
||||||
|
def node_rows(
|
||||||
|
pipeline_id: PipelineId,
|
||||||
|
node_id: NodeId,
|
||||||
|
limit: Annotated[int, Query(ge=1, le=500)] = 50,
|
||||||
|
) -> Rows:
|
||||||
|
out = []
|
||||||
|
for row in nodes.rows(pipeline_id, node_id):
|
||||||
|
out.append(nodes.shown(row))
|
||||||
|
if len(out) == limit:
|
||||||
|
break
|
||||||
|
return out
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
from fastapi import Depends, FastAPI, Request
|
||||||
|
from fastapi.exception_handlers import http_exception_handler
|
||||||
|
from starlette.exceptions import HTTPException
|
||||||
|
|
||||||
|
from core.domains import Domain
|
||||||
|
from webapi import eeg, execution, fhir, ingest, models, preview, review, runs, sources, users
|
||||||
|
from webapi.auth import caller
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title="ISSSTELEON",
|
||||||
|
version="0.0.0",
|
||||||
|
dependencies=[Depends(caller)],
|
||||||
|
generate_unique_id_function=lambda route: route.name,
|
||||||
|
lifespan=users.lifespan,
|
||||||
|
)
|
||||||
|
app.include_router(ingest.router)
|
||||||
|
app.include_router(sources.router)
|
||||||
|
app.include_router(review.router)
|
||||||
|
app.include_router(runs.router)
|
||||||
|
app.include_router(execution.router)
|
||||||
|
app.include_router(models.router)
|
||||||
|
app.include_router(eeg.router)
|
||||||
|
app.include_router(preview.router)
|
||||||
|
app.include_router(fhir.router)
|
||||||
|
app.include_router(users.router)
|
||||||
|
|
||||||
|
|
||||||
|
@app.exception_handler(HTTPException)
|
||||||
|
async def errors(request: Request, error: HTTPException):
|
||||||
|
if "/fhir/" in request.url.path or request.url.path.endswith("/fhir"):
|
||||||
|
return fhir.outcome(error.status_code, str(error.detail))
|
||||||
|
return await http_exception_handler(request, error)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health")
|
||||||
|
def health() -> dict[str, str]:
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/domains")
|
||||||
|
def domains() -> list[Domain]:
|
||||||
|
return list(Domain)
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
import mimetypes
|
||||||
|
import zipfile
|
||||||
|
from datetime import date
|
||||||
|
from typing import Annotated, Any, Literal
|
||||||
|
|
||||||
|
from dagster_graphql import DagsterGraphQLClient
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile
|
||||||
|
from fastapi.responses import Response
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from core.domains import Domain
|
||||||
|
from core.models import title
|
||||||
|
from persistance import bundle, cluster, registry
|
||||||
|
from persistance.cluster import Execution, TrainingSource
|
||||||
|
from webapi.runs import dagster, execution_config, submit
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/models", tags=["models"])
|
||||||
|
|
||||||
|
|
||||||
|
class Version(BaseModel):
|
||||||
|
version: int
|
||||||
|
created: int
|
||||||
|
aliases: list[str]
|
||||||
|
metrics: dict[str, float]
|
||||||
|
params: dict[str, str]
|
||||||
|
reports: list[str]
|
||||||
|
status: Literal["champion", "retired", "candidate"]
|
||||||
|
|
||||||
|
|
||||||
|
class Model(BaseModel):
|
||||||
|
name: str
|
||||||
|
title: str
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{domain}")
|
||||||
|
def models(domain: Domain) -> list[Model]:
|
||||||
|
prefix = f"{domain.value}."
|
||||||
|
return [Model(name=n.removeprefix(prefix), title=title(n)) for n in registry.names(prefix)]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/{domain}/export",
|
||||||
|
responses={200: {"content": {"application/zip": {}}}},
|
||||||
|
response_class=Response,
|
||||||
|
)
|
||||||
|
def export_models(
|
||||||
|
domain: Domain,
|
||||||
|
names: Annotated[list[str] | None, Query()] = None,
|
||||||
|
versions: bundle.Selection = "champion",
|
||||||
|
) -> Response:
|
||||||
|
try:
|
||||||
|
exported = bundle.export(domain, names, versions)
|
||||||
|
except bundle.Empty as e:
|
||||||
|
raise HTTPException(409, detail=str(e)) from e
|
||||||
|
except bundle.BundleError as e:
|
||||||
|
raise HTTPException(422, detail=str(e)) from e
|
||||||
|
return Response(
|
||||||
|
exported.data,
|
||||||
|
media_type="application/zip",
|
||||||
|
headers={
|
||||||
|
"X-Bundle-Sha256": exported.sha256,
|
||||||
|
"X-Bundle-Versions": ",".join(f"{name}/{v}" for name, v in exported.versions),
|
||||||
|
"Content-Disposition": (
|
||||||
|
f'attachment; filename="{domain}-models-{exported.sha256[:12]}.zip"'
|
||||||
|
),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{domain}/import")
|
||||||
|
def import_models(
|
||||||
|
domain: Domain,
|
||||||
|
sha256: Annotated[str, Query(pattern=r"^[0-9a-fA-F]{64}$")],
|
||||||
|
file: UploadFile,
|
||||||
|
client: DagsterGraphQLClient = Depends(dagster),
|
||||||
|
) -> dict[str, str]:
|
||||||
|
computed, path = bundle.stage(file.file)
|
||||||
|
if computed != sha256.lower():
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
raise HTTPException(422, detail=f"the file's SHA-256 is {computed}, not the one given")
|
||||||
|
if not zipfile.is_zipfile(path):
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
raise HTTPException(422, detail="not a bundle")
|
||||||
|
if not bundle.trusted(computed):
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
raise HTTPException(
|
||||||
|
403,
|
||||||
|
detail=f"bundle {computed} is not trusted on this server: "
|
||||||
|
f"the operator adds its SHA-256 to {bundle.trusted_file()}",
|
||||||
|
)
|
||||||
|
return submit(
|
||||||
|
client,
|
||||||
|
"import_bundle",
|
||||||
|
"import_bundle_files",
|
||||||
|
{"domain": domain.value, "sha256": computed},
|
||||||
|
domain.value,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{domain}/{name}/versions")
|
||||||
|
def versions(domain: Domain, name: str) -> list[Version]:
|
||||||
|
if not (found := registry.versions(f"{domain.value}.{name}")):
|
||||||
|
raise HTTPException(404, detail=f"no {domain.value} model {name}")
|
||||||
|
return [Version(**v) for v in found]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{domain}/{name}/versions/{version}/reports/{report}",
|
||||||
|
responses={200: {"content": {"application/json": {}, "application/octet-stream": {}},
|
||||||
|
"description": "the report as stored"}},
|
||||||
|
response_class=Response,
|
||||||
|
description=(
|
||||||
|
"A version's report: the generated ones as JSON (what the "
|
||||||
|
'governance page draws), the\n'
|
||||||
|
'clinical validation as the file the clinical team uploaded.'
|
||||||
|
),
|
||||||
|
) # fmt: skip
|
||||||
|
def read_report(domain: Domain, name: str, version: int, report: str) -> Response:
|
||||||
|
found = registry.report(f"{domain.value}.{name}", version, report)
|
||||||
|
if found is None:
|
||||||
|
raise HTTPException(404, detail=f"{domain.value}.{name} v{version} has no {report}")
|
||||||
|
filename, content = found
|
||||||
|
kind = mimetypes.guess_type(filename)[0] or "application/octet-stream"
|
||||||
|
return Response(content, media_type=kind,
|
||||||
|
headers={"Content-Disposition": f'inline; filename="{filename}"'}) # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/{domain}/{name}/versions/{version}/reports/clinical_validation",
|
||||||
|
description=(
|
||||||
|
"The clinical team's validation of a version: the third report, "
|
||||||
|
"which promotion needs\n"
|
||||||
|
"unless the site left it out of PROMOTION_REPORTS."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def add_clinical_validation(domain: Domain, name: str, version: int, file: UploadFile) -> dict:
|
||||||
|
registry.add_report(f"{domain.value}.{name}", version, "clinical_validation",
|
||||||
|
file.filename or "report", file.file.read()) # fmt: skip
|
||||||
|
return {"reports": sorted(registry.reports(f"{domain.value}.{name}", version))}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/{domain}/{name}/versions/{version}/promote",
|
||||||
|
description=(
|
||||||
|
"The version risk batches come from from now on; refused (409) "
|
||||||
|
"without the reports\n"
|
||||||
|
"the site requires (PROMOTION_REPORTS; default: technical "
|
||||||
|
"validation, interpretability\n"
|
||||||
|
"and clinical validation)."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def promote(domain: Domain, name: str, version: int) -> dict:
|
||||||
|
try:
|
||||||
|
registry.promote(f"{domain.value}.{name}", version)
|
||||||
|
except registry.UnknownVersion as e:
|
||||||
|
raise HTTPException(404, detail=str(e)) from e
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(409, detail=str(e)) from e
|
||||||
|
return {"champion": version}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{domain}/{name}/versions/{version}/checks")
|
||||||
|
def version_checks(domain: Domain, name: str, version: int) -> dict:
|
||||||
|
registered = f"{domain.value}.{name}"
|
||||||
|
try:
|
||||||
|
status = registry.status(registered, version)
|
||||||
|
except registry.UnknownVersion as e:
|
||||||
|
raise HTTPException(404, detail=str(e)) from e
|
||||||
|
checks = registry.checks(registered, version)
|
||||||
|
return {
|
||||||
|
"version": version,
|
||||||
|
"status": status,
|
||||||
|
"checks": checks,
|
||||||
|
"promotable": status != "retired" and all(check["present"] for check in checks),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{domain}/{name}/versions/{version}/retire")
|
||||||
|
def retire(domain: Domain, name: str, version: int) -> dict[str, str]:
|
||||||
|
try:
|
||||||
|
registry.retire(f"{domain.value}.{name}", version)
|
||||||
|
except registry.UnknownVersion as e:
|
||||||
|
raise HTTPException(404, detail=str(e)) from e
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(409, detail=str(e)) from e
|
||||||
|
return {"status": "retired"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{domain}/{name}/versions/{version}/lineage")
|
||||||
|
def lineage(domain: Domain, name: str, version: int) -> dict:
|
||||||
|
try:
|
||||||
|
return registry.lineage(f"{domain.value}.{name}", version)
|
||||||
|
except registry.UnknownVersion as e:
|
||||||
|
raise HTTPException(404, detail=str(e)) from e
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{domain}/{name}/versions/{version}/curve")
|
||||||
|
def curve(domain: Domain, name: str, version: int, feature: str = "value") -> list[dict]:
|
||||||
|
if domain != Domain.TEA:
|
||||||
|
raise HTTPException(404, detail="no age curve for this model")
|
||||||
|
try:
|
||||||
|
model = registry.load(f"{domain.value}.{name}", version).unwrap_python_model()
|
||||||
|
if not hasattr(model, "curve"):
|
||||||
|
raise HTTPException(404, detail="no age curve for this model")
|
||||||
|
return model.curve(feature, range(16, 37))
|
||||||
|
except KeyError as e:
|
||||||
|
raise HTTPException(404, detail=f"no curve feature {feature!r}") from e
|
||||||
|
except LookupError as e:
|
||||||
|
raise HTTPException(404, detail=str(e)) from e
|
||||||
|
|
||||||
|
|
||||||
|
class TrainingForm(BaseModel):
|
||||||
|
as_of: date | None = Field(
|
||||||
|
None, title="Datos hasta", description="Fecha de corte de los datos (por omisión, hoy)"
|
||||||
|
)
|
||||||
|
execution: Execution | None = None
|
||||||
|
source: TrainingSource | None = Field(None, title="Datos de entrenamiento")
|
||||||
|
|
||||||
|
|
||||||
|
class Training(TrainingForm):
|
||||||
|
models: list[str] = []
|
||||||
|
|
||||||
|
|
||||||
|
class TrainingConfig(BaseModel):
|
||||||
|
domain: str
|
||||||
|
name: str
|
||||||
|
json_schema: dict[str, Any]
|
||||||
|
defaults: dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{domain}/{name}/training-config")
|
||||||
|
def training_config(domain: Domain, name: str) -> TrainingConfig:
|
||||||
|
json_schema = TrainingForm.model_json_schema()
|
||||||
|
defaults = {"execution": {"mode": cluster.default_mode(), "scheduler": None}}
|
||||||
|
if domain == Domain.TEA:
|
||||||
|
defaults["source"] = {"kind": "site"}
|
||||||
|
else:
|
||||||
|
del json_schema["properties"]["source"]
|
||||||
|
for definition in ("TrainingSource", "SiteTrainingSource", "FolderTrainingSource"):
|
||||||
|
del json_schema["$defs"][definition]
|
||||||
|
return TrainingConfig(
|
||||||
|
domain=domain.value, name=name, json_schema=json_schema, defaults=defaults
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Analyze(BaseModel):
|
||||||
|
execution: Execution | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/{domain}/train",
|
||||||
|
description="Starts training a new version of every model of the domain; follow it at /runs.",
|
||||||
|
)
|
||||||
|
def train(domain: Domain, request: Training,
|
||||||
|
client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: # fmt: skip
|
||||||
|
if request.source is not None and domain != Domain.TEA:
|
||||||
|
raise HTTPException(422, f"{domain.value} models take no training source")
|
||||||
|
config: dict = {"domain": domain.value, "execution": execution_config(request.execution)}
|
||||||
|
if request.as_of:
|
||||||
|
config["as_of"] = request.as_of.isoformat()
|
||||||
|
if request.models:
|
||||||
|
config["models"] = request.models
|
||||||
|
if request.source is not None:
|
||||||
|
config["source"] = request.source.model_dump()
|
||||||
|
return submit(client, "train", "train_models", config, domain=domain.value)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/{domain}/analyze",
|
||||||
|
description=(
|
||||||
|
"Starts analysing the studies the domain's models read whole "
|
||||||
|
"(TEA: its EEGs); follow\n"
|
||||||
|
"it at /runs."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def analyze(
|
||||||
|
domain: Domain,
|
||||||
|
request: Analyze = Analyze(), # noqa: B008
|
||||||
|
client: DagsterGraphQLClient = Depends(dagster),
|
||||||
|
) -> dict[str, str]:
|
||||||
|
config = {"domain": domain.value, "execution": execution_config(request.execution)}
|
||||||
|
return submit(client, "analyze", "analyze_studies", config, domain=domain.value)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/{domain}/score",
|
||||||
|
description="Starts a risk batch from each model's champion; follow it at /runs.",
|
||||||
|
)
|
||||||
|
def score(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
||||||
|
return submit(client, "score", "score_models", {"domain": domain.value}, domain=domain.value)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import json
|
||||||
|
|
||||||
|
from webapi.main import app
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print(json.dumps(app.openapi(), indent=1, sort_keys=True))
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
from datetime import date
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from dagster_graphql import DagsterGraphQLClient
|
||||||
|
from fastapi import APIRouter, Depends, Form, HTTPException, UploadFile
|
||||||
|
from pydantic import BaseModel, WithJsonSchema
|
||||||
|
|
||||||
|
from persistance import previews
|
||||||
|
from webapi import runs
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/tea/preview", tags=["preview"])
|
||||||
|
_MAX_FILE_BYTES = 200 * 1024 * 1024
|
||||||
|
_BinaryUpload = Annotated[UploadFile, WithJsonSchema({"type": "string", "format": "binary"})]
|
||||||
|
|
||||||
|
|
||||||
|
class PreviewStatus(BaseModel):
|
||||||
|
state: runs.State
|
||||||
|
result: previews.PreviewResult | None
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("")
|
||||||
|
def start_preview(
|
||||||
|
edf: _BinaryUpload,
|
||||||
|
ados2: _BinaryUpload | None = None,
|
||||||
|
birth_date: Annotated[date | None, Form()] = None,
|
||||||
|
pipeline: Annotated[str, Form()] = "tea",
|
||||||
|
client: DagsterGraphQLClient = Depends(runs.dagster),
|
||||||
|
) -> dict[str, str]:
|
||||||
|
for file in (edf, ados2):
|
||||||
|
if file is not None and file.size is not None and file.size > _MAX_FILE_BYTES:
|
||||||
|
raise HTTPException(413, detail="preview files may be at most 200 MiB each")
|
||||||
|
config = {
|
||||||
|
"edf": previews.put(edf.file.read()),
|
||||||
|
"ados2": previews.put(ados2.file.read()) if ados2 is not None else None,
|
||||||
|
"birth_date": birth_date.isoformat() if birth_date else None,
|
||||||
|
"pipeline": pipeline,
|
||||||
|
}
|
||||||
|
return runs.submit(client, "tea_preview", "preview_study", config, domain="tea")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{run_id}")
|
||||||
|
def preview_status(run_id: str) -> PreviewStatus:
|
||||||
|
run = runs.run_status(run_id, outputs=True)
|
||||||
|
if run.job != "tea_preview":
|
||||||
|
raise HTTPException(404, detail=f"no TEA preview run {run_id}")
|
||||||
|
raw = (run.outputs or {}).get("preview_study.result") if run.state == "succeeded" else None
|
||||||
|
return PreviewStatus(
|
||||||
|
state=run.state,
|
||||||
|
result=previews.PreviewResult.model_validate(raw) if raw is not None else None,
|
||||||
|
)
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
from pydantic import BaseModel, ConfigDict, model_validator
|
||||||
|
|
||||||
|
from core.pipeline import EntityName, Id, validate
|
||||||
|
from core.schema import ENTITIES
|
||||||
|
from persistance import nodes, review
|
||||||
|
from webapi.auth import Caller, caller
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/review", tags=["review"])
|
||||||
|
Rows = list[dict[str, Any]]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/held",
|
||||||
|
description="Rows a rule held, with the reasons and the values as they came.",
|
||||||
|
)
|
||||||
|
def held(entity: EntityName) -> Rows:
|
||||||
|
return review.held(entity)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/conflicts",
|
||||||
|
description="Rows of one person and date that disagree; reject the wrong ones.",
|
||||||
|
)
|
||||||
|
def conflicts(entity: EntityName) -> Rows:
|
||||||
|
return review.conflicts(entity)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/unrecognised",
|
||||||
|
description=(
|
||||||
|
"Documents a pipeline's routes don't recognise (what its "
|
||||||
|
"`otherwise` routes took):\n"
|
||||||
|
"a new layout, a study the platform doesn't know, a scan nothing "
|
||||||
|
"could read."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def unrecognised(pipeline: Id) -> Rows:
|
||||||
|
return review.unrecognised(pipeline)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/persons",
|
||||||
|
description=(
|
||||||
|
"Persons to settle (with their possible owners), torn persons "
|
||||||
|
"and persons nothing\n"
|
||||||
|
"names (with their records) left by a pipeline's link node."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def persons(pipeline: Id, node: Id) -> dict[str, Rows]:
|
||||||
|
return review.persons(pipeline, node)
|
||||||
|
|
||||||
|
|
||||||
|
class PersonDecision(BaseModel):
|
||||||
|
person: str
|
||||||
|
candidate: str
|
||||||
|
same: bool
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/persons",
|
||||||
|
status_code=201,
|
||||||
|
description="Whether a person and a possible owner are one patient; applied on the next run.",
|
||||||
|
)
|
||||||
|
def decide_persons(decision: PersonDecision, who: Caller = Depends(caller)) -> dict[str, str]:
|
||||||
|
nodes.decide_persons(decision.person, decision.candidate, decision.same, who.id)
|
||||||
|
return {"person": decision.person}
|
||||||
|
|
||||||
|
|
||||||
|
class Correction(BaseModel):
|
||||||
|
model_config = ConfigDict(
|
||||||
|
json_schema_extra={
|
||||||
|
"description": (
|
||||||
|
"One field of one record as a reviewer read it in the source "
|
||||||
|
"document: an identity\n"
|
||||||
|
"field (a mistyped record number) or a study's (a stage the scan "
|
||||||
|
"made unreadable)."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
entity: EntityName = "identity"
|
||||||
|
record: str
|
||||||
|
field: str
|
||||||
|
value: str
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def _a_valid_value(self):
|
||||||
|
if self.field not in ENTITIES[self.entity].model_fields:
|
||||||
|
raise ValueError(f"{self.entity} has no field {self.field}")
|
||||||
|
reasons = [r for r in validate(self.entity, {self.field: self.value})
|
||||||
|
if r.split(":")[0] == self.field] # fmt: skip
|
||||||
|
if reasons:
|
||||||
|
raise ValueError("; ".join(reasons))
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/corrections",
|
||||||
|
status_code=201,
|
||||||
|
description=(
|
||||||
|
"A corrected field of one record; the next run uses it (linking "
|
||||||
|
"for identity fields,\n"
|
||||||
|
"the study's target for the others). Fixing the source too is "
|
||||||
|
"still worth it."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def correct(fix: Correction, who: Caller = Depends(caller)) -> dict[str, str]:
|
||||||
|
nodes.correct(fix.record, fix.field, fix.value, who.id, fix.entity)
|
||||||
|
return {"record": fix.record}
|
||||||
|
|
||||||
|
|
||||||
|
class Rejection(BaseModel):
|
||||||
|
entity: EntityName
|
||||||
|
record: str
|
||||||
|
reason: str
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/rejections",
|
||||||
|
status_code=201,
|
||||||
|
description="This record's row must not reach silver; applied on the next run.",
|
||||||
|
)
|
||||||
|
def reject(decision: Rejection, who: Caller = Depends(caller)) -> dict[str, str]:
|
||||||
|
nodes.reject(decision.entity, decision.record, decision.reason, who.id)
|
||||||
|
return {"record": decision.record}
|
||||||
+297
@@ -0,0 +1,297 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from typing import Any, Literal
|
||||||
|
|
||||||
|
import requests
|
||||||
|
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
|
from pydantic import BaseModel, ValidationError
|
||||||
|
|
||||||
|
from core.domains import Domain
|
||||||
|
from persistance import cluster
|
||||||
|
from persistance.cluster import Execution, Progress
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/runs", tags=["runs"])
|
||||||
|
|
||||||
|
State = Literal["queued", "running", "succeeded", "failed", "cancelling", "cancelled"]
|
||||||
|
STATE: dict[str, State] = {
|
||||||
|
"QUEUED": "queued",
|
||||||
|
"NOT_STARTED": "queued",
|
||||||
|
"MANAGED": "queued",
|
||||||
|
"STARTING": "running",
|
||||||
|
"STARTED": "running",
|
||||||
|
"CANCELING": "cancelling",
|
||||||
|
"CANCELED": "cancelled",
|
||||||
|
"SUCCESS": "succeeded",
|
||||||
|
"FAILURE": "failed",
|
||||||
|
}
|
||||||
|
|
||||||
|
RUN_QUERY = """
|
||||||
|
query Run($id: ID!, $outputs: Boolean! = false) {
|
||||||
|
runOrError(runId: $id) {
|
||||||
|
__typename
|
||||||
|
... on Run { runId jobName status startTime endTime tags { key value }
|
||||||
|
stepStats { stepKey status startTime endTime } }
|
||||||
|
... on RunNotFoundError { message }
|
||||||
|
... on PythonError { message }
|
||||||
|
}
|
||||||
|
logsForRun(runId: $id, limit: 5000) {
|
||||||
|
__typename
|
||||||
|
... on EventConnection { events { __typename
|
||||||
|
... on MessageEvent { message level stepKey }
|
||||||
|
... on ExecutionStepOutputEvent @include(if: $outputs) {
|
||||||
|
stepKey outputName metadataEntries { label ... on JsonMetadataEntry { jsonString } }
|
||||||
|
}
|
||||||
|
... on ExecutionStepFailureEvent { error { message causes { message } } }
|
||||||
|
... on RunFailureEvent { error { message causes { message } } } } }
|
||||||
|
... on RunNotFoundError { message }
|
||||||
|
... on PythonError { message }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
|
||||||
|
RUNS_QUERY = """
|
||||||
|
query Runs($filter: RunsFilter, $cursor: String, $limit: Int) {
|
||||||
|
runsOrError(filter: $filter, cursor: $cursor, limit: $limit) {
|
||||||
|
__typename
|
||||||
|
... on Runs { results { runId jobName status startTime endTime tags { key value } } }
|
||||||
|
... on InvalidPipelineRunsFilterError { message }
|
||||||
|
... on PythonError { message }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class RunSummary(BaseModel):
|
||||||
|
id: str
|
||||||
|
job: str
|
||||||
|
domain: str | None
|
||||||
|
status: str
|
||||||
|
state: State
|
||||||
|
started: float | None
|
||||||
|
ended: float | None
|
||||||
|
|
||||||
|
|
||||||
|
class Step(BaseModel):
|
||||||
|
key: str
|
||||||
|
status: str
|
||||||
|
started: float | None
|
||||||
|
ended: float | None
|
||||||
|
|
||||||
|
|
||||||
|
class Run(RunSummary):
|
||||||
|
progress: Progress | None
|
||||||
|
steps: list[Step]
|
||||||
|
info: list[str]
|
||||||
|
warnings: list[str]
|
||||||
|
error: str | None
|
||||||
|
outputs: dict[str, Any] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class Cancel(BaseModel):
|
||||||
|
id: str
|
||||||
|
status: str
|
||||||
|
state: State
|
||||||
|
|
||||||
|
|
||||||
|
def _dagster_address() -> tuple[str, int]:
|
||||||
|
return os.environ.get("DAGSTER_HOST", "localhost"), int(os.environ.get("DAGSTER_PORT", "3000"))
|
||||||
|
|
||||||
|
|
||||||
|
def dagster() -> DagsterGraphQLClient:
|
||||||
|
host, port = _dagster_address()
|
||||||
|
return DagsterGraphQLClient(host, port_number=port)
|
||||||
|
|
||||||
|
|
||||||
|
LOCKED = "database is locked"
|
||||||
|
LOCK_RETRIES = 5
|
||||||
|
STARTING_WAIT_S = 30
|
||||||
|
|
||||||
|
|
||||||
|
def _locked(payload: dict) -> bool:
|
||||||
|
results = (payload.get("data") or {}).values()
|
||||||
|
return LOCKED in str(payload.get("errors", "")) or any(
|
||||||
|
isinstance(r, dict)
|
||||||
|
and r.get("__typename") == "PythonError"
|
||||||
|
and LOCKED in r.get("message", "")
|
||||||
|
for r in results
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _graphql_response(url: str, query: str, variables: dict) -> dict:
|
||||||
|
try:
|
||||||
|
response = requests.post(url, json={"query": query, "variables": variables}, timeout=15)
|
||||||
|
if response.status_code != 200:
|
||||||
|
raise HTTPException(502, detail=response.text)
|
||||||
|
return response.json()
|
||||||
|
except requests.RequestException as e:
|
||||||
|
raise HTTPException(502, detail=str(e)) from e
|
||||||
|
|
||||||
|
|
||||||
|
def graphql(query: str, variables: dict) -> dict:
|
||||||
|
host, port = _dagster_address()
|
||||||
|
url = f"http://{host}:{port}/graphql"
|
||||||
|
payload = _graphql_response(url, query, variables)
|
||||||
|
for attempt in range(LOCK_RETRIES):
|
||||||
|
if not _locked(payload):
|
||||||
|
break
|
||||||
|
time.sleep(0.2 * 2**attempt)
|
||||||
|
payload = _graphql_response(url, query, variables)
|
||||||
|
if _locked(payload):
|
||||||
|
raise HTTPException(
|
||||||
|
503, detail="Dagster's run storage is busy; try again", headers={"Retry-After": "5"}
|
||||||
|
)
|
||||||
|
if "errors" in payload:
|
||||||
|
raise HTTPException(502, detail=str(payload["errors"]))
|
||||||
|
return payload["data"]
|
||||||
|
|
||||||
|
|
||||||
|
def _tags(run: dict) -> dict[str, str]:
|
||||||
|
return {tag["key"]: tag["value"] for tag in run.get("tags", [])}
|
||||||
|
|
||||||
|
|
||||||
|
def _summary(run: dict) -> RunSummary:
|
||||||
|
status = run["status"]
|
||||||
|
return RunSummary(
|
||||||
|
id=run["runId"],
|
||||||
|
job=run["jobName"],
|
||||||
|
domain=_tags(run).get("domain"),
|
||||||
|
status=status,
|
||||||
|
state=STATE.get(status, "running"),
|
||||||
|
started=run.get("startTime"),
|
||||||
|
ended=run.get("endTime"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def shape(run: dict, logs: list[dict], outputs: bool = False) -> Run:
|
||||||
|
summary = _summary(run)
|
||||||
|
progress = None
|
||||||
|
if (tag := _tags(run).get("isssteleon/progress")) is not None:
|
||||||
|
try:
|
||||||
|
progress = Progress.model_validate_json(tag)
|
||||||
|
except ValidationError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
steps = [
|
||||||
|
Step(
|
||||||
|
key=step["stepKey"],
|
||||||
|
status=step["status"],
|
||||||
|
started=step.get("startTime"),
|
||||||
|
ended=step.get("endTime"),
|
||||||
|
)
|
||||||
|
for step in run.get("stepStats", [])
|
||||||
|
]
|
||||||
|
steps.sort(key=lambda step: (step.started is None, step.started or 0.0))
|
||||||
|
|
||||||
|
info, warnings = [], []
|
||||||
|
error = None
|
||||||
|
result = {} if outputs else None
|
||||||
|
for event in logs:
|
||||||
|
kind = event["__typename"]
|
||||||
|
if kind == "LogMessageEvent" and event["level"] in ("INFO", "WARNING"):
|
||||||
|
line = event["message"]
|
||||||
|
if step_key := event.get("stepKey"):
|
||||||
|
line = f"{step_key}: {line}"
|
||||||
|
(info if event["level"] == "INFO" else warnings).append(line)
|
||||||
|
if result is not None and kind == "ExecutionStepOutputEvent":
|
||||||
|
for entry in event.get("metadataEntries", ()):
|
||||||
|
if "jsonString" in entry:
|
||||||
|
result[f"{event['stepKey']}.{entry['label']}"] = json.loads(entry["jsonString"])
|
||||||
|
if summary.state == "failed" and kind in ("ExecutionStepFailureEvent", "RunFailureEvent"):
|
||||||
|
failure = event.get("error")
|
||||||
|
error = None
|
||||||
|
if failure:
|
||||||
|
causes = failure.get("causes")
|
||||||
|
message = (causes[-1] if causes else failure)["message"]
|
||||||
|
lines = message.strip().splitlines()
|
||||||
|
error = lines[0][:500] if lines else None
|
||||||
|
|
||||||
|
return Run(
|
||||||
|
**summary.model_dump(),
|
||||||
|
progress=progress,
|
||||||
|
outputs=result,
|
||||||
|
steps=steps,
|
||||||
|
info=info[-200:],
|
||||||
|
warnings=warnings[:200],
|
||||||
|
error=(error or "the run failed") if summary.state == "failed" else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _result(result: dict, typename: str) -> dict:
|
||||||
|
if result["__typename"] != typename:
|
||||||
|
status = 404 if result["__typename"] == "RunNotFoundError" else 502
|
||||||
|
raise HTTPException(status, detail=result.get("message", result["__typename"]))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{run_id}")
|
||||||
|
def run_status(run_id: str, outputs: bool = False) -> Run:
|
||||||
|
data = graphql(RUN_QUERY, {"id": run_id, "outputs": outputs})
|
||||||
|
run = _result(data["runOrError"], "Run")
|
||||||
|
logs = _result(data["logsForRun"], "EventConnection")
|
||||||
|
return shape(run, logs["events"], outputs)
|
||||||
|
|
||||||
|
|
||||||
|
def _status(client: DagsterGraphQLClient, run_id: str) -> str:
|
||||||
|
try:
|
||||||
|
return client.get_run_status(run_id).value
|
||||||
|
except DagsterGraphQLClientError as e:
|
||||||
|
raise HTTPException(404 if e.args[0] == "RunNotFoundError" else 502, detail=str(e)) from e
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{run_id}/cancel")
|
||||||
|
def cancel_run(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> Cancel:
|
||||||
|
status = _status(client, run_id)
|
||||||
|
deadline = time.monotonic() + STARTING_WAIT_S
|
||||||
|
while status == "STARTING" and time.monotonic() < deadline:
|
||||||
|
time.sleep(0.5)
|
||||||
|
status = _status(client, run_id)
|
||||||
|
if status in ("SUCCESS", "FAILURE", "CANCELED"):
|
||||||
|
raise HTTPException(409, detail=f"the run already ended: {STATE[status]}")
|
||||||
|
if status == "STARTING":
|
||||||
|
raise HTTPException(
|
||||||
|
409, detail="the run is still starting; try again", headers={"Retry-After": "5"}
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
client.terminate_run(run_id)
|
||||||
|
except DagsterGraphQLClientError as e:
|
||||||
|
raise HTTPException(502, detail=str(e)) from e
|
||||||
|
status = _status(client, run_id)
|
||||||
|
return Cancel(id=run_id, status=status, state=STATE.get(status, "running"))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def run_history(
|
||||||
|
job: str | None = None,
|
||||||
|
domain: Domain | None = None,
|
||||||
|
limit: int = Query(50, ge=1, le=200),
|
||||||
|
before: str | None = None,
|
||||||
|
) -> list[RunSummary]:
|
||||||
|
filters = {}
|
||||||
|
if job is not None:
|
||||||
|
filters["pipelineName"] = job
|
||||||
|
if domain is not None:
|
||||||
|
filters["tags"] = [{"key": "domain", "value": domain.value}]
|
||||||
|
data = graphql(RUNS_QUERY, {"filter": filters, "cursor": before, "limit": limit})
|
||||||
|
return [_summary(run) for run in _result(data["runsOrError"], "Runs")["results"]]
|
||||||
|
|
||||||
|
|
||||||
|
def submit(
|
||||||
|
client: DagsterGraphQLClient, job: str, op: str, config: dict, domain: str
|
||||||
|
) -> dict[str, str]:
|
||||||
|
try:
|
||||||
|
run_id = client.submit_job_execution(
|
||||||
|
job, run_config={"ops": {op: {"config": config}}}, tags={"domain": domain}
|
||||||
|
)
|
||||||
|
except DagsterGraphQLClientError as e:
|
||||||
|
raise HTTPException(502, detail=str(e)) from e
|
||||||
|
return {"run_id": run_id}
|
||||||
|
|
||||||
|
|
||||||
|
def execution_config(choice: Execution | None) -> dict:
|
||||||
|
try:
|
||||||
|
resolved = cluster.resolve(choice)
|
||||||
|
except cluster.ExecutionError as e:
|
||||||
|
raise HTTPException(422, detail=str(e)) from e
|
||||||
|
return {"mode": resolved.mode, "scheduler": resolved.scheduler}
|
||||||
@@ -0,0 +1,369 @@
|
|||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path, PurePosixPath
|
||||||
|
from typing import Annotated, Any, Literal
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Form, HTTPException, Query, UploadFile
|
||||||
|
from pydantic import BaseModel, ValidationError
|
||||||
|
|
||||||
|
from core import sources
|
||||||
|
from core.pipeline import MASK, Pipeline, Source, restored
|
||||||
|
from persistance import config_log, nodes
|
||||||
|
from persistance.config import DATA_DIR
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/ingest", tags=["ingest"])
|
||||||
|
UPLOADS = "uploads"
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/sources/types",
|
||||||
|
description="Every kind of source the dialog offers, grouped, with the fields each one asks.",
|
||||||
|
)
|
||||||
|
def source_types() -> sources.Catalog:
|
||||||
|
return sources.catalog()
|
||||||
|
|
||||||
|
|
||||||
|
class Answers(BaseModel):
|
||||||
|
type: str
|
||||||
|
answers: dict[str, Any] = {}
|
||||||
|
pipeline: str | None = None
|
||||||
|
node: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class Tested(BaseModel):
|
||||||
|
ok: bool
|
||||||
|
message: str
|
||||||
|
detail: str | None = None
|
||||||
|
tables: list[str] = []
|
||||||
|
rows: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
|
||||||
|
PLAIN = [
|
||||||
|
(
|
||||||
|
r"login failed|password authentication failed|access denied|authentication|"
|
||||||
|
r"401|403|permission denied|invalid credentials",
|
||||||
|
"El usuario o la contraseña no son correctos, o no tiene permiso.",
|
||||||
|
), # fmt: skip
|
||||||
|
(
|
||||||
|
r"name or service not known|could not translate host|nodename nor servname|"
|
||||||
|
r"getaddrinfo|unknown host|no such host|resolve",
|
||||||
|
"No se encontró el servidor. Revise el nombre o la dirección.",
|
||||||
|
), # fmt: skip
|
||||||
|
(
|
||||||
|
r"timed out|timeout|connection refused|unable to connect|adaptive server is unavailable|"
|
||||||
|
r"could not connect|connection reset",
|
||||||
|
"El servidor no respondió. Revise la dirección, el puerto o si está encendido.",
|
||||||
|
), # fmt: skip
|
||||||
|
(
|
||||||
|
r"database .* does not exist|cannot open database|unknown database",
|
||||||
|
"No existe esa base de datos en el servidor.",
|
||||||
|
), # fmt: skip
|
||||||
|
(
|
||||||
|
r"no such table|invalid object name|does not exist|not found|no such file|404",
|
||||||
|
"No se encontró lo que pidió (la tabla, la carpeta o el archivo).",
|
||||||
|
), # fmt: skip
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def plain(error: BaseException) -> str:
|
||||||
|
said = f"{type(error).__name__}: {error}"
|
||||||
|
for pattern, message in PLAIN:
|
||||||
|
if re.search(pattern, said, re.IGNORECASE):
|
||||||
|
return message
|
||||||
|
return "No se pudo conectar. Abajo está lo que respondió el sistema."
|
||||||
|
|
||||||
|
|
||||||
|
def _with_saved_secrets(asked: Answers) -> dict[str, Any]:
|
||||||
|
if MASK not in repr(asked.answers):
|
||||||
|
return asked.answers
|
||||||
|
if not (asked.pipeline and asked.node and config_log.latest_version(asked.pipeline)):
|
||||||
|
raise HTTPException(422, detail="una contraseña oculta necesita la fuente guardada")
|
||||||
|
saved = config_log.get(asked.pipeline)[1]
|
||||||
|
node = {"id": asked.node, "kind": "source", "source": "core.sources:catalog",
|
||||||
|
"guided": {"type": asked.type, "answers": asked.answers}} # fmt: skip
|
||||||
|
try:
|
||||||
|
found = restored(Pipeline(nodes=[node]), saved).nodes[0]
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(422, detail=str(e)) from e
|
||||||
|
return found.guided.answers
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/sources/test",
|
||||||
|
description=(
|
||||||
|
'"Probar conexión": reaches the source with the answers given. A '
|
||||||
|
"database lists its\n"
|
||||||
|
"tables (until one is picked; then its first rows); files and "
|
||||||
|
"records show their first\n"
|
||||||
|
"rows. Never a server error: what went wrong comes back in plain "
|
||||||
|
"words."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def test_source(asked: Answers, limit: Annotated[int, Query(ge=1, le=100)] = 20) -> Tested:
|
||||||
|
if asked.type not in sources.catalog().types:
|
||||||
|
raise HTTPException(404, detail=f"no source type {asked.type}")
|
||||||
|
answers = _with_saved_secrets(asked)
|
||||||
|
spec = sources.catalog().types[asked.type]
|
||||||
|
picked = all(answers.get(k) for k, f in spec.fields.items() if f.type == "table")
|
||||||
|
try:
|
||||||
|
if not picked and (listed := sources.listing(asked.type, answers)):
|
||||||
|
tables = nodes.resources(*listed)
|
||||||
|
count = "1 tabla" if len(tables) == 1 else f"{len(tables)} tablas"
|
||||||
|
return Tested(ok=True, message=f"Conexión correcta: {count}.",
|
||||||
|
tables=tables) # fmt: skip
|
||||||
|
node = Source(id="probe", guided={"type": asked.type, "answers": answers})
|
||||||
|
rows = [nodes.shown(r) for r in nodes.preview(node, limit)]
|
||||||
|
except (sources.MissingAnswer, ValidationError) as e:
|
||||||
|
return Tested(ok=False, message=_missing(e))
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
return Tested(ok=False, message=plain(e), detail=f"{type(e).__name__}: {e}"[:2000])
|
||||||
|
found = (
|
||||||
|
"Conexión correcta."
|
||||||
|
if rows
|
||||||
|
else (
|
||||||
|
"Se conectó, pero no encontró archivos ni filas. Revise la ruta y qué archivos tomar."
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return Tested(ok=True, message=found, rows=rows)
|
||||||
|
|
||||||
|
|
||||||
|
def _missing(e: Exception) -> str:
|
||||||
|
if isinstance(e, ValidationError):
|
||||||
|
return next((str(err["ctx"]["error"]) for err in e.errors()
|
||||||
|
if isinstance(err.get("ctx", {}).get("error"), sources.MissingAnswer)),
|
||||||
|
str(e)) # fmt: skip
|
||||||
|
return str(e)
|
||||||
|
|
||||||
|
|
||||||
|
def roots() -> dict[str, Path]:
|
||||||
|
found = {"Subidos": (DATA_DIR / UPLOADS).resolve()}
|
||||||
|
for raw in filter(None, os.environ.get("SOURCE_ROOTS", "").split(os.pathsep)):
|
||||||
|
path = Path(raw).resolve()
|
||||||
|
found[path.name or str(path)] = path
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
class Entry(BaseModel):
|
||||||
|
name: str
|
||||||
|
path: str
|
||||||
|
kind: Literal["folder", "file"]
|
||||||
|
size: int | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class Browsed(BaseModel):
|
||||||
|
path: str | None
|
||||||
|
parent: str | None
|
||||||
|
entries: list[Entry]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/sources/browse",
|
||||||
|
description=(
|
||||||
|
"The server folders a source may read: the roots, or what one "
|
||||||
|
"folder under them\n"
|
||||||
|
"holds. Nothing outside the roots is shown."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def browse(path: str | None = None) -> Browsed:
|
||||||
|
allowed = roots()
|
||||||
|
if path is None:
|
||||||
|
return Browsed(path=None, parent=None, entries=[
|
||||||
|
Entry(name=name, path=str(root), kind="folder")
|
||||||
|
for name, root in allowed.items() if root.is_dir()]) # fmt: skip
|
||||||
|
folder = Path(path).resolve()
|
||||||
|
root = next((r for r in allowed.values() if folder == r or r in folder.parents), None)
|
||||||
|
if root is None or not folder.is_dir():
|
||||||
|
raise HTTPException(404, detail="esa carpeta no está entre las habilitadas")
|
||||||
|
entries = sorted(
|
||||||
|
(Entry(name=p.name, path=str(p), kind="folder" if p.is_dir() else "file",
|
||||||
|
size=None if p.is_dir() else p.stat().st_size)
|
||||||
|
for p in folder.iterdir() if not p.name.startswith(".")),
|
||||||
|
key=lambda e: (e.kind != "folder", e.name.lower())) # fmt: skip
|
||||||
|
return Browsed(path=str(folder), parent=None if folder == root else str(folder.parent),
|
||||||
|
entries=entries) # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
class Uploaded(BaseModel):
|
||||||
|
bucket_url: str
|
||||||
|
files: list[str]
|
||||||
|
|
||||||
|
|
||||||
|
def _relative(name: str) -> PurePosixPath:
|
||||||
|
parts = [p for p in PurePosixPath(name.replace("\\", "/")).parts if p not in ("", ".", "..")]
|
||||||
|
if not parts:
|
||||||
|
raise HTTPException(422, detail="the file needs a name")
|
||||||
|
return PurePosixPath(*parts)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/uploads",
|
||||||
|
description=(
|
||||||
|
"Files from the operator's computer (one, many, or a whole "
|
||||||
|
"folder), kept on the\n"
|
||||||
|
"server for a `filesystem` source; streamed to disk, so large "
|
||||||
|
"recordings fit. Send\n"
|
||||||
|
"`folder` from a previous answer to add to the same set."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def upload(files: list[UploadFile], folder: Annotated[str | None, Form()] = None) -> Uploaded:
|
||||||
|
base = (DATA_DIR / UPLOADS).resolve()
|
||||||
|
target = Path(folder).resolve() if folder else base / uuid.uuid4().hex[:12]
|
||||||
|
if target.parent != base:
|
||||||
|
raise HTTPException(422, detail="folder is not an upload set")
|
||||||
|
kept = []
|
||||||
|
for file in files:
|
||||||
|
relative = _relative(file.filename or "")
|
||||||
|
destination = target / relative
|
||||||
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with destination.open("wb") as out:
|
||||||
|
shutil.copyfileobj(file.file, out, length=1 << 20)
|
||||||
|
kept.append(str(relative))
|
||||||
|
return Uploaded(bucket_url=str(target), files=kept)
|
||||||
|
|
||||||
|
|
||||||
|
PENDING = DATA_DIR / "oauth_pending"
|
||||||
|
PENDING_SECONDS = 600
|
||||||
|
STATE = re.compile(r"[A-Za-z0-9_-]{8,128}")
|
||||||
|
|
||||||
|
|
||||||
|
def _pend(state: str, pending: dict[str, Any]) -> None:
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
|
||||||
|
PENDING.mkdir(parents=True, exist_ok=True)
|
||||||
|
for old in PENDING.glob("*.json"):
|
||||||
|
if time.time() - old.stat().st_mtime > PENDING_SECONDS:
|
||||||
|
old.unlink(missing_ok=True)
|
||||||
|
path = PENDING / f"{state}.json"
|
||||||
|
path.write_text(json.dumps(pending))
|
||||||
|
path.chmod(0o600)
|
||||||
|
|
||||||
|
|
||||||
|
def _claimed(state: str) -> dict[str, Any] | None:
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
|
||||||
|
if not STATE.fullmatch(state):
|
||||||
|
return None
|
||||||
|
taken = PENDING / f"{state}.{uuid.uuid4().hex}.taken"
|
||||||
|
try:
|
||||||
|
(PENDING / f"{state}.json").rename(taken)
|
||||||
|
except FileNotFoundError:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
fresh = time.time() - taken.stat().st_mtime <= PENDING_SECONDS
|
||||||
|
return json.loads(taken.read_text()) if fresh else None
|
||||||
|
finally:
|
||||||
|
taken.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _registration(provider: str) -> tuple[sources.Provider, dict[str, str]]:
|
||||||
|
found = sources.catalog().providers.get(provider)
|
||||||
|
if found is None:
|
||||||
|
raise HTTPException(404, detail=f"no provider {provider}")
|
||||||
|
env = {k: os.environ.get(f"{found.env}_{k.upper()}", "")
|
||||||
|
for k in ("client_id", "client_secret", "tenant_id", "project_id")} # fmt: skip
|
||||||
|
if not (env["client_id"] and env["client_secret"]):
|
||||||
|
needed = f"{found.env}_CLIENT_ID y {found.env}_CLIENT_SECRET"
|
||||||
|
raise HTTPException(503, detail=(
|
||||||
|
f"Para iniciar sesión con {found.title}, el área de sistemas debe registrar la "
|
||||||
|
f"aplicación y darle al servidor {needed}.")) # fmt: skip
|
||||||
|
return found, env
|
||||||
|
|
||||||
|
|
||||||
|
def _endpoint(url: str, env: dict[str, str]) -> str:
|
||||||
|
return url.format(tenant=env["tenant_id"] or "organizations")
|
||||||
|
|
||||||
|
|
||||||
|
def _client(provider: sources.Provider, env: dict[str, str], redirect_uri: str):
|
||||||
|
from authlib.integrations.httpx_client import OAuth2Client
|
||||||
|
|
||||||
|
return OAuth2Client(env["client_id"], env["client_secret"], scope=provider.scope,
|
||||||
|
redirect_uri=redirect_uri, code_challenge_method="S256") # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
class SignIn(BaseModel):
|
||||||
|
url: str
|
||||||
|
state: str
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/sources/oauth/{provider}/start",
|
||||||
|
description=(
|
||||||
|
"The provider's sign-in address. `origin` is the web app's "
|
||||||
|
"(where the user returns:\n"
|
||||||
|
"`{origin}/api/…/callback`, the address IT registered)."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def oauth_start(provider: str, origin: str) -> SignIn:
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
found, env = _registration(provider)
|
||||||
|
redirect_uri = f"{origin.rstrip('/')}/api/ingest/sources/oauth/{provider}/callback"
|
||||||
|
verifier = secrets.token_urlsafe(48)
|
||||||
|
url, state = _client(found, env, redirect_uri).create_authorization_url(
|
||||||
|
_endpoint(found.authorize_url, env), code_verifier=verifier, **found.authorize_params
|
||||||
|
)
|
||||||
|
_pend(state, {"provider": provider, "verifier": verifier, "redirect_uri": redirect_uri,
|
||||||
|
"origin": origin.rstrip("/")}) # fmt: skip
|
||||||
|
return SignIn(url=url, state=state)
|
||||||
|
|
||||||
|
|
||||||
|
def account(provider: str, token: dict[str, Any], env: dict[str, str]) -> dict[str, Any]:
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
found = sources.catalog().providers[provider]
|
||||||
|
bearer = {"Authorization": f"Bearer {token['access_token']}"}
|
||||||
|
if provider == "microsoft":
|
||||||
|
me = httpx.get("https://graph.microsoft.com/v1.0/me", headers=bearer).json()
|
||||||
|
drive = httpx.get("https://graph.microsoft.com/v1.0/me/drive", headers=bearer).json()
|
||||||
|
return {
|
||||||
|
"user": me.get("mail") or me.get("userPrincipalName") or me.get("displayName"),
|
||||||
|
"drive_id": drive.get("id"),
|
||||||
|
"oauth2_client_params": {
|
||||||
|
"client_id": env["client_id"], "client_secret": env["client_secret"],
|
||||||
|
"token_endpoint": _endpoint(found.token_url, env), "scope": found.scope,
|
||||||
|
"token": token,
|
||||||
|
},
|
||||||
|
} # fmt: skip
|
||||||
|
about = httpx.get("https://www.googleapis.com/drive/v3/about", params={"fields": "user"},
|
||||||
|
headers=bearer).json() # fmt: skip
|
||||||
|
credentials = {"client_id": env["client_id"], "client_secret": env["client_secret"],
|
||||||
|
"refresh_token": token.get("refresh_token"),
|
||||||
|
"project_id": env["project_id"] or None} # fmt: skip
|
||||||
|
return {"user": about.get("user", {}).get("emailAddress"),
|
||||||
|
"credentials": {k: v for k, v in credentials.items() if v}} # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/sources/oauth/{provider}/callback", include_in_schema=False)
|
||||||
|
def oauth_callback(provider: str, state: str, code: str | None = None, error: str | None = None):
|
||||||
|
import json
|
||||||
|
|
||||||
|
from fastapi.responses import HTMLResponse
|
||||||
|
|
||||||
|
pending = _claimed(state)
|
||||||
|
if pending is None or pending["provider"] != provider:
|
||||||
|
return HTMLResponse("<p>La solicitud de inicio de sesión venció. Cierre esta ventana "
|
||||||
|
"e inténtelo de nuevo.</p>", status_code=400) # fmt: skip
|
||||||
|
message: dict[str, Any] = {"type": "isssteleon-oauth", "state": state}
|
||||||
|
if error or not code:
|
||||||
|
message["error"] = "No se completó el inicio de sesión."
|
||||||
|
else:
|
||||||
|
found, env = _registration(provider)
|
||||||
|
try:
|
||||||
|
token = _client(found, env, pending["redirect_uri"]).fetch_token(
|
||||||
|
_endpoint(found.token_url, env), code=code, code_verifier=pending["verifier"]
|
||||||
|
)
|
||||||
|
message["account"] = account(provider, dict(token), env)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
message["error"] = f"No se pudo iniciar sesión: {e}"
|
||||||
|
payload = json.dumps(message).replace("</", "<\\/")
|
||||||
|
target = json.dumps(pending["origin"])
|
||||||
|
return HTMLResponse(
|
||||||
|
"<!doctype html><meta charset=utf-8><title>ISSSTELEON</title>"
|
||||||
|
"<p>Listo. Puede cerrar esta ventana.</p>"
|
||||||
|
f"<script>window.opener&&window.opener.postMessage({payload},{target});"
|
||||||
|
"window.close()</script>"
|
||||||
|
)
|
||||||
+153
@@ -0,0 +1,153 @@
|
|||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
import uuid
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from functools import cache
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, FastAPI
|
||||||
|
from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin, schemas
|
||||||
|
from fastapi_users.authentication import AuthenticationBackend, CookieTransport, JWTStrategy
|
||||||
|
from fastapi_users.exceptions import UserAlreadyExists
|
||||||
|
from fastapi_users_db_sqlalchemy import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
|
||||||
|
from sqlalchemy import JSON, String, event, make_url, text
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||||
|
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||||
|
|
||||||
|
from core.domains import Domain
|
||||||
|
from persistance.config import DATA_DIR, platform_url
|
||||||
|
|
||||||
|
SESSION_HOURS = 10
|
||||||
|
SCHEMA = "config"
|
||||||
|
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class User(SQLAlchemyBaseUserTableUUID, Base):
|
||||||
|
__tablename__ = "users"
|
||||||
|
__table_args__ = {"schema": SCHEMA}
|
||||||
|
name: Mapped[str] = mapped_column(String(120), default="")
|
||||||
|
domains: Mapped[list[str]] = mapped_column(JSON, default=list)
|
||||||
|
|
||||||
|
|
||||||
|
class UserRead(schemas.BaseUser[uuid.UUID]):
|
||||||
|
name: str = ""
|
||||||
|
domains: list[Domain] = []
|
||||||
|
|
||||||
|
|
||||||
|
class UserCreate(schemas.BaseUserCreate):
|
||||||
|
name: str = ""
|
||||||
|
domains: list[Domain] = []
|
||||||
|
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def _engine():
|
||||||
|
url = make_url(platform_url())
|
||||||
|
if url.drivername.startswith("sqlite"):
|
||||||
|
engine = create_async_engine(url.set(drivername="sqlite+aiosqlite"))
|
||||||
|
|
||||||
|
@event.listens_for(engine.sync_engine, "connect")
|
||||||
|
def _attach(connection, _record):
|
||||||
|
path = DATA_DIR / f"platform__{SCHEMA}.db"
|
||||||
|
connection.execute(f"ATTACH DATABASE '{path}' AS {SCHEMA}")
|
||||||
|
|
||||||
|
return engine
|
||||||
|
return create_async_engine(url.set(drivername="postgresql+asyncpg"))
|
||||||
|
|
||||||
|
|
||||||
|
async def _session() -> AsyncIterator[AsyncSession]:
|
||||||
|
async with async_sessionmaker(_engine(), expire_on_commit=False)() as session:
|
||||||
|
yield session
|
||||||
|
|
||||||
|
|
||||||
|
async def _users(session: AsyncSession = Depends(_session)):
|
||||||
|
yield SQLAlchemyUserDatabase(session, User)
|
||||||
|
|
||||||
|
|
||||||
|
@cache
|
||||||
|
def _secret() -> str:
|
||||||
|
if found := os.environ.get("AUTH_SECRET"):
|
||||||
|
return found
|
||||||
|
path = DATA_DIR / "auth_secret"
|
||||||
|
if not path.exists():
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_text(secrets.token_urlsafe(48))
|
||||||
|
path.chmod(0o600)
|
||||||
|
return path.read_text().strip()
|
||||||
|
|
||||||
|
|
||||||
|
class Manager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
||||||
|
@property
|
||||||
|
def reset_password_token_secret(self) -> str: # type: ignore[override]
|
||||||
|
return _secret()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def verification_token_secret(self) -> str: # type: ignore[override]
|
||||||
|
return _secret()
|
||||||
|
|
||||||
|
|
||||||
|
async def _manager(users=Depends(_users)):
|
||||||
|
yield Manager(users)
|
||||||
|
|
||||||
|
|
||||||
|
backend = AuthenticationBackend(
|
||||||
|
name="cookie",
|
||||||
|
transport=CookieTransport(
|
||||||
|
cookie_name="isssteleon_session",
|
||||||
|
cookie_max_age=SESSION_HOURS * 3600,
|
||||||
|
cookie_secure=os.environ.get("AUTH_COOKIE_SECURE", "") == "1",
|
||||||
|
cookie_samesite="lax",
|
||||||
|
),
|
||||||
|
get_strategy=lambda: JWTStrategy(secret=_secret(), lifetime_seconds=SESSION_HOURS * 3600),
|
||||||
|
)
|
||||||
|
users = FastAPIUsers[User, uuid.UUID](_manager, [backend])
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
router.include_router(users.get_auth_router(backend), prefix="/auth", tags=["auth"])
|
||||||
|
user_routes = users.get_users_router(UserRead, schemas.BaseUserUpdate)
|
||||||
|
user_routes.routes[:] = [
|
||||||
|
route for route in user_routes.routes if route.name == "users:current_user"
|
||||||
|
]
|
||||||
|
router.include_router(user_routes, prefix="/users", tags=["users"])
|
||||||
|
admins_only = [Depends(users.current_user(active=True, superuser=True))]
|
||||||
|
router.include_router(
|
||||||
|
users.get_register_router(UserRead, UserCreate),
|
||||||
|
prefix="/users",
|
||||||
|
tags=["users"],
|
||||||
|
dependencies=admins_only,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def first_admin() -> None:
|
||||||
|
async with _engine().begin() as connection:
|
||||||
|
if connection.dialect.name != "sqlite":
|
||||||
|
await connection.execute(text(f"create schema if not exists {SCHEMA}"))
|
||||||
|
await connection.run_sync(Base.metadata.create_all)
|
||||||
|
email, password = os.environ.get("AUTH_ADMIN_EMAIL"), os.environ.get("AUTH_ADMIN_PASSWORD")
|
||||||
|
if not (email and password):
|
||||||
|
return
|
||||||
|
async with async_sessionmaker(_engine(), expire_on_commit=False)() as session:
|
||||||
|
manager = Manager(SQLAlchemyUserDatabase(session, User))
|
||||||
|
try:
|
||||||
|
admin = UserCreate(email=email, password=password, is_superuser=True,
|
||||||
|
name="Administrador", domains=list(Domain)) # fmt: skip
|
||||||
|
await manager.create(admin)
|
||||||
|
except UserAlreadyExists:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
||||||
|
import fcntl
|
||||||
|
|
||||||
|
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
with open(DATA_DIR / "startup.lock", "w") as lock:
|
||||||
|
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||||
|
try:
|
||||||
|
_secret()
|
||||||
|
await first_admin()
|
||||||
|
finally:
|
||||||
|
fcntl.flock(lock, fcntl.LOCK_UN)
|
||||||
|
yield
|
||||||
Reference in New Issue
Block a user