135 lines
4.7 KiB
Python
135 lines
4.7 KiB
Python
from typing import Annotated, Any
|
|
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
|
from fastapi import APIRouter, Depends, HTTPException, Path, Query
|
|
from fhir.resources.R4B.conceptmap import ConceptMap
|
|
from pydantic import BaseModel
|
|
from core import concept_map
|
|
from core.pipeline import ID_PATTERN, ImportPath, Pipeline, Source, redacted, restored
|
|
from core.schema import ENTITIES
|
|
from persistance import config_log, nodes
|
|
from webapi.runs import dagster
|
|
|
|
router = APIRouter(prefix="/ingest", tags=["ingest"])
|
|
PipelineId = Annotated[str, Path(pattern=ID_PATTERN, max_length=40)]
|
|
NodeId = Annotated[str, Path(pattern=ID_PATTERN, max_length=40)]
|
|
Rows = list[dict[str, Any]]
|
|
|
|
|
|
def _from_source(call, *args):
|
|
try:
|
|
return call(*args)
|
|
except Exception as e:
|
|
raise HTTPException(422, detail=f"{type(e).__name__}: {e}") from e
|
|
|
|
|
|
@router.get("/schema")
|
|
def schema() -> dict[str, Any]:
|
|
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]:
|
|
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:
|
|
return [nodes.shown(r) for r in _from_source(nodes.preview, node, limit)]
|
|
|
|
|
|
@router.get("/pipelines")
|
|
def pipelines() -> Rows:
|
|
return config_log.pipelines()
|
|
|
|
|
|
class SavedPipeline(BaseModel):
|
|
version: int
|
|
pipeline: Pipeline
|
|
|
|
|
|
@router.get("/pipelines/{pipeline_id}")
|
|
def pipeline(pipeline_id: PipelineId, version: int | None = None) -> SavedPipeline:
|
|
if not config_log.latest_version(pipeline_id):
|
|
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
|
found, saved = config_log.get(pipeline_id, version)
|
|
return SavedPipeline(version=found, pipeline=redacted(saved))
|
|
|
|
|
|
@router.put("/pipelines/{pipeline_id}")
|
|
def save_pipeline(pipeline_id: PipelineId, drawn: Pipeline) -> dict[str, int]:
|
|
named = {n.concept_map for n in drawn.nodes if getattr(n, "concept_map", None)}
|
|
if missing := sorted((m for m in named if not config_log.latest_version(m, "concept_maps"))):
|
|
raise HTTPException(422, detail=f"no concept maps {missing}")
|
|
previous = config_log.get(pipeline_id)[1] if config_log.latest_version(pipeline_id) else None
|
|
try:
|
|
complete = restored(drawn, previous)
|
|
except ValueError as e:
|
|
raise HTTPException(422, detail=str(e)) from e
|
|
return {"version": config_log.save(pipeline_id, complete)}
|
|
|
|
|
|
@router.get("/concept-maps")
|
|
def concept_maps() -> Rows:
|
|
return config_log.listing("concept_maps")
|
|
|
|
|
|
@router.get("/concept-maps/{map_id}")
|
|
def get_concept_map(map_id: PipelineId) -> dict[str, Any]:
|
|
if not config_log.latest_version(map_id, "concept_maps"):
|
|
raise HTTPException(404, detail=f"no concept map {map_id}")
|
|
return config_log.concept_map(map_id).model_dump(mode="json", exclude_none=True)
|
|
|
|
|
|
@router.put("/concept-maps/{map_id}")
|
|
def save_concept_map(map_id: PipelineId, doc: dict[str, Any]) -> dict[str, int]:
|
|
try:
|
|
found = ConceptMap.model_validate({**doc, "resourceType": "ConceptMap"})
|
|
except ValueError as e:
|
|
raise HTTPException(422, detail=str(e)) from e
|
|
if problems := concept_map.problems(found):
|
|
raise HTTPException(422, detail=problems)
|
|
return {"version": config_log.save(map_id, found, "concept_maps")}
|
|
|
|
|
|
class RunRequest(BaseModel):
|
|
version: int | None = None
|
|
|
|
|
|
@router.post("/pipelines/{pipeline_id}/runs")
|
|
def start_run(
|
|
pipeline_id: PipelineId, request: RunRequest, client: DagsterGraphQLClient = Depends(dagster)
|
|
) -> dict[str, str]:
|
|
if not config_log.latest_version(pipeline_id):
|
|
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
|
return {"run_id": submit(client, pipeline_id, request.version)}
|
|
|
|
|
|
def submit(client: DagsterGraphQLClient, pipeline_id: str, version: int | None = None) -> str:
|
|
config = {"pipeline": pipeline_id, "version": version}
|
|
try:
|
|
return client.submit_job_execution(
|
|
"ingest", run_config={"ops": {"run_pipeline": {"config": config}}}
|
|
)
|
|
except DagsterGraphQLClientError as e:
|
|
raise HTTPException(502, detail=str(e)) from e
|
|
|
|
|
|
@router.get("/pipelines/{pipeline_id}/nodes/{node_id}/rows")
|
|
def node_rows(
|
|
pipeline_id: PipelineId, node_id: NodeId, limit: Annotated[int, Query(ge=1, le=500)] = 50
|
|
) -> Rows:
|
|
out = []
|
|
for row in nodes.rows(pipeline_id, node_id):
|
|
out.append(nodes.shown(row))
|
|
if len(out) == limit:
|
|
break
|
|
return out
|