Conectar API: sources, uploads, pipelines, runs, node rows, review; tested end to end
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
"""An operator connects a messy site through the API, the way the /conectar screens will:
|
||||
look into its sources, save the drawn pipeline, run it, read what came out, and settle
|
||||
what review shows. Real API and Dagster processes; nothing faked."""
|
||||
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from synthetic.site import build
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital" / "hospital_cacu.db"
|
||||
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "messy_site.json"
|
||||
SQL = "dlt.sources.sql_database:sql_database"
|
||||
CYTOLOGY = {"entity": "cervical_cytology"}
|
||||
|
||||
|
||||
def ok(response, status=200):
|
||||
assert response.status_code == status, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def wait_for(api, run_id: str, seconds: int = 900) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while (status := ok(api.get(f"/runs/{run_id}"))["status"]) not in ("SUCCESS", "FAILURE"):
|
||||
assert time.monotonic() < deadline, f"run {run_id} still {status}"
|
||||
time.sleep(2)
|
||||
assert status == "SUCCESS"
|
||||
|
||||
|
||||
def run(api, pipeline: str) -> None:
|
||||
wait_for(api, ok(api.post(f"/ingest/pipelines/{pipeline}/runs", json={}))["run_id"])
|
||||
|
||||
|
||||
def test_an_operator_connects_a_site_and_settles_its_review(api, platform, tmp_path):
|
||||
site = tmp_path / "site"
|
||||
truth = build(HOSPITAL, site)["records"]
|
||||
database = {"credentials": f"sqlite:///{site}/site.db"}
|
||||
|
||||
# What the site has, and what one of its tables holds (documents shown by size).
|
||||
found = ok(api.post("/ingest/sources/resources", json={"source": SQL, "args": database}))
|
||||
assert found == ["ArchivosUni", "pacientes_his"]
|
||||
missing = {"credentials": f"sqlite:///{tmp_path}/nowhere/site.db"}
|
||||
unreachable = api.post("/ingest/sources/resources", json={"source": SQL, "args": missing})
|
||||
assert unreachable.status_code == 422 and "unable to open" in unreachable.text
|
||||
reports = {"id": "reports", "kind": "source", "source": SQL, "args": database}
|
||||
sample = ok(
|
||||
api.post("/ingest/sources/preview?limit=3", json=reports | {"resource": "ArchivosUni"})
|
||||
)
|
||||
assert len(sample) == 3 and all(r["Archivo"].endswith(" bytes>") for r in sample)
|
||||
|
||||
# A file someone uploads becomes a source like any other.
|
||||
csv = (site / "files" / "consultas.csv").read_bytes()
|
||||
uploaded = ok(api.post("/ingest/uploads", files={"file": ("consultas.csv", csv)}))
|
||||
notes = {"id": "notes", "kind": "source", "source": "dlt.sources.filesystem:readers",
|
||||
"resource": "read_csv", "args": {"bucket_url": uploaded["bucket_url"]}} # fmt: skip
|
||||
assert len(ok(api.post("/ingest/sources/preview?limit=5", json=notes))) == 5
|
||||
|
||||
# Saving a drawing: broken ones are refused with the reason; good ones get versions.
|
||||
drawn = json.loads(PIPELINE.read_text().replace("{site}", str(site)))
|
||||
broken = {"nodes": [*drawn["nodes"], {"id": "loose", "kind": "read", "inputs": ["gone"],
|
||||
"column": "x"}]} # fmt: skip
|
||||
assert "no node" in api.put("/ingest/pipelines/site", json=broken).text
|
||||
assert ok(api.put("/ingest/pipelines/site", json=drawn)) == {"version": 1}
|
||||
assert ok(api.get("/ingest/pipelines/site"))["version"] == 1
|
||||
|
||||
# A password is never shown, and survives the UI sending the masked drawing back.
|
||||
secret = "postgresql://isss:S3cret@10.0.10.9/his"
|
||||
hidden = {"nodes": [{"id": "his", "kind": "source", "source": SQL,
|
||||
"args": {"credentials": secret}}]} # fmt: skip
|
||||
ok(api.put("/ingest/pipelines/his", json=hidden))
|
||||
shown = ok(api.get("/ingest/pipelines/his"))["pipeline"]
|
||||
assert "S3cret" not in json.dumps(shown)
|
||||
assert ok(api.put("/ingest/pipelines/his", json=shown)) == {"version": 2}
|
||||
stored = platform.query(
|
||||
"select doc from config.pipelines where pipeline_id = 'his' and version = 2"
|
||||
)
|
||||
assert secret in stored[0][0]
|
||||
|
||||
# Run it, and look at what any node produced.
|
||||
run(api, "site")
|
||||
reports_read = ok(api.get("/ingest/pipelines/site/nodes/archivos/rows?limit=500"))
|
||||
record_of = {f"ArchivosUni:{r['id']}": r["_record"] for r in reports_read}
|
||||
assert len(ok(api.get("/ingest/pipelines/site/nodes/cytology/rows?limit=500"))) == 53
|
||||
|
||||
# Review shows exactly the reports that contradict each other; nothing else is held.
|
||||
conflicting = {record_of[r["where"]] for r in truth if r.get("conflict")}
|
||||
assert {c["_record"] for c in ok(api.get("/review/conflicts", params=CYTOLOGY))} == conflicting
|
||||
assert ok(api.get("/review/held", params=CYTOLOGY)) == []
|
||||
assert isinstance(
|
||||
ok(api.get("/review/links", params={"pipeline": "site", "node": "persons"})), list
|
||||
)
|
||||
|
||||
# The reviewer rejects the wrong copies; the next run settles the conflicts.
|
||||
for r in truth:
|
||||
if r.get("flipped"):
|
||||
decision = CYTOLOGY | {"record": record_of[r["where"]], "reason": "flipped HPV"}
|
||||
ok(api.post("/review/rejections", json=decision), status=201)
|
||||
run(api, "site")
|
||||
assert ok(api.get("/review/conflicts", params=CYTOLOGY)) == []
|
||||
placed = platform.count("silver.cervical_cytology")
|
||||
assert placed == sum(
|
||||
1 for r in truth if r["entity"] == "cervical_cytology" and not r.get("flipped")
|
||||
)
|
||||
@@ -0,0 +1,137 @@
|
||||
"""/conectar: look into a site's sources, draw and save pipelines, run them, inspect nodes."""
|
||||
|
||||
from pathlib import Path as FilePath
|
||||
from typing import Annotated, Any
|
||||
|
||||
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||
from fastapi import APIRouter, Depends, HTTPException, Path, Query, UploadFile
|
||||
from pydantic import BaseModel
|
||||
|
||||
from core.pipeline import ID_PATTERN, ImportPath, Pipeline, Source, redacted, restored
|
||||
from core.schema import ENTITIES
|
||||
from persistance import config_log, nodes
|
||||
from persistance.config import DATA_DIR
|
||||
from webapi.runs import dagster
|
||||
|
||||
router = APIRouter(prefix="/ingest", tags=["ingest"])
|
||||
PipelineId = Annotated[str, Path(pattern=ID_PATTERN, max_length=40)]
|
||||
NodeId = Annotated[str, Path(pattern=ID_PATTERN, max_length=40)]
|
||||
Rows = list[dict[str, Any]]
|
||||
|
||||
|
||||
def _shown(row: dict) -> dict:
|
||||
"""A row as JSON: file contents shown by size, never sent whole."""
|
||||
return {k: f"<{len(v)} bytes>" if isinstance(v, bytes) else v for k, v in row.items()}
|
||||
|
||||
|
||||
def _from_source(call, *args):
|
||||
try:
|
||||
return call(*args)
|
||||
except Exception as e: # noqa: BLE001 - the operator needs the source's own message
|
||||
raise HTTPException(422, detail=f"{type(e).__name__}: {e}") from e
|
||||
|
||||
|
||||
@router.get("/schema")
|
||||
def schema() -> dict[str, Any]:
|
||||
"""What the canvas draws with: every node kind's form, and the platform entities."""
|
||||
return {
|
||||
"pipeline": Pipeline.model_json_schema(),
|
||||
"entities": {name: model.model_json_schema() for name, model in ENTITIES.items()},
|
||||
}
|
||||
|
||||
|
||||
class SourceRef(BaseModel):
|
||||
source: ImportPath
|
||||
args: dict[str, Any] = {}
|
||||
|
||||
|
||||
@router.post("/sources/resources")
|
||||
def source_resources(ref: SourceRef) -> list[str]:
|
||||
"""What a source offers (a database's tables...): also tests that it can be reached."""
|
||||
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:
|
||||
"""The first rows a source node would load."""
|
||||
return [_shown(r) for r in _from_source(nodes.preview, node, limit)]
|
||||
|
||||
|
||||
@router.post("/uploads")
|
||||
def upload(file: UploadFile) -> dict[str, str]:
|
||||
"""A CSV, Excel or document file for a `filesystem` source: use `bucket_url`."""
|
||||
name = FilePath(file.filename or "").name
|
||||
if not name:
|
||||
raise HTTPException(422, detail="the file needs a name")
|
||||
folder = DATA_DIR / "uploads"
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
(folder / name).write_bytes(file.file.read())
|
||||
return {"bucket_url": str(folder), "file_name": name}
|
||||
|
||||
|
||||
@router.get("/pipelines")
|
||||
def pipelines() -> Rows:
|
||||
return config_log.pipelines()
|
||||
|
||||
|
||||
class SavedPipeline(BaseModel):
|
||||
version: int
|
||||
pipeline: Pipeline
|
||||
|
||||
|
||||
@router.get("/pipelines/{pipeline_id}")
|
||||
def pipeline(pipeline_id: PipelineId, version: int | None = None) -> SavedPipeline:
|
||||
"""A saved pipeline (latest by default), with its secrets masked."""
|
||||
if not config_log.latest_version(pipeline_id):
|
||||
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
||||
found, saved = config_log.get(pipeline_id, version)
|
||||
return SavedPipeline(version=found, pipeline=redacted(saved))
|
||||
|
||||
|
||||
@router.put("/pipelines/{pipeline_id}")
|
||||
def save_pipeline(pipeline_id: PipelineId, drawn: Pipeline) -> dict[str, int]:
|
||||
"""Saves a new version. Masked secrets sent back are kept as they were saved."""
|
||||
previous = config_log.get(pipeline_id)[1] if config_log.latest_version(pipeline_id) else None
|
||||
try:
|
||||
complete = restored(drawn, previous)
|
||||
except ValueError as e:
|
||||
raise HTTPException(422, detail=str(e)) from e
|
||||
return {"version": config_log.save(pipeline_id, complete)}
|
||||
|
||||
|
||||
class RunRequest(BaseModel):
|
||||
version: int | None = None # default: the latest saved
|
||||
|
||||
|
||||
@router.post("/pipelines/{pipeline_id}/runs")
|
||||
def start_run(
|
||||
pipeline_id: PipelineId,
|
||||
request: RunRequest,
|
||||
client: DagsterGraphQLClient = Depends(dagster),
|
||||
) -> dict[str, str]:
|
||||
"""Starts the `ingest` job for this pipeline; follow it at /runs/{run_id}."""
|
||||
if not config_log.latest_version(pipeline_id):
|
||||
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
||||
config = {"pipeline": pipeline_id, "version": request.version}
|
||||
try:
|
||||
run_id = client.submit_job_execution(
|
||||
"ingest", run_config={"ops": {"run_pipeline": {"config": config}}}
|
||||
)
|
||||
except DagsterGraphQLClientError as e:
|
||||
raise HTTPException(502, detail=str(e)) from e
|
||||
return {"run_id": run_id}
|
||||
|
||||
|
||||
@router.get("/pipelines/{pipeline_id}/nodes/{node_id}/rows")
|
||||
def node_rows(
|
||||
pipeline_id: PipelineId,
|
||||
node_id: NodeId,
|
||||
limit: Annotated[int, Query(ge=1, le=500)] = 50,
|
||||
) -> Rows:
|
||||
"""What a node produced in the last run (empty if it produced nothing yet)."""
|
||||
out = []
|
||||
for row in nodes.rows(pipeline_id, node_id):
|
||||
out.append(_shown(row))
|
||||
if len(out) == limit:
|
||||
break
|
||||
return out
|
||||
+6
-22
@@ -1,24 +1,18 @@
|
||||
import os
|
||||
|
||||
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||
from fastapi import Depends, FastAPI, HTTPException
|
||||
from fastapi import Depends, FastAPI
|
||||
|
||||
from core.domains import Domain
|
||||
from webapi import ingest, review, runs
|
||||
from webapi.auth import caller
|
||||
|
||||
app = FastAPI(
|
||||
title="ISSSTELEON",
|
||||
version="0.0.0",
|
||||
dependencies=[Depends(caller)],
|
||||
dependencies=[Depends(caller)], # every route; where authentication will go
|
||||
generate_unique_id_function=lambda route: route.name, # clean names in the generated client
|
||||
)
|
||||
|
||||
|
||||
def dagster() -> DagsterGraphQLClient:
|
||||
return DagsterGraphQLClient(
|
||||
os.environ.get("DAGSTER_HOST", "localhost"),
|
||||
port_number=int(os.environ.get("DAGSTER_PORT", "3000")),
|
||||
)
|
||||
app.include_router(ingest.router)
|
||||
app.include_router(review.router)
|
||||
app.include_router(runs.router)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
@@ -29,13 +23,3 @@ def health() -> dict[str, str]:
|
||||
@app.get("/domains")
|
||||
def domains() -> list[Domain]:
|
||||
return list(Domain)
|
||||
|
||||
|
||||
@app.get("/runs/{run_id}")
|
||||
def run_status(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
||||
try:
|
||||
return {"id": run_id, "status": client.get_run_status(run_id).value}
|
||||
except DagsterGraphQLClientError as e:
|
||||
raise HTTPException(
|
||||
status_code=404 if "RunNotFound" in str(e) else 502, detail=str(e)
|
||||
) from e
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""What waits for a person, and their decisions (append-only; the next run applies them)."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel
|
||||
|
||||
from core.pipeline import EntityName, Id
|
||||
from persistance import nodes, review
|
||||
from webapi.auth import Caller, caller
|
||||
|
||||
router = APIRouter(prefix="/review", tags=["review"])
|
||||
Rows = list[dict[str, Any]]
|
||||
|
||||
|
||||
@router.get("/held")
|
||||
def held(entity: EntityName) -> Rows:
|
||||
"""Rows a rule held, with the reasons and the values as they came."""
|
||||
return review.held(entity)
|
||||
|
||||
|
||||
@router.get("/conflicts")
|
||||
def conflicts(entity: EntityName) -> Rows:
|
||||
"""Rows of one person and date that disagree; reject the wrong ones."""
|
||||
return review.conflicts(entity)
|
||||
|
||||
|
||||
@router.get("/links")
|
||||
def links(pipeline: Id, node: Id) -> Rows:
|
||||
"""Records that may be the same person but were left apart."""
|
||||
return review.links(pipeline, node)
|
||||
|
||||
|
||||
class Rejection(BaseModel):
|
||||
entity: EntityName
|
||||
record: str
|
||||
reason: str
|
||||
|
||||
|
||||
@router.post("/rejections", status_code=201)
|
||||
def reject(decision: Rejection, who: Caller = Depends(caller)) -> dict[str, str]:
|
||||
"""This record's row must not reach silver; applied on the next run."""
|
||||
nodes.reject(decision.entity, decision.record, decision.reason, who.id)
|
||||
return {"record": decision.record}
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Runs live in Dagster: the API starts them and reads their state, never computes."""
|
||||
|
||||
import os
|
||||
|
||||
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
router = APIRouter(prefix="/runs", tags=["runs"])
|
||||
|
||||
|
||||
def dagster() -> DagsterGraphQLClient:
|
||||
return DagsterGraphQLClient(
|
||||
os.environ.get("DAGSTER_HOST", "localhost"),
|
||||
port_number=int(os.environ.get("DAGSTER_PORT", "3000")),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{run_id}")
|
||||
def run_status(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
||||
try:
|
||||
return {"id": run_id, "status": client.get_run_status(run_id).value}
|
||||
except DagsterGraphQLClientError as e:
|
||||
raise HTTPException(404 if "RunNotFound" in str(e) else 502, detail=str(e)) from e
|
||||
Reference in New Issue
Block a user