Compare commits

..

2 Commits

Author SHA1 Message Date
Roberto Treviño b0d361a47d ISSSTELEON 2fe5301 2026-12-01 09:59:53 -06:00
Roberto Treviño 510000658b ISSSTELEON WebApi 2026-11-29 18:11:42 -06:00
21 changed files with 495 additions and 1893 deletions
+3 -1
View File
@@ -1,2 +1,4 @@
__pycache__/ __pycache__/
.pytest_cache/ node_modules/
dist/
.angular/
-1
View File
@@ -12,7 +12,6 @@ dependencies = [
"fastapi-users[sqlalchemy]>=15", "fastapi-users[sqlalchemy]>=15",
"aiosqlite>=0.20", "aiosqlite>=0.20",
"asyncpg>=0.30", "asyncpg>=0.30",
"requests",
] ]
[build-system] [build-system]
-37
View File
@@ -1,37 +0,0 @@
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()
-161
View File
@@ -1,161 +0,0 @@
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"}}}
)
-140
View File
@@ -1,140 +0,0 @@
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"
)
-110
View File
@@ -1,110 +0,0 @@
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"}
-46
View File
@@ -1,46 +0,0 @@
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
-178
View File
@@ -1,178 +0,0 @@
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("/tea/eegs/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("/tea/eegs/analyze", json={}))["run_id"])
@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
View File
@@ -0,0 +1 @@
+32 -28
View File
@@ -1,12 +1,6 @@
from typing import Any from fastapi import APIRouter, HTTPException
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel from pydantic import BaseModel
from persistance import eeg 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"]) router = APIRouter(prefix="/tea/eegs", tags=["eeg"])
@@ -21,12 +15,42 @@ class Study(BaseModel):
level: str | None level: str | None
class Site(BaseModel):
site: str
value: float
z: float | None
class Metric(BaseModel): class Metric(BaseModel):
code: str code: str
value: float value: float
z: float | None z: float | None
outside: float | None outside: float | None
p5: float | None = None
median: float | None = None
p95: float | None = None
model: str | None model: str | None
zones: list[Site] = []
electrodes: list[Site] = []
class Relation(BaseModel):
biomarker: str
metric: str
zone: str
outcome_code: str
kind: str
event: str
z: float
probability: float
reference_probability: float
observed: float | None = None
odds_ratio: float
ci_low: float | None
ci_high: float | None
q: float | None
n: float
model: str
class Analysis(BaseModel): class Analysis(BaseModel):
@@ -35,13 +59,7 @@ class Analysis(BaseModel):
level: str | None level: str | None
age_months: float | None age_months: float | None
metrics: list[Metric] metrics: list[Metric]
checks: list[dict[str, Any]] relation: list[Relation] = []
regions: list[dict[str, Any]]
class AnalyzeRequest(BaseModel):
scope: Scope = Scope()
execution: Execution | None = None
@router.get("") @router.get("")
@@ -49,20 +67,6 @@ def studies() -> list[Study]:
return [Study(**s) for s in eeg.studies()] 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}") @router.get("/{eeg_id}")
def study(eeg_id: str) -> Analysis: def study(eeg_id: str) -> Analysis:
if (found := eeg.study(eeg_id)) is None: if (found := eeg.study(eeg_id)) is None:
-21
View File
@@ -1,21 +0,0 @@
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
+233 -382
View File
@@ -1,26 +1,20 @@
import operator
import unicodedata import unicodedata
from collections import defaultdict
from datetime import date, datetime from datetime import date, datetime
from typing import Annotated, Any from typing import Annotated, Any
from urllib.parse import urlencode
from dagster_graphql import DagsterGraphQLClient from dagster_graphql import DagsterGraphQLClient
from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request
from fastapi.responses import Response from fastapi.responses import Response
from fhir.resources.R4B.bundle import Bundle from fhir.resources.R4B.bundle import Bundle
from fhir.resources.R4B.capabilitystatement import CapabilityStatement from fhir.resources.R4B.capabilitystatement import CapabilityStatement
from fhir.resources.R4B.operationoutcome import OperationOutcome from fhir.resources.R4B.operationoutcome import OperationOutcome
from fhir.resources.R4B.parameters import Parameters
from fhir.resources.R4B.resource import Resource from fhir.resources.R4B.resource import Resource
from core import catalog from core import catalog
from core import fhir as f from core import fhir as f
from core import measures as m from core import measures as m
from core.domains import Domain, measures, part from core.domains import Domain, measures, part
from core.follow_up import window_start from core.follow_up import window_start
from core.pipeline import ID_PATTERN 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 config_log, readers
from persistance import fhir as reads from persistance import fhir as reads
from persistance import measures as measure_reads from persistance import measures as measure_reads
@@ -28,9 +22,8 @@ from webapi.ingest import submit
from webapi.runs import dagster from webapi.runs import dagster
FHIR_JSON = "application/fhir+json" FHIR_JSON = "application/fhir+json"
PAGE, MAX_PAGE = 50, 200 PAGE, MAX_PAGE = (50, 200)
REVINCLUDES = ("DiagnosticReport:subject", "RiskAssessment:subject", "Observation:subject") REVINCLUDES = ("DiagnosticReport:subject", "RiskAssessment:subject", "Observation:subject")
router = APIRouter(prefix="/{domain}/fhir", tags=["fhir"]) router = APIRouter(prefix="/{domain}/fhir", tags=["fhir"])
_OK = {200: {"content": {FHIR_JSON: {"schema": {"type": "object"}}}, "description": "FHIR"}} _OK = {200: {"content": {FHIR_JSON: {"schema": {"type": "object"}}}, "description": "FHIR"}}
@@ -40,10 +33,16 @@ def fhir(resource: Resource) -> Response:
def outcome(status: int, text: str) -> Response: def outcome(status: int, text: str) -> Response:
issue = {"severity": "error", "code": "not-found" if status == 404 else "invalid", issue = {
"diagnostics": text} # fmt: skip "severity": "error",
return Response(OperationOutcome(issue=[issue]).model_dump_json(exclude_none=True), "code": "not-found" if status == 404 else "invalid",
status_code=status, media_type=FHIR_JSON) # fmt: skip "diagnostics": text,
}
return Response(
OperationOutcome(issue=[issue]).model_dump_json(exclude_none=True),
status_code=status,
media_type=FHIR_JSON,
)
def _clinical(domain: Domain): def _clinical(domain: Domain):
@@ -62,17 +61,22 @@ def _page(count: int | None, offset: int) -> tuple[int, int]:
count = PAGE if count is None else count count = PAGE if count is None else count
if not 0 <= count <= MAX_PAGE or offset < 0: if not 0 <= count <= MAX_PAGE or offset < 0:
raise HTTPException(422, f"_count goes from 0 to {MAX_PAGE}; _offset from 0") raise HTTPException(422, f"_count goes from 0 to {MAX_PAGE}; _offset from 0")
return count, offset return (count, offset)
def bundle(request: Request, matches: list[Resource], total: int, count: int, offset: int, def bundle(
included: list[Resource] = (), applied: dict | None = None) -> Response: # fmt: skip request: Request,
matches: list[Resource],
total: int,
count: int,
offset: int,
included: list[Resource] = (),
applied: dict | None = None,
) -> Response:
base = str(request.base_url).rstrip("/") + request.url.path.rsplit("/", 1)[0] base = str(request.base_url).rstrip("/") + request.url.path.rsplit("/", 1)[0]
def link(relation: str, at: int) -> dict: def link(relation: str, at: int) -> dict:
params = {**(applied or {}), "_offset": at, "_count": count} url = request.url.include_query_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)} return {"relation": relation, "url": str(url)}
links = [link("self", offset)] links = [link("self", offset)]
@@ -81,65 +85,21 @@ def bundle(request: Request, matches: list[Resource], total: int, count: int, of
if offset > 0: if offset > 0:
links.append(link("previous", max(offset - count, 0))) links.append(link("previous", max(offset - count, 0)))
groups = (("match", matches), ("include", included)) groups = (("match", matches), ("include", included))
entries = [{"fullUrl": f"{base}/{r.get_resource_type()}/{r.id}", "resource": r, entries = [
"search": {"mode": mode}} for mode, group in groups for r in group] # fmt: skip {
"fullUrl": f"{base}/{r.get_resource_type()}/{r.id}",
"resource": r,
"search": {"mode": mode},
}
for mode, group in groups
for r in group
]
found = Bundle(type="searchset", total=total, link=links, entry=entries or None) found = Bundle(type="searchset", total=total, link=links, entry=entries or None)
return fhir(found) return fhir(found)
def _sliced(found: list, count: int, offset: int) -> list: def _sliced(found: list, count: int, offset: int) -> list:
return found[offset:offset + count] # fmt: skip return found[offset : offset + count]
_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) @router.get("/Patient/{id}", responses=_OK, response_class=Response)
@@ -158,7 +118,7 @@ def read_patient(domain: Domain, id: str) -> Response:
def _with_identity(domain: Domain, rows: list[dict]) -> list[dict]: def _with_identity(domain: Domain, rows: list[dict]) -> list[dict]:
persons = [r["person_id"] for r in rows] persons = [r["person_id"] for r in rows]
names, ids, replaces = {}, {}, {} names, ids, replaces = ({}, {}, {})
for r in reads.rows(domain.value, "names", persons=persons): for r in reads.rows(domain.value, "names", persons=persons):
names.setdefault(r["person_id"], []).append(r["text"]) names.setdefault(r["person_id"], []).append(r["text"])
for r in reads.rows(domain.value, "identifiers", persons=persons): for r in reads.rows(domain.value, "identifiers", persons=persons):
@@ -166,55 +126,66 @@ def _with_identity(domain: Domain, rows: list[dict]) -> list[dict]:
for r in reads.rows(domain.value, "replaces", persons=persons): for r in reads.rows(domain.value, "replaces", persons=persons):
replaces.setdefault(r["replaced_by"], []).append(r["person_id"]) replaces.setdefault(r["replaced_by"], []).append(r["person_id"])
return [ return [
{**r, "names": names.get(p, []), "identifiers": ids.get(p, []), {
"replaces": replaces.get(p, [])} **r,
for r in rows if (p := r["person_id"]) "names": names.get(p, []),
] # fmt: skip "identifiers": ids.get(p, []),
"replaces": replaces.get(p, []),
}
for r in rows
if (p := r["person_id"])
]
def _folded(text: str) -> str: def _folded(text: str) -> str:
return "".join(c for c in unicodedata.normalize("NFKD", text.casefold()) return "".join(
if not unicodedata.combining(c)) # fmt: skip (c for c in unicodedata.normalize("NFKD", text.casefold()) if not unicodedata.combining(c))
)
def _matches(row: dict, name: str | None, identifier: str | None) -> bool: def _matches(row: dict, name: str | None, identifier: str | None) -> bool:
if name: if name:
words = _folded(name).split() words = _folded(name).split()
if not any(all(any(w.startswith(q) for w in _folded(n).split()) for q in words) if not any(
for n in row["names"]): # fmt: skip (
all((any((w.startswith(q) for w in _folded(n).split())) for q in words))
for n in row["names"]
)
):
return False return False
if identifier: if identifier:
system, _, value = identifier.rpartition("|") system, _, value = identifier.rpartition("|")
if not any((not system or s == system) and v.casefold() == value.strip().casefold() if not any(
for s, v in row["identifiers"]): # fmt: skip (
(not system or s == system) and v.casefold() == value.strip().casefold()
for s, v in row["identifiers"]
)
):
return False return False
return True return True
@router.get( @router.get("/Patient", responses=_OK, response_class=Response)
"/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( def search_patient(
request: Request, request: Request,
domain: Domain, domain: Domain,
_id: str | None = Query(None, alias="_id"), _id: str | None = Query(None, alias="_id"),
window: int | None = _WINDOW, window: int | None = Query(
start: date | None = _START, None,
cutoff: date | None = _CUTOFF, alias="follow-up-window",
status: str | None = _STATUS, description="months: the domain's follow-up list over that window up to the cut-off",
),
cutoff: date | None = Query(
None, alias="follow-up-cutoff", description="default: the last day with data"
),
status: str | None = Query(None, alias="follow-up-status"),
name: str | None = Query( name: str | None = Query(
None, description="each word starts a word of her name (case and accents ignored)" None, description="each word starts a word of her name (case and accents ignored)"
), ),
identifier: str | None = Query( identifier: str | None = Query(
None, description="[system|]value: a CURP or record number (case ignored)" None, description="[system|]value: a CURP or record number (case ignored)"
), ),
birthdate: list[str] = Query([], description="gt, ge, lt or le and a day (2000-12-31)"),
sort: str = Query("-recent", alias="_sort", description="-recent or -risk-<outcome>"), sort: str = Query("-recent", alias="_sort", description="-recent or -risk-<outcome>"),
horizon: float | None = Query(None, alias="risk-horizon", description="years"), horizon: float | None = Query(None, alias="risk-horizon", description="years"),
revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"), revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"),
@@ -226,94 +197,69 @@ def search_patient(
count, offset = _page(_count, _offset) count, offset = _page(_count, _offset)
at = _cutoff(domain, cutoff) at = _cutoff(domain, cutoff)
horizon = fu.DEFAULT_HORIZON if horizon is None else horizon horizon = fu.DEFAULT_HORIZON if horizon is None else horizon
try: persons_rows = reads.rows(domain.value, "persons")
rows, listed, applied = _patient_rows( if window is None:
request, domain, fu, at, window, start, cutoff, status, sort, _id rows = [{**r, "status": fu.status(r, at)} for r in persons_rows]
) else:
except ValueError as exc: if window not in fu.WINDOWS:
return outcome(422, str(exc)) raise HTTPException(422, f"follow-up-window is one of {fu.WINDOWS}")
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: if sort not in fu.SORTS:
raise HTTPException(422, f"_sort is one of {fu.SORTS}") raise HTTPException(422, f"_sort is one of {fu.SORTS}")
if start is None and window is not None: start = window_start(at, window)
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()} params = {"start": start.isoformat(), "cutoff": at.isoformat()}
person = {r["person_id"]: r for r in persons} person = {r["person_id"]: r for r in persons_rows}
rows = [ rows = [
{**person[r["person_id"]], **r} {**person[r["person_id"]], **r}
for r in fu.listed(reads.rows(domain.value, "follow_up", **params), start, at) for r in fu.listed(reads.rows(domain.value, "follow_up", **params), start, at)
] ]
applied = {"follow-up-cutoff": at.isoformat(), **filters} if _id:
else: rows = [r for r in rows if r["person_id"] in _id.split(",")]
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: if status:
rows = [r for r in rows if r["status"] in status.split(",")] rows = [r for r in rows if r["status"] in status.split(",")]
if filters: if birthdate:
rows = [r for r in rows if fu.matches(r, filters)] rows = [r for r in rows if all((_born(r, b) for b in birthdate))]
return rows, listed, applied if name or identifier:
found = {
r["person_id"] for r in _with_identity(domain, rows) if _matches(r, name, identifier)
}
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 window is not None and sort != "-recent" or "RiskAssessment:subject" in revinclude:
for r in reads.rows(domain.value, "risk", persons=persons):
risks.setdefault(r["person_id"], []).append(r)
if window is not None:
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}
)
applied = {"follow-up-cutoff": at.isoformat()} if window is not None else None
patients = [f.patient(r, fu.STATUS_SYSTEM) for r in _with_identity(domain, page)]
return bundle(request, patients, len(rows), count, offset, included, applied)
def _included(domain: Domain, revinclude: list[str], include: list[str], persons: list[str], _COMPARE = {"gt": operator.gt, "ge": operator.ge, "lt": operator.lt, "le": operator.le}
at: date, risks: dict[str, list[dict]]) -> list[Resource]: # fmt: skip
allowed = _revincludes(domain)
unknown = set(revinclude) - set(allowed) | set(include) - {"DiagnosticReport:result"} def _born(row: dict, asked: str) -> bool:
try:
compare, day = (_COMPARE[asked[:2]], date.fromisoformat(asked[2:]))
except (KeyError, ValueError):
raise HTTPException(422, "birthdate is gt, ge, lt or le and a day") from None
return row["birth_date"] is not None and compare(str(row["birth_date"])[:10], str(day))
def _included(
domain: Domain,
revinclude: list[str],
include: list[str],
persons: list[str],
at: date,
risks: dict[str, list[dict]],
) -> list[Resource]:
unknown = set(revinclude) - set(REVINCLUDES) | set(include) - {"DiagnosticReport:result"}
if unknown: if unknown:
raise HTTPException(422, f"cannot include {sorted(unknown)}") raise HTTPException(422, f"cannot include {sorted(unknown)}")
found: list[Resource] = [] found: list[Resource] = []
@@ -324,23 +270,13 @@ def _included(domain: Domain, revinclude: list[str], include: list[str], persons
if reports or observations: if reports or observations:
for r in _studies(domain, persons, at.isoformat()): for r in _studies(domain, persons, at.isoformat()):
kind = r.get_resource_type() kind = r.get_resource_type()
if (kind == "DiagnosticReport" and reports) or (kind == "Observation" and observations): if kind == "DiagnosticReport" and reports or (kind == "Observation" and observations):
found.append(r) 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 "RiskAssessment:subject" in revinclude:
if domain == Domain.TEA: found += _risk_assessments([r for p in persons for r in risks.get(p, [])])
found += _tea_risks(persons, at.isoformat())
else:
found += _risk_assessments([r for p in persons for r in risks.get(p, [])])
return found 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]: def _subjects(subject: str | None) -> list[str]:
if not subject: if not subject:
raise HTTPException(422, "subject is required (Patient/<id>, comma-separated)") raise HTTPException(422, "subject is required (Patient/<id>, comma-separated)")
@@ -350,71 +286,25 @@ def _subjects(subject: str | None) -> list[str]:
def _studies(domain: Domain, persons: list[str], at: str) -> list[Resource]: def _studies(domain: Domain, persons: list[str], at: str) -> list[Resource]:
found: list[Resource] = [] found: list[Resource] = []
report_facts = _clinical(domain).REPORT_FACTS 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): for study in catalog.of_domain(domain.value):
spec = catalog.studies()[study] spec = catalog.studies()[study]
facts = {} facts = {}
if kind := report_facts.get(study): if kind := report_facts.get(study):
found_facts = reads.rows(domain.value, kind, persons=persons, cutoff=at) found_facts = reads.rows(domain.value, kind, persons=persons, cutoff=at)
facts = {(r["person_id"], str(r["sample_date"])[:10]): r["days"] facts = {(r["person_id"], str(r["sample_date"])[:10]): r for r in found_facts}
for r in found_facts} # fmt: skip first = next((e.date for e in spec.events.values() if e.parent is None))
first = next(e.date for e in spec.events.values() if e.parent is None)
for row in reads.instances(study, persons, at): for row in reads.instances(study, persons, at):
days = facts.get((row["person_id"], str(row[first])[:10])) extra = f.report_facts(facts.get((row["person_id"], str(row[first])[:10]), {}))
extra = [] if days is None else [f.ext("days-to-diagnosis", "integer", int(days))] found += f.instance(study, f.known(study, row, at), extra)
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 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]: def _risk_assessments(rows: list[dict]) -> list[Resource]:
groups: dict[tuple, list[dict]] = {} groups: dict[tuple, list[dict]] = {}
for r in rows: for r in rows:
groups.setdefault((r["model"], r["version"], r["person_id"], str(r["index_date"])), groups.setdefault(
[]).append(r) # fmt: skip (r["model"], r["version"], r["person_id"], str(r["index_date"])), []
).append(r)
return [f.risk_assessment(g[0], g) for g in groups.values()] return [f.risk_assessment(g[0], g) for g in groups.values()]
@@ -426,77 +316,62 @@ def _clinical_search(kind: str, build, request, domain, subject, count, offset):
params["cutoff"] = _cutoff(domain, None).isoformat() params["cutoff"] = _cutoff(domain, None).isoformat()
if kind == "procedure": if kind == "procedure":
params["types"] = list(fu.PROCEDURES) params["types"] = list(fu.PROCEDURES)
if kind == "risk" and domain == Domain.TEA: found = build(reads.rows(domain.value, kind, **params))
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) return bundle(request, _sliced(found, count, offset), len(found), count, offset)
SUBJECT = "Patient/<id>, comma-separated" SUBJECT = "Patient/<id>, comma-separated"
@router.get( @router.get("/DiagnosticReport", responses=_OK, response_class=Response)
"/DiagnosticReport", def search_diagnostic_report(
responses=_OK, request: Request,
response_class=Response, domain: Domain,
description=( subject: str | None = Query(None, description=SUBJECT),
"The domain's reports (each study of the catalog with a report), " _count: int | None = Query(None),
"as known by the last\n" _offset: int = Query(0),
"day with data." ) -> Response:
),
)
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) return _study_search("DiagnosticReport", request, domain, subject, _count, _offset)
def _study_search(kind: str, request, domain, subject, count, offset) -> Response: def _study_search(kind: str, request, domain, subject, count, offset) -> Response:
_clinical(domain) _clinical(domain)
count, offset = _page(count, offset) count, offset = _page(count, offset)
persons, at = _subjects(subject), _cutoff(domain, None).isoformat() persons, at = (_subjects(subject), _cutoff(domain, None).isoformat())
found = [r for r in _studies(domain, persons, at) if r.get_resource_type() == kind] 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) return bundle(request, _sliced(found, count, offset), len(found), count, offset)
@router.get( @router.get("/Encounter", responses=_OK, response_class=Response)
"/Encounter", def search_encounter(
responses=_OK, request: Request,
response_class=Response, domain: Domain,
description="Consultations: each study of the catalog without a report, as an encounter.", subject: str | None = Query(None, description=SUBJECT),
) _count: int | None = Query(None),
def search_encounter(request: Request, domain: Domain, _offset: int = Query(0),
subject: str | None = Query(None, description=SUBJECT), ) -> Response:
_count: int | None = Query(None),
_offset: int = Query(0)) -> Response: # fmt: skip
return _study_search("Encounter", request, domain, subject, _count, _offset) return _study_search("Encounter", request, domain, subject, _count, _offset)
@router.get( @router.get("/Observation", responses=_OK, response_class=Response)
"/Observation", def search_observation(
responses=_OK, request: Request,
response_class=Response, domain: Domain,
description="Every result of the domain's reports, one per field of the catalog.", subject: str | None = Query(None, description=SUBJECT),
) _count: int | None = Query(None),
def search_observation(request: Request, domain: Domain, _offset: int = Query(0),
subject: str | None = Query(None, description=SUBJECT), ) -> Response:
_count: int | None = Query(None),
_offset: int = Query(0)) -> Response: # fmt: skip
return _study_search("Observation", request, domain, subject, _count, _offset) return _study_search("Observation", request, domain, subject, _count, _offset)
@router.get( @router.get("/Condition", responses=_OK, response_class=Response)
"/Condition", def search_condition(
responses=_OK, request: Request,
response_class=Response, domain: Domain,
description="What clinical notes diagnosed (CaMa: and each recurrence).", subject: str | None = Query(None, description=SUBJECT),
) _count: int | None = Query(None),
def search_condition(request: Request, domain: Domain, _offset: int = Query(0),
subject: str | None = Query(None, description=SUBJECT), ) -> Response:
_count: int | None = Query(None),
_offset: int = Query(0)) -> Response: # fmt: skip
def build(rows): def build(rows):
return [f.condition(r) for r in rows] return [f.condition(r) for r in rows]
@@ -504,20 +379,14 @@ def search_condition(request: Request, domain: Domain,
return _clinical_search("condition", build, request, domain, subject, _count, _offset) return _clinical_search("condition", build, request, domain, subject, _count, _offset)
@router.get( @router.get("/Procedure", responses=_OK, response_class=Response)
"/Procedure", def search_procedure(
responses=_OK, request: Request,
response_class=Response, domain: Domain,
description=( subject: str | None = Query(None, description=SUBJECT),
"The procedures the domain's timeline infers (CaCu: colposcopies " _count: int | None = Query(None),
"and treatments;\n" _offset: int = Query(0),
"CaMa: each treatment, by its kind)." ) -> Response:
),
)
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): def build(rows):
return [f.procedure(r, domain.value) for r in rows] return [f.procedure(r, domain.value) for r in rows]
@@ -525,16 +394,14 @@ def search_procedure(request: Request, domain: Domain,
return _clinical_search("procedure", build, request, domain, subject, _count, _offset) return _clinical_search("procedure", build, request, domain, subject, _count, _offset)
@router.get( @router.get("/RiskAssessment", responses=_OK, response_class=Response)
"/RiskAssessment", def search_risk_assessment(
responses=_OK, request: Request,
response_class=Response, domain: Domain,
description="The champion models' risks, one per model and index date.", subject: str | None = Query(None, description=SUBJECT),
) _count: int | None = Query(None),
def search_risk_assessment(request: Request, domain: Domain, _offset: int = Query(0),
subject: str | None = Query(None, description=SUBJECT), ) -> Response:
_count: int | None = Query(None),
_offset: int = Query(0)) -> Response: # fmt: skip
return _clinical_search("risk", _risk_assessments, request, domain, subject, _count, _offset) return _clinical_search("risk", _risk_assessments, request, domain, subject, _count, _offset)
@@ -551,25 +418,16 @@ def read_measure(domain: Domain, id: str) -> Response:
return fhir(f.measure(_measure(domain, id), domain.value)) return fhir(f.measure(_measure(domain, id), domain.value))
@router.get( @router.get("/Measure", responses=_OK, response_class=Response)
"/Measure", def search_measure(
responses=_OK, request: Request, domain: Domain, _count: int | None = Query(None), _offset: int = Query(0)
response_class=Response, ) -> 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) count, offset = _page(_count, _offset)
found = [f.measure(x, domain.value) for x in measures(domain).values()] found = [f.measure(x, domain.value) for x in measures(domain).values()]
return bundle(request, _sliced(found, count, offset), len(found), count, offset) return bundle(request, _sliced(found, count, offset), len(found), count, offset)
@router.get( @router.get("/MeasureReport", responses=_OK, response_class=Response)
"/MeasureReport",
responses=_OK,
response_class=Response,
description="The measure's summary report for each period asked for, evaluated over gold.",
)
def search_measure_report( def search_measure_report(
request: Request, request: Request,
domain: Domain, domain: Domain,
@@ -604,18 +462,7 @@ def search_measure_report(
return bundle(request, reports, len(asked), count, offset) return bundle(request, reports, len(asked), count, offset)
@router.post( @router.post("", responses=_OK, response_class=Response, status_code=202)
"",
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( def post_bundle(
domain: Domain, domain: Domain,
bundle: Annotated[dict[str, Any], Body(description="a FHIR R4 batch or transaction Bundle")], bundle: Annotated[dict[str, Any], Body(description="a FHIR R4 batch or transaction Bundle")],
@@ -636,9 +483,16 @@ def post_bundle(
raise HTTPException(404, f"no pipeline {sender} to place what it sends") raise HTTPException(404, f"no pipeline {sender} to place what it sends")
readers.receive(sender, bundle) readers.receive(sender, bundle)
run_id = submit(client, sender) run_id = submit(client, sender)
entries = [{"response": {"status": "202 Accepted", "location": entries = [
f"{e.resource.get_resource_type()}/{e.resource.id}"}} {
for e in parsed.entry or [] if e.resource is not None] # fmt: skip "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
]
answer = Bundle(type="batch-response", entry=entries or None) answer = Bundle(type="batch-response", entry=entries or None)
found = fhir(answer) found = fhir(answer)
found.status_code = 202 found.status_code = 202
@@ -646,19 +500,11 @@ def post_bundle(
return found return found
@router.get( @router.get("/metadata", responses=_OK, response_class=Response)
"/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: def metadata(request: Request, domain: Domain) -> Response:
resources: dict[str, dict] = {} resources: dict[str, dict] = {}
system: list[dict] = [] system: list[dict] = []
fu = part(domain, "follow_up") clinical = part(domain, "follow_up") is not None
clinical = fu is not None
for route in router.routes: for route in router.routes:
path = route.path.removeprefix(router.prefix) path = route.path.removeprefix(router.prefix)
if not path: if not path:
@@ -666,43 +512,48 @@ def metadata(request: Request, domain: Domain) -> Response:
system = [{"code": "batch"}, {"code": "transaction"}] system = [{"code": "batch"}, {"code": "transaction"}]
continue continue
_, kind, *rest = path.split("/") _, kind, *rest = path.split("/")
if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport" if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport" and (not clinical)):
and not clinical): # fmt: skip
continue
if rest and rest[0].startswith("$"):
continue continue
entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []}) entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []})
if kind == "Patient" and not rest: if kind == "Patient" and (not rest):
entry |= {"searchInclude": ["DiagnosticReport:result"], entry |= {
"searchRevInclude": list(_revincludes(domain))} # fmt: skip "searchInclude": ["DiagnosticReport:result"],
if domain == Domain.TEA: "searchRevInclude": list(REVINCLUDES),
entry["searchParam"] += [ }
{"name": name, "type": spec[0]} for name, spec in TEA_FILTERS.items()
]
entry["interaction"].append({"code": "read" if rest else "search-type"}) entry["interaction"].append({"code": "read" if rest else "search-type"})
for param in route.dependant.query_params: for param in route.dependant.query_params:
name = param.alias name = param.alias
if name.startswith("_") and name != "_id": if name.startswith("_") and name != "_id":
continue continue
declared = f.SEARCH_PARAMETERS.get(name) declared = f.SEARCH_PARAMETERS.get(name)
entry["searchParam"].append({ entry["searchParam"].append(
"name": name, {
"type": declared[1] if declared else _STANDARD[name], "name": name,
**({"definition": f"{f.BASE}/SearchParameter/{name}"} if declared else {}), "type": declared[1] if declared else _STANDARD[name],
}) # fmt: skip **({"definition": f"{f.BASE}/SearchParameter/{name}"} if declared else {}),
statement = CapabilityStatement.model_validate({ }
"resourceType": "CapabilityStatement", )
"status": "active", statement = CapabilityStatement.model_validate(
"date": date.today().isoformat(), {
"kind": "instance", "resourceType": "CapabilityStatement",
"fhirVersion": f.FHIR_VERSION, "status": "active",
"format": ["json"], "date": date.today().isoformat(),
"implementation": {"description": f"ISSSTELEON {domain.value}", "kind": "instance",
"url": str(request.base_url).rstrip("/") + f"/{domain.value}/fhir"}, "fhirVersion": f.FHIR_VERSION,
"rest": [{"mode": "server", "format": ["json"],
"resource": [{k: v for k, v in r.items() if v} for r in resources.values()], "implementation": {
**({"interaction": system} if system else {})}], "description": f"ISSSTELEON {domain.value}",
}) # fmt: skip "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 {}),
}
],
}
)
return fhir(statement) return fhir(statement)
@@ -710,7 +561,7 @@ _STANDARD = {
"_id": "token", "_id": "token",
"subject": "reference", "subject": "reference",
"measure": "reference", "measure": "reference",
"follow-up-start": "date",
"name": "string", "name": "string",
"birthdate": "date",
"identifier": "token", "identifier": "token",
} }
+28 -52
View File
@@ -1,12 +1,10 @@
from typing import Annotated, Any from typing import Annotated, Any
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
from fastapi import APIRouter, Depends, HTTPException, Path, Query from fastapi import APIRouter, Depends, HTTPException, Path, Query
from fhir.resources.R4B.conceptmap import ConceptMap from fhir.resources.R4B.conceptmap import ConceptMap
from pydantic import BaseModel from pydantic import BaseModel
from core import concept_map from core import concept_map
from core.pipeline import ID_PATTERN, Pipeline, Source, redacted, restored from core.pipeline import ID_PATTERN, ImportPath, Pipeline, Source, redacted, restored
from core.schema import ENTITIES from core.schema import ENTITIES
from persistance import config_log, nodes from persistance import config_log, nodes
from webapi.runs import dagster from webapi.runs import dagster
@@ -20,14 +18,11 @@ Rows = list[dict[str, Any]]
def _from_source(call, *args): def _from_source(call, *args):
try: try:
return call(*args) return call(*args)
except Exception as e: # noqa: BLE001 except Exception as e:
raise HTTPException(422, detail=f"{type(e).__name__}: {e}") from e raise HTTPException(422, detail=f"{type(e).__name__}: {e}") from e
@router.get( @router.get("/schema")
"/schema",
description="What the canvas draws with: every node kind's form, and the platform entities.",
)
def schema() -> dict[str, Any]: def schema() -> dict[str, Any]:
return { return {
"pipeline": Pipeline.model_json_schema(), "pipeline": Pipeline.model_json_schema(),
@@ -35,10 +30,17 @@ def schema() -> dict[str, Any]:
} }
@router.post( class SourceRef(BaseModel):
"/sources/preview", source: ImportPath
description="The first rows a source node would load.", args: dict[str, Any] = {}
)
@router.post("/sources/resources")
def source_resources(ref: SourceRef) -> list[str]:
return _from_source(nodes.resources, ref.source, ref.args)
@router.post("/sources/preview")
def source_preview(node: Source, limit: Annotated[int, Query(ge=1, le=200)] = 20) -> Rows: 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)] return [nodes.shown(r) for r in _from_source(nodes.preview, node, limit)]
@@ -53,10 +55,7 @@ class SavedPipeline(BaseModel):
pipeline: Pipeline pipeline: Pipeline
@router.get( @router.get("/pipelines/{pipeline_id}")
"/pipelines/{pipeline_id}",
description="A saved pipeline (latest by default), with its secrets masked.",
)
def pipeline(pipeline_id: PipelineId, version: int | None = None) -> SavedPipeline: def pipeline(pipeline_id: PipelineId, version: int | None = None) -> SavedPipeline:
if not config_log.latest_version(pipeline_id): if not config_log.latest_version(pipeline_id):
raise HTTPException(404, detail=f"no pipeline {pipeline_id}") raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
@@ -64,17 +63,10 @@ def pipeline(pipeline_id: PipelineId, version: int | None = None) -> SavedPipeli
return SavedPipeline(version=found, pipeline=redacted(saved)) return SavedPipeline(version=found, pipeline=redacted(saved))
@router.put( @router.put("/pipelines/{pipeline_id}")
"/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]: 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)} 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")): 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}") 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 previous = config_log.get(pipeline_id)[1] if config_log.latest_version(pipeline_id) else None
try: try:
@@ -84,25 +76,19 @@ def save_pipeline(pipeline_id: PipelineId, drawn: Pipeline) -> dict[str, int]:
return {"version": config_log.save(pipeline_id, complete)} return {"version": config_log.save(pipeline_id, complete)}
@router.get( @router.get("/concept-maps")
"/concept-maps/{map_id}", def concept_maps() -> Rows:
description="A site's codes in platform terms (FHIR R4B ConceptMap), latest version.", return config_log.listing("concept_maps")
)
@router.get("/concept-maps/{map_id}")
def get_concept_map(map_id: PipelineId) -> dict[str, Any]: def get_concept_map(map_id: PipelineId) -> dict[str, Any]:
if not config_log.latest_version(map_id, "concept_maps"): if not config_log.latest_version(map_id, "concept_maps"):
raise HTTPException(404, detail=f"no concept map {map_id}") raise HTTPException(404, detail=f"no concept map {map_id}")
return config_log.concept_map(map_id).model_dump(mode="json", exclude_none=True) return config_log.concept_map(map_id).model_dump(mode="json", exclude_none=True)
@router.put( @router.put("/concept-maps/{map_id}")
"/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]: def save_concept_map(map_id: PipelineId, doc: dict[str, Any]) -> dict[str, int]:
try: try:
found = ConceptMap.model_validate({**doc, "resourceType": "ConceptMap"}) found = ConceptMap.model_validate({**doc, "resourceType": "ConceptMap"})
@@ -117,14 +103,9 @@ class RunRequest(BaseModel):
version: int | None = None version: int | None = None
@router.post( @router.post("/pipelines/{pipeline_id}/runs")
"/pipelines/{pipeline_id}/runs",
description="Starts the `ingest` job for this pipeline; follow it at /runs/{run_id}.",
)
def start_run( def start_run(
pipeline_id: PipelineId, pipeline_id: PipelineId, request: RunRequest, client: DagsterGraphQLClient = Depends(dagster)
request: RunRequest,
client: DagsterGraphQLClient = Depends(dagster),
) -> dict[str, str]: ) -> dict[str, str]:
if not config_log.latest_version(pipeline_id): if not config_log.latest_version(pipeline_id):
raise HTTPException(404, detail=f"no pipeline {pipeline_id}") raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
@@ -141,14 +122,9 @@ def submit(client: DagsterGraphQLClient, pipeline_id: str, version: int | None =
raise HTTPException(502, detail=str(e)) from e raise HTTPException(502, detail=str(e)) from e
@router.get( @router.get("/pipelines/{pipeline_id}/nodes/{node_id}/rows")
"/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( def node_rows(
pipeline_id: PipelineId, pipeline_id: PipelineId, node_id: NodeId, limit: Annotated[int, Query(ge=1, le=500)] = 50
node_id: NodeId,
limit: Annotated[int, Query(ge=1, le=500)] = 50,
) -> Rows: ) -> Rows:
out = [] out = []
for row in nodes.rows(pipeline_id, node_id): for row in nodes.rows(pipeline_id, node_id):
+1 -4
View File
@@ -1,9 +1,8 @@
from fastapi import Depends, FastAPI, Request from fastapi import Depends, FastAPI, Request
from fastapi.exception_handlers import http_exception_handler from fastapi.exception_handlers import http_exception_handler
from starlette.exceptions import HTTPException from starlette.exceptions import HTTPException
from core.domains import Domain from core.domains import Domain
from webapi import eeg, execution, fhir, ingest, models, preview, review, runs, sources, users from webapi import eeg, fhir, ingest, models, review, runs, sources, users
from webapi.auth import caller from webapi.auth import caller
app = FastAPI( app = FastAPI(
@@ -17,10 +16,8 @@ app.include_router(ingest.router)
app.include_router(sources.router) app.include_router(sources.router)
app.include_router(review.router) app.include_router(review.router)
app.include_router(runs.router) app.include_router(runs.router)
app.include_router(execution.router)
app.include_router(models.router) app.include_router(models.router)
app.include_router(eeg.router) app.include_router(eeg.router)
app.include_router(preview.router)
app.include_router(fhir.router) app.include_router(fhir.router)
app.include_router(users.router) app.include_router(users.router)
+47 -220
View File
@@ -1,18 +1,13 @@
import mimetypes import mimetypes
import zipfile
from datetime import date from datetime import date
from typing import Annotated, Any, Literal from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
from fastapi import APIRouter, Depends, HTTPException, UploadFile
from dagster_graphql import DagsterGraphQLClient
from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile
from fastapi.responses import Response from fastapi.responses import Response
from pydantic import BaseModel, Field from pydantic import BaseModel
from core.domains import Domain from core.domains import Domain
from core.models import title from core.models import title
from persistance import bundle, cluster, registry from persistance import registry
from persistance.cluster import Execution, TrainingSource from webapi.runs import dagster
from webapi.runs import dagster, execution_config, submit
router = APIRouter(prefix="/models", tags=["models"]) router = APIRouter(prefix="/models", tags=["models"])
@@ -24,7 +19,6 @@ class Version(BaseModel):
metrics: dict[str, float] metrics: dict[str, float]
params: dict[str, str] params: dict[str, str]
reports: list[str] reports: list[str]
status: Literal["champion", "retired", "candidate"]
class Model(BaseModel): class Model(BaseModel):
@@ -38,65 +32,6 @@ def models(domain: Domain) -> list[Model]:
return [Model(name=n.removeprefix(prefix), title=title(n)) for n in registry.names(prefix)] 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") @router.get("/{domain}/{name}/versions")
def versions(domain: Domain, name: str) -> list[Version]: def versions(domain: Domain, name: str) -> list[Version]:
if not (found := registry.versions(f"{domain.value}.{name}")): if not (found := registry.versions(f"{domain.value}.{name}")):
@@ -104,186 +39,78 @@ def versions(domain: Domain, name: str) -> list[Version]:
return [Version(**v) for v in found] return [Version(**v) for v in found]
@router.get("/{domain}/{name}/versions/{version}/reports/{report}", @router.get(
responses={200: {"content": {"application/json": {}, "application/octet-stream": {}}, "/{domain}/{name}/versions/{version}/reports/{report}",
"description": "the report as stored"}}, responses={
response_class=Response, 200: {
description=( "content": {"application/json": {}, "application/octet-stream": {}},
"A version's report: the generated ones as JSON (what the " "description": "the report as stored",
'governance page draws), the\n' }
'clinical validation as the file the clinical team uploaded.' },
), response_class=Response,
) # fmt: skip )
def read_report(domain: Domain, name: str, version: int, report: str) -> Response: def read_report(domain: Domain, name: str, version: int, report: str) -> Response:
found = registry.report(f"{domain.value}.{name}", version, report) found = registry.report(f"{domain.value}.{name}", version, report)
if found is None: if found is None:
raise HTTPException(404, detail=f"{domain.value}.{name} v{version} has no {report}") raise HTTPException(404, detail=f"{domain.value}.{name} v{version} has no {report}")
filename, content = found filename, content = found
kind = mimetypes.guess_type(filename)[0] or "application/octet-stream" kind = mimetypes.guess_type(filename)[0] or "application/octet-stream"
return Response(content, media_type=kind, return Response(
headers={"Content-Disposition": f'inline; filename="{filename}"'}) # fmt: skip content, media_type=kind, headers={"Content-Disposition": f'inline; filename="{filename}"'}
)
@router.post( @router.post("/{domain}/{name}/versions/{version}/reports/clinical_validation")
"/{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: def add_clinical_validation(domain: Domain, name: str, version: int, file: UploadFile) -> dict:
registry.add_report(f"{domain.value}.{name}", version, "clinical_validation", registry.add_report(
file.filename or "report", file.file.read()) # fmt: skip f"{domain.value}.{name}",
version,
"clinical_validation",
file.filename or "report",
file.file.read(),
)
return {"reports": sorted(registry.reports(f"{domain.value}.{name}", version))} return {"reports": sorted(registry.reports(f"{domain.value}.{name}", version))}
@router.post( @router.post("/{domain}/{name}/versions/{version}/promote")
"/{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: def promote(domain: Domain, name: str, version: int) -> dict:
try: try:
registry.promote(f"{domain.value}.{name}", version) registry.promote(f"{domain.value}.{name}", version)
except registry.UnknownVersion as e: except registry.MissingReports as e:
raise HTTPException(404, detail=str(e)) from e
except ValueError as e:
raise HTTPException(409, detail=str(e)) from e raise HTTPException(409, detail=str(e)) from e
return {"champion": version} return {"champion": version}
@router.get("/{domain}/{name}/versions/{version}/checks") class Training(BaseModel):
def version_checks(domain: Domain, name: str, version: int) -> dict: as_of: date | None = None
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] = [] models: list[str] = []
class TrainingConfig(BaseModel): def _submit(client: DagsterGraphQLClient, job: str, op: str, config: dict) -> dict[str, str]:
domain: str try:
name: str run_id = client.submit_job_execution(job, run_config={"ops": {op: {"config": config}}})
json_schema: dict[str, Any] except DagsterGraphQLClientError as e:
defaults: dict[str, Any] raise HTTPException(502, detail=str(e)) from e
return {"run_id": run_id}
@router.get("/{domain}/{name}/training-config") @router.post("/{domain}/train")
def training_config(domain: Domain, name: str) -> TrainingConfig: def train(
json_schema = TrainingForm.model_json_schema() domain: Domain, request: Training, client: DagsterGraphQLClient = Depends(dagster)
defaults = {"execution": {"mode": cluster.default_mode(), "scheduler": None}} ) -> dict[str, str]:
if domain == Domain.TEA: config: dict = {"domain": domain.value}
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: if request.as_of:
config["as_of"] = request.as_of.isoformat() config["as_of"] = request.as_of.isoformat()
if request.models: if request.models:
config["models"] = request.models config["models"] = request.models
if request.source is not None: return _submit(client, "train", "train_models", config)
config["source"] = request.source.model_dump()
return submit(client, "train", "train_models", config, domain=domain.value)
@router.post( @router.post("/{domain}/analyze")
"/{domain}/analyze", def analyze(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
description=( return _submit(client, "analyze", "analyze_studies", {"domain": domain.value})
"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( @router.post("/{domain}/score")
"/{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]: def score(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
return submit(client, "score", "score_models", {"domain": domain.value}, domain=domain.value) return _submit(client, "score", "score_models", {"domain": domain.value})
-1
View File
@@ -1,5 +1,4 @@
import json import json
from webapi.main import app from webapi.main import app
if __name__ == "__main__": if __name__ == "__main__":
-50
View File
@@ -1,50 +0,0 @@
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,
)
+13 -61
View File
@@ -1,8 +1,6 @@
from typing import Any from typing import Any
from fastapi import APIRouter, Depends from fastapi import APIRouter, Depends
from pydantic import BaseModel, ConfigDict, model_validator from pydantic import BaseModel, model_validator
from core.pipeline import EntityName, Id, validate from core.pipeline import EntityName, Id, validate
from core.schema import ENTITIES from core.schema import ENTITIES
from persistance import nodes, review from persistance import nodes, review
@@ -12,43 +10,22 @@ router = APIRouter(prefix="/review", tags=["review"])
Rows = list[dict[str, Any]] Rows = list[dict[str, Any]]
@router.get( @router.get("/held")
"/held",
description="Rows a rule held, with the reasons and the values as they came.",
)
def held(entity: EntityName) -> Rows: def held(entity: EntityName) -> Rows:
return review.held(entity) return review.held(entity)
@router.get( @router.get("/conflicts")
"/conflicts",
description="Rows of one person and date that disagree; reject the wrong ones.",
)
def conflicts(entity: EntityName) -> Rows: def conflicts(entity: EntityName) -> Rows:
return review.conflicts(entity) return review.conflicts(entity)
@router.get( @router.get("/unrecognised")
"/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: def unrecognised(pipeline: Id) -> Rows:
return review.unrecognised(pipeline) return review.unrecognised(pipeline)
@router.get( @router.get("/persons")
"/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]: def persons(pipeline: Id, node: Id) -> dict[str, Rows]:
return review.persons(pipeline, node) return review.persons(pipeline, node)
@@ -59,28 +36,13 @@ class PersonDecision(BaseModel):
same: bool same: bool
@router.post( @router.post("/persons", status_code=201)
"/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]: def decide_persons(decision: PersonDecision, who: Caller = Depends(caller)) -> dict[str, str]:
nodes.decide_persons(decision.person, decision.candidate, decision.same, who.id) nodes.decide_persons(decision.person, decision.candidate, decision.same, who.id)
return {"person": decision.person} return {"person": decision.person}
class Correction(BaseModel): 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" entity: EntityName = "identity"
record: str record: str
field: str field: str
@@ -90,23 +52,17 @@ class Correction(BaseModel):
def _a_valid_value(self): def _a_valid_value(self):
if self.field not in ENTITIES[self.entity].model_fields: if self.field not in ENTITIES[self.entity].model_fields:
raise ValueError(f"{self.entity} has no field {self.field}") raise ValueError(f"{self.entity} has no field {self.field}")
reasons = [r for r in validate(self.entity, {self.field: self.value}) reasons = [
if r.split(":")[0] == self.field] # fmt: skip r
for r in validate(self.entity, {self.field: self.value})
if r.split(":")[0] == self.field
]
if reasons: if reasons:
raise ValueError("; ".join(reasons)) raise ValueError("; ".join(reasons))
return self return self
@router.post( @router.post("/corrections", status_code=201)
"/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]: def correct(fix: Correction, who: Caller = Depends(caller)) -> dict[str, str]:
nodes.correct(fix.record, fix.field, fix.value, who.id, fix.entity) nodes.correct(fix.record, fix.field, fix.value, who.id, fix.entity)
return {"record": fix.record} return {"record": fix.record}
@@ -118,11 +74,7 @@ class Rejection(BaseModel):
reason: str reason: str
@router.post( @router.post("/rejections", status_code=201)
"/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]: def reject(decision: Rejection, who: Caller = Depends(caller)) -> dict[str, str]:
nodes.reject(decision.entity, decision.record, decision.reason, who.id) nodes.reject(decision.entity, decision.record, decision.reason, who.id)
return {"record": decision.record} return {"record": decision.record}
+11 -279
View File
@@ -1,297 +1,29 @@
import json
import os import os
import time
from typing import Any, Literal
import requests
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
from fastapi import APIRouter, Depends, HTTPException, Query from fastapi import APIRouter, Depends, HTTPException
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"]) 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: def dagster() -> DagsterGraphQLClient:
host, port = _dagster_address() return DagsterGraphQLClient(
return DagsterGraphQLClient(host, port_number=port) os.environ.get("DAGSTER_HOST", "localhost"),
port_number=int(os.environ.get("DAGSTER_PORT", "3000")),
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}") @router.get("/{run_id}")
def run_status(run_id: str, outputs: bool = False) -> Run: def run_status(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
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: try:
return client.get_run_status(run_id).value return {"id": run_id, "status": client.get_run_status(run_id).value}
except DagsterGraphQLClientError as e: except DagsterGraphQLClientError as e:
raise HTTPException(404 if e.args[0] == "RunNotFoundError" else 502, detail=str(e)) from e raise HTTPException(404 if "RunNotFound" in str(e) else 502, detail=str(e)) from e
@router.post("/{run_id}/cancel") @router.post("/{run_id}/terminate")
def cancel_run(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> Cancel: def terminate_run(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
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: try:
client.terminate_run(run_id) client.terminate_run(run_id)
return {"id": run_id, "status": client.get_run_status(run_id).value}
except DagsterGraphQLClientError as e: except DagsterGraphQLClientError as e:
raise HTTPException(502, detail=str(e)) from e raise HTTPException(404 if "RunNotFound" in str(e) else 409, 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}
+108 -107
View File
@@ -4,10 +4,8 @@ import shutil
import uuid import uuid
from pathlib import Path, PurePosixPath from pathlib import Path, PurePosixPath
from typing import Annotated, Any, Literal from typing import Annotated, Any, Literal
from fastapi import APIRouter, Form, HTTPException, Query, UploadFile from fastapi import APIRouter, Form, HTTPException, Query, UploadFile
from pydantic import BaseModel, ValidationError from pydantic import BaseModel, ValidationError
from core import sources from core import sources
from core.pipeline import MASK, Pipeline, Source, restored from core.pipeline import MASK, Pipeline, Source, restored
from persistance import config_log, nodes from persistance import config_log, nodes
@@ -17,10 +15,7 @@ router = APIRouter(prefix="/ingest", tags=["ingest"])
UPLOADS = "uploads" UPLOADS = "uploads"
@router.get( @router.get("/sources/types")
"/sources/types",
description="Every kind of source the dialog offers, grouped, with the fields each one asks.",
)
def source_types() -> sources.Catalog: def source_types() -> sources.Catalog:
return sources.catalog() return sources.catalog()
@@ -42,28 +37,25 @@ class Tested(BaseModel):
PLAIN = [ PLAIN = [
( (
r"login failed|password authentication failed|access denied|authentication|" "login failed|password authentication failed|access denied|authentication|401|403|permission denied|invalid credentials",
r"401|403|permission denied|invalid credentials",
"El usuario o la contraseña no son correctos, o no tiene permiso.", "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|" "name or service not known|could not translate host|nodename nor servname|getaddrinfo|unknown host|no such host|resolve",
r"getaddrinfo|unknown host|no such host|resolve",
"No se encontró el servidor. Revise el nombre o la dirección.", "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|" "timed out|timeout|connection refused|unable to connect|adaptive server is unavailable|could not connect|connection reset",
r"could not connect|connection reset",
"El servidor no respondió. Revise la dirección, el puerto o si está encendido.", "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", "database .* does not exist|cannot open database|unknown database",
"No existe esa base de datos en el servidor.", "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 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).", "No se encontró lo que pidió (la tabla, la carpeta o el archivo).",
), # fmt: skip ),
] ]
@@ -81,8 +73,12 @@ def _with_saved_secrets(asked: Answers) -> dict[str, Any]:
if not (asked.pipeline and asked.node and config_log.latest_version(asked.pipeline)): 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") raise HTTPException(422, detail="una contraseña oculta necesita la fuente guardada")
saved = config_log.get(asked.pipeline)[1] saved = config_log.get(asked.pipeline)[1]
node = {"id": asked.node, "kind": "source", "source": "core.sources:catalog", node = {
"guided": {"type": asked.type, "answers": asked.answers}} # fmt: skip "id": asked.node,
"kind": "source",
"source": "core.sources:catalog",
"guided": {"type": asked.type, "answers": asked.answers},
}
try: try:
found = restored(Pipeline(nodes=[node]), saved).nodes[0] found = restored(Pipeline(nodes=[node]), saved).nodes[0]
except ValueError as e: except ValueError as e:
@@ -90,50 +86,42 @@ def _with_saved_secrets(asked: Answers) -> dict[str, Any]:
return found.guided.answers return found.guided.answers
@router.post( @router.post("/sources/test")
"/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: def test_source(asked: Answers, limit: Annotated[int, Query(ge=1, le=100)] = 20) -> Tested:
if asked.type not in sources.catalog().types: if asked.type not in sources.catalog().types:
raise HTTPException(404, detail=f"no source type {asked.type}") raise HTTPException(404, detail=f"no source type {asked.type}")
answers = _with_saved_secrets(asked) answers = _with_saved_secrets(asked)
spec = sources.catalog().types[asked.type] spec = sources.catalog().types[asked.type]
picked = all(answers.get(k) for k, f in spec.fields.items() if f.type == "table") picked = all((answers.get(k) for k, f in spec.fields.items() if f.type == "table"))
try: try:
if not picked and (listed := sources.listing(asked.type, answers)): if not picked and (listed := sources.listing(asked.type, answers)):
tables = nodes.resources(*listed) tables = nodes.resources(*listed)
count = "1 tabla" if len(tables) == 1 else f"{len(tables)} tablas" count = "1 tabla" if len(tables) == 1 else f"{len(tables)} tablas"
return Tested(ok=True, message=f"Conexión correcta: {count}.", return Tested(ok=True, message=f"Conexión correcta: {count}.", tables=tables)
tables=tables) # fmt: skip
node = Source(id="probe", guided={"type": asked.type, "answers": answers}) node = Source(id="probe", guided={"type": asked.type, "answers": answers})
rows = [nodes.shown(r) for r in nodes.preview(node, limit)] rows = [nodes.shown(r) for r in nodes.preview(node, limit)]
except (sources.MissingAnswer, ValidationError) as e: except (sources.MissingAnswer, ValidationError) as e:
return Tested(ok=False, message=_missing(e)) return Tested(ok=False, message=_missing(e))
except Exception as e: # noqa: BLE001 except Exception as e:
return Tested(ok=False, message=plain(e), detail=f"{type(e).__name__}: {e}"[:2000]) return Tested(ok=False, message=plain(e), detail=f"{type(e).__name__}: {e}"[:2000])
found = ( found = (
"Conexión correcta." "Conexión correcta."
if rows if rows
else ( else "Se conectó, pero no encontró archivos ni filas. Revise la ruta y qué archivos tomar."
"Se conectó, pero no encontró archivos ni filas. Revise la ruta y qué archivos tomar."
)
) )
return Tested(ok=True, message=found, rows=rows) return Tested(ok=True, message=found, rows=rows)
def _missing(e: Exception) -> str: def _missing(e: Exception) -> str:
if isinstance(e, ValidationError): if isinstance(e, ValidationError):
return next((str(err["ctx"]["error"]) for err in e.errors() return next(
if isinstance(err.get("ctx", {}).get("error"), sources.MissingAnswer)), (
str(e)) # fmt: skip str(err["ctx"]["error"])
for err in e.errors()
if isinstance(err.get("ctx", {}).get("error"), sources.MissingAnswer)
),
str(e),
)
return str(e) return str(e)
@@ -158,31 +146,39 @@ class Browsed(BaseModel):
entries: list[Entry] entries: list[Entry]
@router.get( @router.get("/sources/browse")
"/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: def browse(path: str | None = None) -> Browsed:
allowed = roots() allowed = roots()
if path is None: if path is None:
return Browsed(path=None, parent=None, entries=[ return Browsed(
Entry(name=name, path=str(root), kind="folder") path=None,
for name, root in allowed.items() if root.is_dir()]) # fmt: skip parent=None,
entries=[
Entry(name=name, path=str(root), kind="folder")
for name, root in allowed.items()
if root.is_dir()
],
)
folder = Path(path).resolve() folder = Path(path).resolve()
root = next((r for r in allowed.values() if folder == r or r in folder.parents), None) 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(): if root is None or not folder.is_dir():
raise HTTPException(404, detail="esa carpeta no está entre las habilitadas") raise HTTPException(404, detail="esa carpeta no está entre las habilitadas")
entries = sorted( 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) Entry(
for p in folder.iterdir() if not p.name.startswith(".")), name=p.name,
key=lambda e: (e.kind != "folder", e.name.lower())) # fmt: skip path=str(p),
return Browsed(path=str(folder), parent=None if folder == root else str(folder.parent), kind="folder" if p.is_dir() else "file",
entries=entries) # fmt: skip 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()),
)
return Browsed(
path=str(folder), parent=None if folder == root else str(folder.parent), entries=entries
)
class Uploaded(BaseModel): class Uploaded(BaseModel):
@@ -197,16 +193,7 @@ def _relative(name: str) -> PurePosixPath:
return PurePosixPath(*parts) return PurePosixPath(*parts)
@router.post( @router.post("/uploads")
"/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: def upload(files: list[UploadFile], folder: Annotated[str | None, Form()] = None) -> Uploaded:
base = (DATA_DIR / UPLOADS).resolve() base = (DATA_DIR / UPLOADS).resolve()
target = Path(folder).resolve() if folder else base / uuid.uuid4().hex[:12] target = Path(folder).resolve() if folder else base / uuid.uuid4().hex[:12]
@@ -225,7 +212,7 @@ def upload(files: list[UploadFile], folder: Annotated[str | None, Form()] = None
PENDING = DATA_DIR / "oauth_pending" PENDING = DATA_DIR / "oauth_pending"
PENDING_SECONDS = 600 PENDING_SECONDS = 600
STATE = re.compile(r"[A-Za-z0-9_-]{8,128}") STATE = re.compile("[A-Za-z0-9_-]{8,128}")
def _pend(state: str, pending: dict[str, Any]) -> None: def _pend(state: str, pending: dict[str, Any]) -> None:
@@ -238,7 +225,7 @@ def _pend(state: str, pending: dict[str, Any]) -> None:
old.unlink(missing_ok=True) old.unlink(missing_ok=True)
path = PENDING / f"{state}.json" path = PENDING / f"{state}.json"
path.write_text(json.dumps(pending)) path.write_text(json.dumps(pending))
path.chmod(0o600) path.chmod(384)
def _claimed(state: str) -> dict[str, Any] | None: def _claimed(state: str) -> dict[str, Any] | None:
@@ -263,14 +250,17 @@ def _registration(provider: str) -> tuple[sources.Provider, dict[str, str]]:
found = sources.catalog().providers.get(provider) found = sources.catalog().providers.get(provider)
if found is None: if found is None:
raise HTTPException(404, detail=f"no provider {provider}") raise HTTPException(404, detail=f"no provider {provider}")
env = {k: os.environ.get(f"{found.env}_{k.upper()}", "") env = {
for k in ("client_id", "client_secret", "tenant_id", "project_id")} # fmt: skip k: os.environ.get(f"{found.env}_{k.upper()}", "")
for k in ("client_id", "client_secret", "tenant_id", "project_id")
}
if not (env["client_id"] and env["client_secret"]): if not (env["client_id"] and env["client_secret"]):
needed = f"{found.env}_CLIENT_ID y {found.env}_CLIENT_SECRET" needed = f"{found.env}_CLIENT_ID y {found.env}_CLIENT_SECRET"
raise HTTPException(503, detail=( raise HTTPException(
f"Para iniciar sesión con {found.title}, el área de sistemas debe registrar la " 503,
f"aplicación y darle al servidor {needed}.")) # fmt: skip detail=f"Para iniciar sesión con {found.title}, el área de sistemas debe registrar la aplicación y darle al servidor {needed}.",
return found, env )
return (found, env)
def _endpoint(url: str, env: dict[str, str]) -> str: def _endpoint(url: str, env: dict[str, str]) -> str:
@@ -280,8 +270,13 @@ def _endpoint(url: str, env: dict[str, str]) -> str:
def _client(provider: sources.Provider, env: dict[str, str], redirect_uri: str): def _client(provider: sources.Provider, env: dict[str, str], redirect_uri: str):
from authlib.integrations.httpx_client import OAuth2Client from authlib.integrations.httpx_client import OAuth2Client
return OAuth2Client(env["client_id"], env["client_secret"], scope=provider.scope, return OAuth2Client(
redirect_uri=redirect_uri, code_challenge_method="S256") # fmt: skip env["client_id"],
env["client_secret"],
scope=provider.scope,
redirect_uri=redirect_uri,
code_challenge_method="S256",
)
class SignIn(BaseModel): class SignIn(BaseModel):
@@ -289,14 +284,7 @@ class SignIn(BaseModel):
state: str state: str
@router.get( @router.get("/sources/oauth/{provider}/start")
"/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: def oauth_start(provider: str, origin: str) -> SignIn:
import secrets import secrets
@@ -306,8 +294,15 @@ def oauth_start(provider: str, origin: str) -> SignIn:
url, state = _client(found, env, redirect_uri).create_authorization_url( url, state = _client(found, env, redirect_uri).create_authorization_url(
_endpoint(found.authorize_url, env), code_verifier=verifier, **found.authorize_params _endpoint(found.authorize_url, env), code_verifier=verifier, **found.authorize_params
) )
_pend(state, {"provider": provider, "verifier": verifier, "redirect_uri": redirect_uri, _pend(
"origin": origin.rstrip("/")}) # fmt: skip state,
{
"provider": provider,
"verifier": verifier,
"redirect_uri": redirect_uri,
"origin": origin.rstrip("/"),
},
)
return SignIn(url=url, state=state) return SignIn(url=url, state=state)
@@ -323,30 +318,39 @@ def account(provider: str, token: dict[str, Any], env: dict[str, str]) -> dict[s
"user": me.get("mail") or me.get("userPrincipalName") or me.get("displayName"), "user": me.get("mail") or me.get("userPrincipalName") or me.get("displayName"),
"drive_id": drive.get("id"), "drive_id": drive.get("id"),
"oauth2_client_params": { "oauth2_client_params": {
"client_id": env["client_id"], "client_secret": env["client_secret"], "client_id": env["client_id"],
"token_endpoint": _endpoint(found.token_url, env), "scope": found.scope, "client_secret": env["client_secret"],
"token_endpoint": _endpoint(found.token_url, env),
"scope": found.scope,
"token": token, "token": token,
}, },
} # fmt: skip }
about = httpx.get("https://www.googleapis.com/drive/v3/about", params={"fields": "user"}, about = httpx.get(
headers=bearer).json() # fmt: skip "https://www.googleapis.com/drive/v3/about", params={"fields": "user"}, headers=bearer
credentials = {"client_id": env["client_id"], "client_secret": env["client_secret"], ).json()
"refresh_token": token.get("refresh_token"), credentials = {
"project_id": env["project_id"] or None} # fmt: skip "client_id": env["client_id"],
return {"user": about.get("user", {}).get("emailAddress"), "client_secret": env["client_secret"],
"credentials": {k: v for k, v in credentials.items() if v}} # fmt: skip "refresh_token": token.get("refresh_token"),
"project_id": env["project_id"] or None,
}
return {
"user": about.get("user", {}).get("emailAddress"),
"credentials": {k: v for k, v in credentials.items() if v},
}
@router.get("/sources/oauth/{provider}/callback", include_in_schema=False) @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): def oauth_callback(provider: str, state: str, code: str | None = None, error: str | None = None):
import json import json
from fastapi.responses import HTMLResponse from fastapi.responses import HTMLResponse
pending = _claimed(state) pending = _claimed(state)
if pending is None or pending["provider"] != provider: if pending is None or pending["provider"] != provider:
return HTMLResponse("<p>La solicitud de inicio de sesión venció. Cierre esta ventana " return HTMLResponse(
"e inténtelo de nuevo.</p>", status_code=400) # fmt: skip "<p>La solicitud de inicio de sesión venció. Cierre esta ventana e inténtelo de nuevo.</p>",
status_code=400,
)
message: dict[str, Any] = {"type": "isssteleon-oauth", "state": state} message: dict[str, Any] = {"type": "isssteleon-oauth", "state": state}
if error or not code: if error or not code:
message["error"] = "No se completó el inicio de sesión." message["error"] = "No se completó el inicio de sesión."
@@ -357,13 +361,10 @@ def oauth_callback(provider: str, state: str, code: str | None = None, error: st
_endpoint(found.token_url, env), code=code, code_verifier=pending["verifier"] _endpoint(found.token_url, env), code=code, code_verifier=pending["verifier"]
) )
message["account"] = account(provider, dict(token), env) message["account"] = account(provider, dict(token), env)
except Exception as e: # noqa: BLE001 except Exception as e:
message["error"] = f"No se pudo iniciar sesión: {e}" message["error"] = f"No se pudo iniciar sesión: {e}"
payload = json.dumps(message).replace("</", "<\\/") payload = json.dumps(message).replace("</", "<\\/")
target = json.dumps(pending["origin"]) target = json.dumps(pending["origin"])
return HTMLResponse( return HTMLResponse(
"<!doctype html><meta charset=utf-8><title>ISSSTELEON</title>" f"<!doctype html><meta charset=utf-8><title>ISSSTELEON</title><p>Listo. Puede cerrar esta ventana.</p><script>window.opener&&window.opener.postMessage({payload},{target});window.close()</script>"
"<p>Listo. Puede cerrar esta ventana.</p>"
f"<script>window.opener&&window.opener.postMessage({payload},{target});"
"window.close()</script>"
) )
+18 -14
View File
@@ -4,7 +4,6 @@ import uuid
from collections.abc import AsyncIterator from collections.abc import AsyncIterator
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from functools import cache from functools import cache
from fastapi import APIRouter, Depends, FastAPI from fastapi import APIRouter, Depends, FastAPI
from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin, schemas from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin, schemas
from fastapi_users.authentication import AuthenticationBackend, CookieTransport, JWTStrategy from fastapi_users.authentication import AuthenticationBackend, CookieTransport, JWTStrategy
@@ -13,7 +12,6 @@ from fastapi_users_db_sqlalchemy import SQLAlchemyBaseUserTableUUID, SQLAlchemyU
from sqlalchemy import JSON, String, event, make_url, text from sqlalchemy import JSON, String, event, make_url, text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from core.domains import Domain from core.domains import Domain
from persistance.config import DATA_DIR, platform_url from persistance.config import DATA_DIR, platform_url
@@ -42,6 +40,11 @@ class UserCreate(schemas.BaseUserCreate):
domains: list[Domain] = [] domains: list[Domain] = []
class UserUpdate(schemas.BaseUserUpdate):
name: str | None = None
domains: list[Domain] | None = None
@cache @cache
def _engine(): def _engine():
url = make_url(platform_url()) url = make_url(platform_url())
@@ -74,17 +77,17 @@ def _secret() -> str:
if not path.exists(): if not path.exists():
path.parent.mkdir(parents=True, exist_ok=True) path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(secrets.token_urlsafe(48)) path.write_text(secrets.token_urlsafe(48))
path.chmod(0o600) path.chmod(384)
return path.read_text().strip() return path.read_text().strip()
class Manager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]): class Manager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
@property @property
def reset_password_token_secret(self) -> str: # type: ignore[override] def reset_password_token_secret(self) -> str:
return _secret() return _secret()
@property @property
def verification_token_secret(self) -> str: # type: ignore[override] def verification_token_secret(self) -> str:
return _secret() return _secret()
@@ -103,14 +106,10 @@ backend = AuthenticationBackend(
get_strategy=lambda: JWTStrategy(secret=_secret(), lifetime_seconds=SESSION_HOURS * 3600), get_strategy=lambda: JWTStrategy(secret=_secret(), lifetime_seconds=SESSION_HOURS * 3600),
) )
users = FastAPIUsers[User, uuid.UUID](_manager, [backend]) users = FastAPIUsers[User, uuid.UUID](_manager, [backend])
current_user = users.current_user(active=True)
router = APIRouter() router = APIRouter()
router.include_router(users.get_auth_router(backend), prefix="/auth", tags=["auth"]) router.include_router(users.get_auth_router(backend), prefix="/auth", tags=["auth"])
user_routes = users.get_users_router(UserRead, schemas.BaseUserUpdate) router.include_router(users.get_users_router(UserRead, UserUpdate), prefix="/users", tags=["users"])
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))] admins_only = [Depends(users.current_user(active=True, superuser=True))]
router.include_router( router.include_router(
users.get_register_router(UserRead, UserCreate), users.get_register_router(UserRead, UserCreate),
@@ -125,14 +124,19 @@ async def first_admin() -> None:
if connection.dialect.name != "sqlite": if connection.dialect.name != "sqlite":
await connection.execute(text(f"create schema if not exists {SCHEMA}")) await connection.execute(text(f"create schema if not exists {SCHEMA}"))
await connection.run_sync(Base.metadata.create_all) await connection.run_sync(Base.metadata.create_all)
email, password = os.environ.get("AUTH_ADMIN_EMAIL"), os.environ.get("AUTH_ADMIN_PASSWORD") email, password = (os.environ.get("AUTH_ADMIN_EMAIL"), os.environ.get("AUTH_ADMIN_PASSWORD"))
if not (email and password): if not (email and password):
return return
async with async_sessionmaker(_engine(), expire_on_commit=False)() as session: async with async_sessionmaker(_engine(), expire_on_commit=False)() as session:
manager = Manager(SQLAlchemyUserDatabase(session, User)) manager = Manager(SQLAlchemyUserDatabase(session, User))
try: try:
admin = UserCreate(email=email, password=password, is_superuser=True, admin = UserCreate(
name="Administrador", domains=list(Domain)) # fmt: skip email=email,
password=password,
is_superuser=True,
name="Administrador",
domains=list(Domain),
)
await manager.create(admin) await manager.create(admin)
except UserAlreadyExists: except UserAlreadyExists:
pass pass