"""/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