From 03c7a8fedb0801d5a9f492d648cee4bc24f72c91 Mon Sep 17 00:00:00 2001 From: clippy Date: Fri, 31 Jul 2026 14:12:21 -0700 Subject: [PATCH 1/5] feat(embed): add the Python router (FastAPI) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the Python port of the /embed router — embed_router(EmbedConfig(...)) as a mountable FastAPI/Starlette APIRouter (package monad-embed, httpx-based). Same contract, idiomatic Python. Adds the python leg to the conformance matrix: the harness venv also installs fastapi/uvicorn and the router (editable), boots servers/py_server.py, and runs ROUTER=python. Restores py_server.py (deferred from the TS-router layer). This completes the router set — ts, go, and python all proven against one contract. Local: python router unit tests pass; conformance green for ROUTER=python, ts, and go. Layer 5 (PRO-404), stacked on the Go router (PRO-403). Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_011ASKA2VrufrNLGGrcFjY7n --- .github/workflows/ci.yml | 7 +- conformance/servers/py_server.py | 26 +++ routers/python/.gitignore | 7 + routers/python/README.md | 104 ++++++++++ routers/python/monad_embed/__init__.py | 34 ++++ routers/python/monad_embed/client.py | 256 +++++++++++++++++++++++++ routers/python/monad_embed/config.py | 49 +++++ routers/python/monad_embed/errors.py | 27 +++ routers/python/monad_embed/models.py | 44 +++++ routers/python/monad_embed/router.py | 219 +++++++++++++++++++++ routers/python/pyproject.toml | 22 +++ routers/python/tests/test_router.py | 129 +++++++++++++ 12 files changed, 923 insertions(+), 1 deletion(-) create mode 100644 conformance/servers/py_server.py create mode 100644 routers/python/.gitignore create mode 100644 routers/python/README.md create mode 100644 routers/python/monad_embed/__init__.py create mode 100644 routers/python/monad_embed/client.py create mode 100644 routers/python/monad_embed/config.py create mode 100644 routers/python/monad_embed/errors.py create mode 100644 routers/python/monad_embed/models.py create mode 100644 routers/python/monad_embed/router.py create mode 100644 routers/python/pyproject.toml create mode 100644 routers/python/tests/test_router.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7569514..aae0530 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,7 +51,7 @@ jobs: strategy: fail-fast: false matrix: - router: [ts, go] + router: [ts, go, python] steps: - uses: actions/checkout@v4 @@ -84,6 +84,11 @@ jobs: uv venv --python 3.10 .venv uv pip install --python .venv/bin/python schemathesis pytest httpx jsonschema + - name: Install the Python router into the harness + if: matrix.router == 'python' + working-directory: conformance + run: uv pip install --python .venv/bin/python fastapi uvicorn -e ../routers/python + - name: Run conformance (${{ matrix.router }}) working-directory: conformance env: diff --git a/conformance/servers/py_server.py b/conformance/servers/py_server.py new file mode 100644 index 0000000..71b15fc --- /dev/null +++ b/conformance/servers/py_server.py @@ -0,0 +1,26 @@ +"""Boot the Python router for conformance testing, pointed at the mock Monad.""" + +import os + +import uvicorn +from fastapi import FastAPI + +from monad_embed import EmbedConfig, Provision, embed_router + +app = FastAPI() +app.include_router( + embed_router( + EmbedConfig( + api_key="conf-key", + api_base=os.environ["MONAD_API_BASE"], + frame_origin="https://app.monad.com/embed", + get_customer_org_id=lambda req: "org_conf", + get_provisioned_components=lambda org: Provision(destination_output_id="out_store", source_input_id="in_source"), + catalog_allow=["aws-cloudtrail", "okta-systemlog"], + ) + ), + prefix="/embed", +) + +if __name__ == "__main__": + uvicorn.run(app, host="127.0.0.1", port=int(os.environ.get("PORT", "8791")), log_level="warning") diff --git a/routers/python/.gitignore b/routers/python/.gitignore new file mode 100644 index 0000000..13f2046 --- /dev/null +++ b/routers/python/.gitignore @@ -0,0 +1,7 @@ +.venv/ +__pycache__/ +*.pyc +.pytest_cache/ +*.egg-info/ +dist/ +build/ diff --git a/routers/python/README.md b/routers/python/README.md new file mode 100644 index 0000000..3b54b53 --- /dev/null +++ b/routers/python/README.md @@ -0,0 +1,104 @@ +# Monad Embed — Python router + +A mountable `/embed` backend router for a Monad embed integration, as a FastAPI +`APIRouter`. Implements the [`/embed` route contract](../../packages/embed/openapi/embed.openapi.yaml). + +```python +from fastapi import FastAPI +from monad_embed import EmbedConfig, Provision, embed_router + +app = FastAPI() +app.include_router( + embed_router(EmbedConfig( + api_key=os.environ["MONAD_API_KEY"], + # your auth → the tenant's Monad team id (sync or async) + get_customer_org_id=lambda req: req.session["org_id"], + # server-side lookup of a tenant's pre-provisioned components + get_provisioned_components=lambda org: Provision(destination_output_id=STORES[org]), + )), + prefix="/embed", +) +``` + +Mounted with `prefix="/embed"`, the router serves `/embed/session`, +`/embed/pipelines/ingress`, etc. The browser holds only a session token; this +router holds the API key and is the seam to the Monad API. + +## Mounting on common frameworks + +`embed_router(cfg)` is a FastAPI `APIRouter` (ASGI), so it slots into any FastAPI +or Starlette app. Assume `router = embed_router(cfg)` below. + +**FastAPI** — include it in your app + +```python +app.include_router(router, prefix="/embed") +``` + +**FastAPI** — as an isolated sub-application (its own docs, middleware, lifespan) + +```python +embed_app = FastAPI() +embed_app.include_router(router) +app.mount("/embed", embed_app) +``` + +**Starlette** — [starlette](https://www.starlette.io) + +```python +from starlette.applications import Starlette +from starlette.routing import Mount + +embed_app = FastAPI() +embed_app.include_router(router) + +app = Starlette(routes=[ + Mount("/embed", app=embed_app), + # ... your other routes +]) +``` + +Serve it with any ASGI server: + +```sh +uvicorn app:app +# or: gunicorn -k uvicorn.workers.UvicornWorker app:app +# or: hypercorn app:app +``` + +**Flask / Django (WSGI)** — the router is ASGI, so either run it as its own +service, or host it inside your WSGI app with an ASGI bridge such as +[`a2wsgi`](https://github.com/abersheeran/a2wsgi): + +```python +from a2wsgi import ASGIMiddleware +from werkzeug.middleware.dispatcher import DispatcherMiddleware + +embed_app = FastAPI() +embed_app.include_router(router) + +# /embed/* → the ASGI embed app; everything else → Flask +flask_app.wsgi_app = DispatcherMiddleware( + flask_app.wsgi_app, + {"/embed": ASGIMiddleware(embed_app)}, +) +``` + +## Config + +| Field | Purpose | +| ---------------------------- | ------------------------------------------------------------------------------------------------------------ | +| `api_key` | Long-lived Monad API key (server-side only). | +| `api_base` | Monad API base. Optional — defaults to `https://app.monad.com/api` (production). | +| `frame_origin` | Iframe origin returned by `GET /embed/config`. Optional — defaults to production. | +| `get_customer_org_id` | `Request → org id`, sync or async. Return `""` / raise to reject (→ 401). | +| `get_provisioned_components` | `org → Provision(destination_output_id, source_input_id)`. Omit → ingress uses dev/null, egress unavailable. | +| `catalog_allow` | Restrict the catalog to these connector type ids. Omit → all. | + +## Develop + +```sh +uv venv --python 3.10 .venv +uv pip install --python .venv/bin/python "fastapi>=0.110" "httpx>=0.27" "pytest>=8" +.venv/bin/python -m pytest -q +``` diff --git a/routers/python/monad_embed/__init__.py b/routers/python/monad_embed/__init__.py new file mode 100644 index 0000000..3ff1c00 --- /dev/null +++ b/routers/python/monad_embed/__init__.py @@ -0,0 +1,34 @@ +"""monad-embed — a mountable ``/embed`` backend router (FastAPI). + +Implements the ``/embed`` route contract (``packages/embed/openapi/embed.openapi.yaml``) +for a Monad embed integration. + + from fastapi import FastAPI + from monad_embed import EmbedConfig, Provision, embed_router + + app = FastAPI() + app.include_router( + embed_router(EmbedConfig( + api_key=os.environ["MONAD_API_KEY"], + api_base="https://app.monad.com/api", + frame_origin="https://app.monad.com/embed", + get_customer_org_id=lambda req: req.session["org_id"], # your auth → Monad team + get_provisioned_components=lambda org: Provision(destination_output_id=STORES[org]), + )), + prefix="/embed", + ) +""" + +from .client import MonadClient +from .config import EmbedConfig, Provision +from .errors import EmbedError, MonadError +from .router import embed_router + +__all__ = [ + "EmbedConfig", + "Provision", + "MonadClient", + "EmbedError", + "MonadError", + "embed_router", +] diff --git a/routers/python/monad_embed/client.py b/routers/python/monad_embed/client.py new file mode 100644 index 0000000..ad82810 --- /dev/null +++ b/routers/python/monad_embed/client.py @@ -0,0 +1,256 @@ +"""The hand-written Monad API client — the Python equivalent of the TS kit. + +Sequences Monad's /v1 + /v2 + /v3 calls; the router layer turns its results into +the ``/embed`` contract's responses. A failed call raises :class:`MonadError`, +which the router maps to ``502 upstream_error``. +""" + +from __future__ import annotations + +import asyncio +from typing import Any, Optional +from urllib.parse import quote + +import httpx + +from .errors import MonadError +from .models import ( + BuiltPipeline, + CatalogType, + ConfiguredConnector, + PipelineStatus, + Session, +) + +_POLL_ATTEMPTS = 15 +_POLL_INTERVAL = 2.0 + + +def _seg(value: Any) -> str: + """URL-encode a single path segment so browser-supplied ids can't inject + query params or traverse the path (``/``, ``?``, ``#`` are neutralised).""" + return quote(str(value), safe="") + + +class MonadClient: + """Talks to the Monad API with the host's long-lived key.""" + + def __init__( + self, + api_key: str, + api_base: str, + *, + transport: Optional[httpx.AsyncBaseTransport] = None, + ) -> None: + self._base = api_base.rstrip("/") + self._headers = { + "Authorization": f"ApiKey {api_key}", + "Content-Type": "application/json", + } + self._transport = transport + self._poll_attempts = _POLL_ATTEMPTS + self._poll_interval = _POLL_INTERVAL + + def _open(self) -> httpx.AsyncClient: + return httpx.AsyncClient(timeout=30.0, transport=self._transport) + + async def _do( + self, c: httpx.AsyncClient, method: str, path: str, json_body: Any = None + ) -> Any: + resp = await c.request(method, self._base + path, headers=self._headers, json=json_body) + if resp.status_code >= 400: + raise MonadError(resp.status_code, f"{resp.status_code} {path}: {resp.text[:300]}") + if not resp.content: + return None + return resp.json() + + async def mint_session(self, org: str) -> Session: + async with self._open() as c: + data = await self._do( + c, "POST", "/v3/sessions", {"ttl_seconds": 1800, "organization_id": org} + ) + return Session( + sessionToken=data["session_token"], + organizationId=org, + expiresAt=data["expires_at"], + ) + + async def list_catalog( + self, kind: str, allow: Optional[list[str]] + ) -> list[CatalogType]: + async with self._open() as c: + data = await self._do(c, "GET", f"/v1/{kind}s") + allow_set = set(allow) if allow else None + out: list[CatalogType] = [] + for t in data or []: + if allow_set is not None and t.get("type_id") not in allow_set: + continue + out.append(CatalogType(typeId=t["type_id"], name=t["name"])) + return out + + async def list_connectors(self, org: str, kind: str) -> list[ConfiguredConnector]: + async with self._open() as c: + page = await self._do(c, "GET", f"/v1/{_seg(org)}/{kind}s?limit=1000&offset=0") + # Monad returns the list as null (not []) when a tenant has none, so + # coalesce with `or []` — a bare .get(key, []) would return that null. + rows = (page or {}).get(f"{kind}s") or [] + return [ + ConfiguredConnector(id=r["id"], typeId=r["type"], name=r["name"]) for r in rows + ] + + async def wire_pipeline( + self, org: str, input_id: str, output_id: str, name: str + ) -> BuiltPipeline: + body = { + "name": name, + "description": "Created when the connector was configured via embed", + "enabled": True, + "nodes": [ + {"slug": "in", "component_id": input_id, "component_type": "input", "enabled": True}, + {"slug": "out", "component_id": output_id, "component_type": "output", "enabled": True}, + ], + "edges": [ + { + "from_node_instance_id": "in", + "to_node_instance_id": "out", + "description": "all records", + "conditions": {"operator": "always"}, + } + ], + } + async with self._open() as c: + created = await self._do(c, "POST", f"/v2/{_seg(org)}/pipelines/", body) + pid = created["id"] + status = "Pending" + for _ in range(self._poll_attempts): + s = await self._do(c, "GET", f"/v2/{_seg(org)}/pipelines/{_seg(pid)}/status") + status = (s or {}).get("status") or status + if status in ("Running", "Erroring"): + break + await asyncio.sleep(self._poll_interval) + return BuiltPipeline( + pipelineId=pid, outputId=output_id, status=status, active=status == "Running" + ) + + async def build_dev_null(self, org: str, input_id: str, name: str) -> BuiltPipeline: + async with self._open() as c: + out = await self._do( + c, + "POST", + f"/v2/{_seg(org)}/outputs", + { + "output_type": "dev-null", + "name": f"{name} → /dev/null", + "description": "Auto-created sink for embed pipeline", + "promise_id": "", + "config": {"settings": {}, "secrets": {}}, + }, + ) + return await self.wire_pipeline(org, input_id, out["id"], name) + + async def _list_pipelines(self, c: httpx.AsyncClient, org: str) -> list[dict]: + data = await self._do(c, "GET", f"/v2/{_seg(org)}/pipelines/") + if isinstance(data, list): + return data + if isinstance(data, dict): + return data.get("pipelines") or data.get("data") or [] + return [] + + async def _get_pipeline(self, c: httpx.AsyncClient, org: str, pid: str) -> dict: + data = await self._do(c, "GET", f"/v2/{_seg(org)}/pipelines/{_seg(pid)}") + if isinstance(data, dict): + return data.get("config") or data + return {} + + async def status_by_input(self, org: str, input_id: str) -> PipelineStatus: + async with self._open() as c: + for summary in await self._list_pipelines(c, org): + pid = summary.get("id") + if not pid: + continue + try: + p = await self._get_pipeline(c, org, pid) + except MonadError: + continue + nodes = p.get("nodes") or [] + in_node = next( + (n for n in nodes if n.get("component_type") == "input" and n.get("component_id") == input_id), + None, + ) + if in_node is None: + continue + out_node = next((n for n in nodes if n.get("component_type") == "output"), None) + return PipelineStatus( + hasPipeline=True, + enabled=bool(p.get("enabled")), + pipelineId=pid, + outputId=out_node.get("component_id") if out_node else None, + ) + return PipelineStatus(hasPipeline=False, enabled=False) + + async def find_by_output(self, org: str, output_id: str) -> PipelineStatus: + async with self._open() as c: + for summary in await self._list_pipelines(c, org): + pid = summary.get("id") + if not pid: + continue + try: + p = await self._get_pipeline(c, org, pid) + except MonadError: + continue + nodes = p.get("nodes") or [] + out_node = next( + (n for n in nodes if n.get("component_type") == "output" and n.get("component_id") == output_id), + None, + ) + if out_node is None: + continue + in_node = next((n for n in nodes if n.get("component_type") == "input"), None) + return PipelineStatus( + hasPipeline=True, + enabled=bool(p.get("enabled")), + pipelineId=pid, + inputId=in_node.get("component_id") if in_node else None, + ) + return PipelineStatus(hasPipeline=False, enabled=False) + + async def set_enabled(self, org: str, pipeline_id: str, enabled: bool) -> None: + async with self._open() as c: + p = await self._get_pipeline(c, org, pipeline_id) + nodes = [ + { + "id": n.get("id"), + "slug": n.get("slug"), + "component_id": n.get("component_id"), + "component_type": n.get("component_type"), + "enabled": n.get("enabled", True), + } + for n in (p.get("nodes") or []) + ] + edges = [ + { + "name": e.get("name"), + "description": e.get("description", ""), + "from_node_instance_id": e.get("from_node_instance_id"), + "to_node_instance_id": e.get("to_node_instance_id"), + "disabled": e.get("disabled", False), + "conditions": e.get("conditions"), + } + for e in (p.get("edges") or []) + ] + await self._do( + c, + "PATCH", + f"/v2/{_seg(org)}/pipelines/{_seg(pipeline_id)}", + { + "name": p.get("name"), + "description": p.get("description", ""), + "enabled": enabled, + "nodes": nodes, + "edges": edges, + }, + ) + + async def delete(self, path: str) -> None: + async with self._open() as c: + await self._do(c, "DELETE", path) diff --git a/routers/python/monad_embed/config.py b/routers/python/monad_embed/config.py new file mode 100644 index 0000000..5b97a13 --- /dev/null +++ b/routers/python/monad_embed/config.py @@ -0,0 +1,49 @@ +"""Configuration for the ``/embed`` router — uniform across every language.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Awaitable, Callable, Optional, Union + +from starlette.requests import Request + + +@dataclass +class Provision: + """What the host pre-provisions per tenant, resolved server-side. + + Never sent by the browser. + """ + + #: Ingress target. ``None`` → ingress goes to a dev/null sink. + destination_output_id: Optional[str] = None + #: Egress source. ``None`` → egress is unavailable. + source_input_id: Optional[str] = None + + +#: Resolve the authenticated request to the caller's Monad team id. Sync or async. +GetCustomerOrgID = Callable[[Request], Union[str, Awaitable[str]]] +#: Return a tenant's pre-provisioned resources. Sync or async. +GetProvisionedComponents = Callable[[str], Union[Provision, Awaitable[Provision]]] + + +@dataclass +class EmbedConfig: + """Uniform router configuration.""" + + #: Long-lived Monad API key. Server-side only. + api_key: str + #: Map the authenticated request → the caller's Monad team id. The one seam + #: only the host can fill. Raise (or return ``""``) to reject → 401. + get_customer_org_id: GetCustomerOrgID + #: Monad API base. Defaults to ``https://app.monad.com/api`` (production); + #: set only for non-prod. + api_base: str = "https://app.monad.com/api" + #: Iframe origin returned by ``GET /embed/config``. Defaults to + #: ``https://app.monad.com/embed`` (production); set only for non-prod. + frame_origin: str = "https://app.monad.com/embed" + #: Per-tenant pre-provisioned resources. ``None`` → ingress uses dev/null and + #: egress is unavailable. + get_provisioned_components: Optional[GetProvisionedComponents] = None + #: Restrict the catalog to these connector type ids. ``None`` → all. + catalog_allow: Optional[list[str]] = None diff --git a/routers/python/monad_embed/errors.py b/routers/python/monad_embed/errors.py new file mode 100644 index 0000000..451d95b --- /dev/null +++ b/routers/python/monad_embed/errors.py @@ -0,0 +1,27 @@ +"""Error types for the ``/embed`` router.""" + +from __future__ import annotations + + +class EmbedError(Exception): + """An error carrying the HTTP status + stable code from the contract's error model.""" + + def __init__(self, status: int, code: str, message: str) -> None: + super().__init__(message) + self.status = status + self.code = code + self.message = message + + +class MonadError(Exception): + """Raised by the Monad client on an API failure. Mapped to ``502 upstream_error``. + + Carries the upstream status + internal detail for server-side logging; the + router surfaces only a generic message so the upstream response body never + reaches the browser. + """ + + def __init__(self, status: int, detail: str) -> None: + super().__init__(detail) + self.status = status + self.detail = detail diff --git a/routers/python/monad_embed/models.py b/routers/python/monad_embed/models.py new file mode 100644 index 0000000..3cc5b8b --- /dev/null +++ b/routers/python/monad_embed/models.py @@ -0,0 +1,44 @@ +"""Response models for the ``/embed`` contract (camelCase, per the spec).""" + +from __future__ import annotations + +from typing import Optional + +from pydantic import BaseModel + + +class ConfigResponse(BaseModel): + frameOrigin: str + apiBase: str + + +class Session(BaseModel): + sessionToken: str + organizationId: str + expiresAt: str + + +class CatalogType(BaseModel): + typeId: str + name: str + + +class ConfiguredConnector(BaseModel): + id: str + typeId: str + name: str + + +class BuiltPipeline(BaseModel): + pipelineId: str + outputId: str + status: str + active: bool + + +class PipelineStatus(BaseModel): + hasPipeline: bool + enabled: bool + pipelineId: Optional[str] = None + inputId: Optional[str] = None + outputId: Optional[str] = None diff --git a/routers/python/monad_embed/router.py b/routers/python/monad_embed/router.py new file mode 100644 index 0000000..7265d32 --- /dev/null +++ b/routers/python/monad_embed/router.py @@ -0,0 +1,219 @@ +"""The mountable ``/embed`` FastAPI router.""" + +from __future__ import annotations + +import functools +import inspect +import logging +from typing import Any, Awaitable, Callable, Optional + +from fastapi import APIRouter, Response +from fastapi.responses import JSONResponse +from starlette.requests import Request + +from .client import MonadClient, _seg +from .config import EmbedConfig, Provision +from .errors import EmbedError, MonadError +from .models import ConfigResponse + +logger = logging.getLogger("monad_embed") + + +def _error(status: int, code: str, message: str) -> JSONResponse: + return JSONResponse(status_code=status, content={"code": code, "message": message}) + + +async def _maybe_await(value: Any) -> Any: + if inspect.isawaitable(value): + return await value + return value + + +async def _resolve(config: EmbedConfig, request: Request) -> str: + try: + org = await _maybe_await(config.get_customer_org_id(request)) + except EmbedError: + raise + except Exception as exc: # noqa: BLE001 — any resolver failure means "not authenticated" + raise EmbedError( + 401, "unauthenticated", "Could not resolve a tenant for the request." + ) from exc + if not org: + raise EmbedError(401, "unauthenticated", "Could not resolve a tenant for the request.") + return org + + +async def _provision(config: EmbedConfig, org: str) -> Provision: + if config.get_provisioned_components is None: + return Provision() + return await _maybe_await(config.get_provisioned_components(org)) + + +def _require_kind(value: Optional[str]) -> str: + if value not in ("input", "output"): + raise EmbedError(400, "invalid_request", "'kind' must be 'input' or 'output'.") + return value + + +def _require_str(body: Any, field: str) -> str: + value = body.get(field) if isinstance(body, dict) else None + if not isinstance(value, str) or not value: + raise EmbedError(400, "invalid_request", f"Field '{field}' is required.") + return value + + +async def _json_body(request: Request) -> Any: + try: + return await request.json() + except Exception: # noqa: BLE001 — malformed/empty body → validated below + return None + + +def _guard( + fn: Callable[[Request], Awaitable[Response]], +) -> Callable[[Request], Awaitable[Response]]: + """Wrap a route so every failure returns the contract's uniform error body.""" + + @functools.wraps(fn) + async def wrapper(request: Request) -> Response: + try: + return await fn(request) + except EmbedError as exc: + return _error(exc.status, exc.code, exc.message) + except MonadError as exc: + # Translate Monad's own status codes into the contract's error model. + if exc.status == 404: + return _error( + 404, "not_found", "The referenced connector or pipeline does not exist." + ) + if exc.status == 409: + return _error(409, "conflict", "The request conflicts with existing state.") + # Anything else: log the detail server-side, return a generic 502. + logger.error("upstream Monad API call failed: %s", exc) + return _error(502, "upstream_error", "The upstream Monad API request failed.") + except Exception: # noqa: BLE001 + logger.exception("unexpected error handling embed request") + return _error(500, "internal_error", "An unexpected error occurred.") + + return wrapper + + +def embed_router( + config: EmbedConfig, *, monad_client: Optional[MonadClient] = None +) -> APIRouter: + """Build the ``/embed`` router. Mount with ``app.include_router(router, prefix="/embed")``. + + ``monad_client`` is an injection hook (mainly for tests); by default one is + built from ``config``. + """ + client = monad_client or MonadClient(config.api_key, config.api_base) + router = APIRouter() + + async def get_config(request: Request) -> Response: + return JSONResponse( + ConfigResponse(frameOrigin=config.frame_origin, apiBase=config.api_base).model_dump() + ) + + async def create_session(request: Request) -> Response: + org = await _resolve(config, request) + session = await client.mint_session(org) + return JSONResponse(session.model_dump()) + + async def list_catalog(request: Request) -> Response: + await _resolve(config, request) + kind = _require_kind(request.query_params.get("kind")) + types = await client.list_catalog(kind, config.catalog_allow) + return JSONResponse([t.model_dump() for t in types]) + + async def list_connectors(request: Request) -> Response: + org = await _resolve(config, request) + kind = _require_kind(request.query_params.get("kind")) + rows = await client.list_connectors(org, kind) + return JSONResponse([r.model_dump() for r in rows]) + + async def build_ingress(request: Request) -> Response: + org = await _resolve(config, request) + body = await _json_body(request) + input_id = _require_str(body, "inputId") + name = _require_str(body, "name") + prov = await _provision(config, org) + if prov.destination_output_id: + built = await client.wire_pipeline(org, input_id, prov.destination_output_id, name) + else: + built = await client.build_dev_null(org, input_id, name) + return JSONResponse(status_code=201, content=built.model_dump()) + + async def build_egress(request: Request) -> Response: + org = await _resolve(config, request) + body = await _json_body(request) + output_id = _require_str(body, "outputId") + name = _require_str(body, "name") + prov = await _provision(config, org) + if not prov.source_input_id: + raise EmbedError( + 500, + "internal_error", + "No source input is provisioned for this tenant; egress cannot be built.", + ) + built = await client.wire_pipeline(org, prov.source_input_id, output_id, name) + return JSONResponse(status_code=201, content=built.model_dump()) + + async def get_pipeline_status(request: Request) -> Response: + org = await _resolve(config, request) + connector_id = request.query_params.get("connectorId") + if not connector_id: + raise EmbedError(400, "invalid_request", "Query 'connectorId' is required.") + kind = _require_kind(request.query_params.get("kind")) + if kind == "input": + status = await client.status_by_input(org, connector_id) + else: + status = await client.find_by_output(org, connector_id) + return JSONResponse(status.model_dump(exclude_none=True)) + + async def set_pipeline_state(request: Request) -> Response: + org = await _resolve(config, request) + body = await _json_body(request) + pipeline_id = _require_str(body, "pipelineId") + enabled = body.get("enabled") if isinstance(body, dict) else None + if not isinstance(enabled, bool): + raise EmbedError(400, "invalid_request", "Field 'enabled' must be a boolean.") + await client.set_enabled(org, pipeline_id, enabled) + return Response(status_code=204) + + async def remove_integration(request: Request) -> Response: + org = await _resolve(config, request) + body = await _json_body(request) + connector_id = _require_str(body, "connectorId") + kind = _require_kind(body.get("kind") if isinstance(body, dict) else None) + + if kind == "input": + status = await client.status_by_input(org, connector_id) + prov = await _provision(config, org) + keep_store = bool( + prov.destination_output_id + and status.outputId + and prov.destination_output_id == status.outputId + ) + if status.pipelineId: + await client.delete(f"/v2/{_seg(org)}/pipelines/{_seg(status.pipelineId)}") + await client.delete(f"/v1/{_seg(org)}/inputs/{_seg(connector_id)}") + if status.outputId and not keep_store: + await client.delete(f"/v1/{_seg(org)}/outputs/{_seg(status.outputId)}") + else: + status = await client.find_by_output(org, connector_id) + if status.pipelineId: + await client.delete(f"/v2/{_seg(org)}/pipelines/{_seg(status.pipelineId)}") + # Keep the shared source input; remove only the user's output. + await client.delete(f"/v1/{_seg(org)}/outputs/{_seg(connector_id)}") + return Response(status_code=204) + + router.add_api_route("/config", _guard(get_config), methods=["GET"]) + router.add_api_route("/session", _guard(create_session), methods=["POST"]) + router.add_api_route("/catalog", _guard(list_catalog), methods=["GET"]) + router.add_api_route("/connectors", _guard(list_connectors), methods=["GET"]) + router.add_api_route("/pipelines/ingress", _guard(build_ingress), methods=["POST"]) + router.add_api_route("/pipelines/egress", _guard(build_egress), methods=["POST"]) + router.add_api_route("/pipelines", _guard(get_pipeline_status), methods=["GET"]) + router.add_api_route("/pipelines/state", _guard(set_pipeline_state), methods=["POST"]) + router.add_api_route("/pipelines/remove", _guard(remove_integration), methods=["POST"]) + return router diff --git a/routers/python/pyproject.toml b/routers/python/pyproject.toml new file mode 100644 index 0000000..772a589 --- /dev/null +++ b/routers/python/pyproject.toml @@ -0,0 +1,22 @@ +[project] +name = "monad-embed" +version = "0.1.0" +description = "Mountable /embed backend router (FastAPI) for a Monad embed integration." +readme = "README.md" +requires-python = ">=3.10" +license = { text = "Apache-2.0" } +authors = [{ name = "Monad Inc." }] +dependencies = ["fastapi>=0.110", "httpx>=0.27"] + +[project.optional-dependencies] +test = ["pytest>=8"] + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["monad_embed"] + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/routers/python/tests/test_router.py b/routers/python/tests/test_router.py new file mode 100644 index 0000000..7e47def --- /dev/null +++ b/routers/python/tests/test_router.py @@ -0,0 +1,129 @@ +import httpx +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from monad_embed import EmbedConfig, MonadClient, Provision, embed_router + + +def _monad_handler(request: httpx.Request) -> httpx.Response: + """Stands in for the Monad API — just the endpoints these tests hit.""" + m, p = request.method, request.url.path + if m == "POST" and p == "/v3/sessions": + return httpx.Response(200, json={"session_token": "tok", "expires_at": "2026-01-01T00:00:00Z"}) + if m == "GET" and p == "/v1/inputs": + return httpx.Response( + 200, + json=[ + {"type_id": "aws-cloudtrail", "name": "AWS"}, + {"type_id": "secret", "name": "Hidden"}, + ], + ) + if m == "POST" and p == "/v2/org_1/outputs": + return httpx.Response(200, json={"id": "out_devnull"}) + if m == "POST" and p == "/v2/org_1/pipelines/": + return httpx.Response(200, json={"id": "pipe_1"}) + if m == "GET" and p == "/v2/org_1/pipelines/pipe_1/status": + return httpx.Response(200, json={"status": "Running"}) + return httpx.Response(500, json={"error": f"unmocked {m} {p}"}) + + +def make_client(over=None, resolve=lambda req: "org_1") -> TestClient: + cfg = EmbedConfig( + api_key="k", + api_base="http://monad", + frame_origin="https://app.monad.com/embed", + get_customer_org_id=resolve, + ) + if over: + over(cfg) + mc = MonadClient("k", "http://monad", transport=httpx.MockTransport(_monad_handler)) + app = FastAPI() + app.include_router(embed_router(cfg, monad_client=mc), prefix="/embed") + return TestClient(app) + + +def test_get_config(): + res = make_client(resolve=lambda req: (_ for _ in ()).throw(AssertionError("no auth"))).get( + "/embed/config" + ) + assert res.status_code == 200 + assert res.json() == {"frameOrigin": "https://app.monad.com/embed", "apiBase": "http://monad"} + + +def test_config_defaults(): + # api_base + frame_origin omitted → production defaults. + cfg = EmbedConfig(api_key="k", get_customer_org_id=lambda req: "org_1") + app = FastAPI() + app.include_router(embed_router(cfg), prefix="/embed") + res = TestClient(app).get("/embed/config") + assert res.json() == { + "frameOrigin": "https://app.monad.com/embed", + "apiBase": "https://app.monad.com/api", + } + + +def test_session(): + res = make_client().post("/embed/session") + assert res.status_code == 200 + assert res.json() == { + "sessionToken": "tok", + "organizationId": "org_1", + "expiresAt": "2026-01-01T00:00:00Z", + } + + +def test_catalog_allow_list(): + res = make_client(over=lambda c: setattr(c, "catalog_allow", ["aws-cloudtrail"])).get( + "/embed/catalog?kind=input" + ) + assert res.status_code == 200 + assert res.json() == [{"typeId": "aws-cloudtrail", "name": "AWS"}] + + +def test_ingress_dev_null(): + res = make_client().post("/embed/pipelines/ingress", json={"inputId": "in_1", "name": "CT"}) + assert res.status_code == 201 + body = res.json() + assert body["outputId"] == "out_devnull" + assert body["active"] is True + + +def test_ingress_store(): + res = make_client(over=lambda c: setattr(c, "get_provisioned_components", lambda org: Provision(destination_output_id="out_store"))).post( + "/embed/pipelines/ingress", json={"inputId": "in_1", "name": "CT"} + ) + assert res.status_code == 201 + assert res.json()["outputId"] == "out_store" + + +def test_egress_without_source_500s(): + res = make_client().post("/embed/pipelines/egress", json={"outputId": "out_1", "name": "Splunk"}) + assert res.status_code == 500 + assert res.json()["code"] == "internal_error" + + +def test_unauthenticated(): + res = make_client(resolve=lambda req: "").post("/embed/session") + assert res.status_code == 401 + assert res.json()["code"] == "unauthenticated" + + +def test_invalid_kind(): + res = make_client().get("/embed/catalog?kind=nope") + assert res.status_code == 400 + assert res.json()["code"] == "invalid_request" + + +def test_missing_body_field(): + res = make_client().post("/embed/pipelines/ingress", json={"name": "x"}) + assert res.status_code == 400 + + +def test_not_found(): + res = make_client().get("/embed/nope") + assert res.status_code == 404 + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-q"])) From decd7e44ca2e8db37cbd8ec65cf3cb8a4ca4c39f Mon Sep 17 00:00:00 2001 From: clippy Date: Fri, 31 Jul 2026 15:42:33 -0700 Subject: [PATCH 2/5] test(conformance): drive the Python router in live mode Parameterizes the Python conformance server from env, matching TS/Go. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_011ASKA2VrufrNLGGrcFjY7n --- conformance/servers/py_server.py | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/conformance/servers/py_server.py b/conformance/servers/py_server.py index 71b15fc..8aa59f9 100644 --- a/conformance/servers/py_server.py +++ b/conformance/servers/py_server.py @@ -1,4 +1,9 @@ -"""Boot the Python router for conformance testing, pointed at the mock Monad.""" +"""Boot the Python router for conformance testing. + +Default (mock) mode points at the in-memory mock via ``MONAD_API_BASE``; live +mode sets the same knobs to real Monad staging values. Every value falls back to +the mock fixture default, so nothing changes for the existing hermetic run. +""" import os @@ -7,16 +12,23 @@ from monad_embed import EmbedConfig, Provision, embed_router +# A provisioned id may be intentionally empty (a live tenant with no store) → +# treat "" as "not provisioned" so the router falls back to a dev/null sink. +_store = os.environ.get("MONAD_STORE_ID", "out_store") or None +_source = os.environ.get("MONAD_SOURCE_ID", "in_source") or None +# Empty allow-list → expose the whole catalog (None), never the empty set. +_allow = [s.strip() for s in os.environ.get("MONAD_CATALOG_ALLOW", "aws-cloudtrail,okta-systemlog").split(",") if s.strip()] or None + app = FastAPI() app.include_router( embed_router( EmbedConfig( - api_key="conf-key", + api_key=os.environ.get("MONAD_API_KEY", "conf-key"), api_base=os.environ["MONAD_API_BASE"], - frame_origin="https://app.monad.com/embed", - get_customer_org_id=lambda req: "org_conf", - get_provisioned_components=lambda org: Provision(destination_output_id="out_store", source_input_id="in_source"), - catalog_allow=["aws-cloudtrail", "okta-systemlog"], + frame_origin=os.environ.get("MONAD_FRAME_ORIGIN", "https://app.monad.com/embed"), + get_customer_org_id=lambda req: os.environ.get("MONAD_ORG_ID", "org_conf"), + get_provisioned_components=lambda org: Provision(destination_output_id=_store, source_input_id=_source), + catalog_allow=_allow, ) ), prefix="/embed", From dcfca8b888d91f5872c4cccb3582402379c73e26 Mon Sep 17 00:00:00 2001 From: curtis Date: Tue, 4 Aug 2026 12:32:12 -0400 Subject: [PATCH 3/5] fix(embed): correct the Python router against the real Monad API [PRO-457] Ports the fixes from the Go and TypeScript routers so all three stay contract-identical on the wire. - resolve a connector's pipeline via `component_of` instead of scanning every pipeline; the scan sent no `limit` and Monad defaults it to 10 - `set_enabled` PATCHes `{enabled}` alone now that PATCH is a true partial update, instead of rebuilding and replacing the node/edge graph - drain the connector list rather than one `limit=1000` request - send `type` on output create; `output_type` is deprecated - drop the speculative `data` / `config` response-shape fallbacks - map `kind` to its path segment explicitly rather than appending "s" --- routers/python/monad_embed/client.py | 187 +++++++++++++-------------- routers/python/monad_embed/router.py | 21 ++- 2 files changed, 97 insertions(+), 111 deletions(-) diff --git a/routers/python/monad_embed/client.py b/routers/python/monad_embed/client.py index ad82810..c58c2f4 100644 --- a/routers/python/monad_embed/client.py +++ b/routers/python/monad_embed/client.py @@ -25,6 +25,11 @@ _POLL_ATTEMPTS = 15 _POLL_INTERVAL = 2.0 +# Rows per request when draining a Monad list. Monad defaults ``limit`` to 10 +# and enforces no maximum, so this is a round-trip/response-size trade-off only: +# correctness comes from draining every page. +_PAGE_SIZE = 200 + def _seg(value: Any) -> str: """URL-encode a single path segment so browser-supplied ids can't inject @@ -32,6 +37,12 @@ def _seg(value: Any) -> str: return quote(str(value), safe="") +def _collection(kind: str) -> str: + """The contract's singular ``kind`` → Monad's collection path segment. + Spelled out rather than appending "s", so the mapping is a fact.""" + return "inputs" if kind == "input" else "outputs" + + class MonadClient: """Talks to the Monad API with the host's long-lived key.""" @@ -79,7 +90,7 @@ async def list_catalog( self, kind: str, allow: Optional[list[str]] ) -> list[CatalogType]: async with self._open() as c: - data = await self._do(c, "GET", f"/v1/{kind}s") + data = await self._do(c, "GET", f"/v1/{_collection(kind)}") allow_set = set(allow) if allow else None out: list[CatalogType] = [] for t in data or []: @@ -89,14 +100,36 @@ async def list_catalog( return out async def list_connectors(self, org: str, kind: str) -> list[ConfiguredConnector]: + """Every connector of a kind the tenant has configured. + + Monad pages this at ``limit=10`` by default with no maximum, and the + ``/embed`` contract returns a bare array with no pagination — so + draining the pages is the router's job. One large ``limit`` instead + would silently truncate whichever tenant outgrows it. + """ + key = _collection(kind) + out: list[ConfiguredConnector] = [] async with self._open() as c: - page = await self._do(c, "GET", f"/v1/{_seg(org)}/{kind}s?limit=1000&offset=0") - # Monad returns the list as null (not []) when a tenant has none, so - # coalesce with `or []` — a bare .get(key, []) would return that null. - rows = (page or {}).get(f"{kind}s") or [] - return [ - ConfiguredConnector(id=r["id"], typeId=r["type"], name=r["name"]) for r in rows - ] + offset = 0 + while True: + page = await self._do( + c, "GET", f"/v1/{_seg(org)}/{key}?limit={_PAGE_SIZE}&offset={offset}" + ) + # Monad returns the list as null (not []) for an empty page, so + # coalesce with `or []` — a bare .get(key, []) would return null. + rows = (page or {}).get(key) or [] + out.extend( + ConfiguredConnector(id=r["id"], typeId=r["type"], name=r["name"]) + for r in rows + ) + # A short page is the last page; `total` only lets us stop one + # round trip earlier when the count divides evenly. + if len(rows) < _PAGE_SIZE: + return out + total = ((page or {}).get("pagination") or {}).get("total") + if isinstance(total, int) and len(out) >= total: + return out + offset += _PAGE_SIZE async def wire_pipeline( self, org: str, input_id: str, output_id: str, name: str @@ -139,7 +172,8 @@ async def build_dev_null(self, org: str, input_id: str, name: str) -> BuiltPipel "POST", f"/v2/{_seg(org)}/outputs", { - "output_type": "dev-null", + # `type` is canonical; `output_type` is a deprecated alias. + "type": "dev-null", "name": f"{name} → /dev/null", "description": "Auto-created sink for embed pipeline", "promise_id": "", @@ -148,107 +182,62 @@ async def build_dev_null(self, org: str, input_id: str, name: str) -> BuiltPipel ) return await self.wire_pipeline(org, input_id, out["id"], name) - async def _list_pipelines(self, c: httpx.AsyncClient, org: str) -> list[dict]: - data = await self._do(c, "GET", f"/v2/{_seg(org)}/pipelines/") - if isinstance(data, list): - return data - if isinstance(data, dict): - return data.get("pipelines") or data.get("data") or [] - return [] - - async def _get_pipeline(self, c: httpx.AsyncClient, org: str, pid: str) -> dict: + async def _pipeline_nodes(self, c: httpx.AsyncClient, org: str, pid: str) -> list[dict]: + """A pipeline's wiring. The detail response is flat — the nodes sit at + the top level, not under a ``config`` envelope.""" data = await self._do(c, "GET", f"/v2/{_seg(org)}/pipelines/{_seg(pid)}") - if isinstance(data, dict): - return data.get("config") or data - return {} + return (data or {}).get("nodes") or [] - async def status_by_input(self, org: str, input_id: str) -> PipelineStatus: - async with self._open() as c: - for summary in await self._list_pipelines(c, org): - pid = summary.get("id") - if not pid: - continue - try: - p = await self._get_pipeline(c, org, pid) - except MonadError: - continue - nodes = p.get("nodes") or [] - in_node = next( - (n for n in nodes if n.get("component_type") == "input" and n.get("component_id") == input_id), - None, - ) - if in_node is None: - continue - out_node = next((n for n in nodes if n.get("component_type") == "output"), None) - return PipelineStatus( - hasPipeline=True, - enabled=bool(p.get("enabled")), - pipelineId=pid, - outputId=out_node.get("component_id") if out_node else None, - ) - return PipelineStatus(hasPipeline=False, enabled=False) + async def pipeline_for(self, org: str, kind: str, connector_id: str) -> PipelineStatus: + """The pipeline a configured connector is wired into. + + Monad answers this directly: ``GET /v1/{org}/{kind}s/{id}`` returns + ``component_of``, the pipelines the component is a node of. Walking the + org's pipeline list instead would be both O(n) and wrong — that list + pages at 10, so any pipeline past the first page would read as "not + connected". - async def find_by_output(self, org: str, output_id: str) -> PipelineStatus: + ``component_of`` carries no wiring (the datastore fills only a summary + projection), so resolving the peer connector costs one further fetch. + Raises :class:`MonadError` with status 404 when the connector is gone. + """ async with self._open() as c: - for summary in await self._list_pipelines(c, org): - pid = summary.get("id") - if not pid: - continue - try: - p = await self._get_pipeline(c, org, pid) - except MonadError: - continue - nodes = p.get("nodes") or [] - out_node = next( - (n for n in nodes if n.get("component_type") == "output" and n.get("component_id") == output_id), - None, - ) - if out_node is None: - continue - in_node = next((n for n in nodes if n.get("component_type") == "input"), None) - return PipelineStatus( - hasPipeline=True, - enabled=bool(p.get("enabled")), - pipelineId=pid, - inputId=in_node.get("component_id") if in_node else None, - ) - return PipelineStatus(hasPipeline=False, enabled=False) + connector = await self._do( + c, "GET", f"/v1/{_seg(org)}/{_collection(kind)}/{_seg(connector_id)}" + ) + pipelines = (connector or {}).get("component_of") or [] + if not pipelines or not pipelines[0].get("id"): + return PipelineStatus(hasPipeline=False, enabled=False) + + pipeline = pipelines[0] + peer_type = "output" if kind == "input" else "input" + nodes = await self._pipeline_nodes(c, org, pipeline["id"]) + peer = next((n for n in nodes if n.get("component_type") == peer_type), None) + peer_id = peer.get("component_id") if peer else None + + return PipelineStatus( + hasPipeline=True, + enabled=bool(pipeline.get("enabled")), + pipelineId=pipeline["id"], + outputId=peer_id if kind == "input" else None, + inputId=peer_id if kind == "output" else None, + ) async def set_enabled(self, org: str, pipeline_id: str, enabled: bool) -> None: + """Flip a pipeline's enabled flag. + + ``PATCH`` is a true partial update: omitted fields keep their stored + value and the node/edge graph is preserved untouched. Reading the + pipeline and sending it back would replace the graph with whatever + subset of fields the round trip happened to reproduce — silently + dropping node ``config_overrides`` and edge ``schema_detection_spec``. + """ async with self._open() as c: - p = await self._get_pipeline(c, org, pipeline_id) - nodes = [ - { - "id": n.get("id"), - "slug": n.get("slug"), - "component_id": n.get("component_id"), - "component_type": n.get("component_type"), - "enabled": n.get("enabled", True), - } - for n in (p.get("nodes") or []) - ] - edges = [ - { - "name": e.get("name"), - "description": e.get("description", ""), - "from_node_instance_id": e.get("from_node_instance_id"), - "to_node_instance_id": e.get("to_node_instance_id"), - "disabled": e.get("disabled", False), - "conditions": e.get("conditions"), - } - for e in (p.get("edges") or []) - ] await self._do( c, "PATCH", f"/v2/{_seg(org)}/pipelines/{_seg(pipeline_id)}", - { - "name": p.get("name"), - "description": p.get("description", ""), - "enabled": enabled, - "nodes": nodes, - "edges": edges, - }, + {"enabled": enabled}, ) async def delete(self, path: str) -> None: diff --git a/routers/python/monad_embed/router.py b/routers/python/monad_embed/router.py index 7265d32..e9684f7 100644 --- a/routers/python/monad_embed/router.py +++ b/routers/python/monad_embed/router.py @@ -164,10 +164,7 @@ async def get_pipeline_status(request: Request) -> Response: if not connector_id: raise EmbedError(400, "invalid_request", "Query 'connectorId' is required.") kind = _require_kind(request.query_params.get("kind")) - if kind == "input": - status = await client.status_by_input(org, connector_id) - else: - status = await client.find_by_output(org, connector_id) + status = await client.pipeline_for(org, kind, connector_id) return JSONResponse(status.model_dump(exclude_none=True)) async def set_pipeline_state(request: Request) -> Response: @@ -186,23 +183,23 @@ async def remove_integration(request: Request) -> Response: connector_id = _require_str(body, "connectorId") kind = _require_kind(body.get("kind") if isinstance(body, dict) else None) + status = await client.pipeline_for(org, kind, connector_id) + # The pipeline references its connectors, so it goes first. + if status.pipelineId: + await client.delete(f"/v2/{_seg(org)}/pipelines/{_seg(status.pipelineId)}") + if kind == "input": - status = await client.status_by_input(org, connector_id) + await client.delete(f"/v1/{_seg(org)}/inputs/{_seg(connector_id)}") + # The tenant's provisioned store is shared; only a sink this + # pipeline created on the fly gets torn down with it. prov = await _provision(config, org) keep_store = bool( prov.destination_output_id - and status.outputId and prov.destination_output_id == status.outputId ) - if status.pipelineId: - await client.delete(f"/v2/{_seg(org)}/pipelines/{_seg(status.pipelineId)}") - await client.delete(f"/v1/{_seg(org)}/inputs/{_seg(connector_id)}") if status.outputId and not keep_store: await client.delete(f"/v1/{_seg(org)}/outputs/{_seg(status.outputId)}") else: - status = await client.find_by_output(org, connector_id) - if status.pipelineId: - await client.delete(f"/v2/{_seg(org)}/pipelines/{_seg(status.pipelineId)}") # Keep the shared source input; remove only the user's output. await client.delete(f"/v1/{_seg(org)}/outputs/{_seg(connector_id)}") return Response(status_code=204) From a01690be2f71f62cd76079c127619bdc9d9e9440 Mon Sep 17 00:00:00 2001 From: clippy Date: Tue, 8 Sep 2026 13:51:01 -0700 Subject: [PATCH 4/5] fix(embed): harden Python router pagination listConnectors: drain until a short page; drop the pagination.total early-break (truncates when Monad under-reports total); add _MAX_PAGES cap so an upstream that never returns a short page bounds the loop instead of spinning / OOMing. (Body-size limits are handled at the ASGI/proxy layer for FastAPI.) Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_011ASKA2VrufrNLGGrcFjY7n --- routers/python/monad_embed/client.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/routers/python/monad_embed/client.py b/routers/python/monad_embed/client.py index c58c2f4..cf200b8 100644 --- a/routers/python/monad_embed/client.py +++ b/routers/python/monad_embed/client.py @@ -30,6 +30,12 @@ # correctness comes from draining every page. _PAGE_SIZE = 200 +# Hard ceiling on pages drained from a single list, so an upstream that never +# returns a short page (e.g. offset-clamping) bounds the loop instead of +# spinning forever / exhausting memory. _MAX_PAGES * _PAGE_SIZE = 200k rows — +# far beyond any real tenant. +_MAX_PAGES = 1000 + def _seg(value: Any) -> str: """URL-encode a single path segment so browser-supplied ids can't inject @@ -110,8 +116,11 @@ async def list_connectors(self, org: str, kind: str) -> list[ConfiguredConnector key = _collection(kind) out: list[ConfiguredConnector] = [] async with self._open() as c: - offset = 0 - while True: + # A short page is the only safe stop; trusting pagination.total to + # break early truncates the list when Monad under-reports it. + # _MAX_PAGES bounds an upstream that never returns a short page. + for page_index in range(_MAX_PAGES): + offset = page_index * _PAGE_SIZE page = await self._do( c, "GET", f"/v1/{_seg(org)}/{key}?limit={_PAGE_SIZE}&offset={offset}" ) @@ -122,14 +131,9 @@ async def list_connectors(self, org: str, kind: str) -> list[ConfiguredConnector ConfiguredConnector(id=r["id"], typeId=r["type"], name=r["name"]) for r in rows ) - # A short page is the last page; `total` only lets us stop one - # round trip earlier when the count divides evenly. if len(rows) < _PAGE_SIZE: return out - total = ((page or {}).get("pagination") or {}).get("total") - if isinstance(total, int) and len(out) >= total: - return out - offset += _PAGE_SIZE + raise MonadError(502, f"pagination exceeded {_MAX_PAGES} pages draining {key}") async def wire_pipeline( self, org: str, input_id: str, output_id: str, name: str From 218eff9483f514bf6da23afc9bacb306d84db399 Mon Sep 17 00:00:00 2001 From: clippy Date: Tue, 8 Sep 2026 14:26:47 -0700 Subject: [PATCH 5/5] fix(embed): Python router orphan-safety (D/E/F) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - wire_pipeline: a transient status-poll failure no longer fails the request — the pipeline exists, so return it as built (last-known status) rather than orphaning it and inviting a retry duplicate. (D) - build_dev_null: best-effort delete the created sink if wiring fails. (E) - pipeline_for: document the one-pipeline-per-connector invariant behind component_of[0]. (F) (Router error redaction (H) was already clean in the Python router.) Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_011ASKA2VrufrNLGGrcFjY7n --- routers/python/monad_embed/client.py | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/routers/python/monad_embed/client.py b/routers/python/monad_embed/client.py index cf200b8..5874424 100644 --- a/routers/python/monad_embed/client.py +++ b/routers/python/monad_embed/client.py @@ -158,9 +158,16 @@ async def wire_pipeline( async with self._open() as c: created = await self._do(c, "POST", f"/v2/{_seg(org)}/pipelines/", body) pid = created["id"] + # The pipeline now EXISTS. Polling for Running is a courtesy — a + # transient status-poll failure must NOT fail the request, or the + # caller treats a live pipeline as un-built and retries into a + # duplicate. On a poll error we stop with the last-known status. status = "Pending" for _ in range(self._poll_attempts): - s = await self._do(c, "GET", f"/v2/{_seg(org)}/pipelines/{_seg(pid)}/status") + try: + s = await self._do(c, "GET", f"/v2/{_seg(org)}/pipelines/{_seg(pid)}/status") + except MonadError: + break status = (s or {}).get("status") or status if status in ("Running", "Erroring"): break @@ -184,7 +191,20 @@ async def build_dev_null(self, org: str, input_id: str, name: str) -> BuiltPipel "config": {"settings": {}, "secrets": {}}, }, ) - return await self.wire_pipeline(org, input_id, out["id"], name) + try: + return await self.wire_pipeline(org, input_id, out["id"], name) + except Exception: + # The sink was created but wiring failed. Best-effort delete it so a + # retry doesn't accumulate dev/null outputs; if the cleanup itself + # fails, leave it for orphan monitoring + # (docs/embed-security-and-operations.md) and surface the original + # error. Create/delete are non-atomic — Monad offers no transaction. + try: + async with self._open() as c: + await self._do(c, "DELETE", f"/v1/{_seg(org)}/outputs/{_seg(out['id'])}") + except Exception: + pass + raise async def _pipeline_nodes(self, c: httpx.AsyncClient, org: str, pid: str) -> list[dict]: """A pipeline's wiring. The detail response is flat — the nodes sit at @@ -209,6 +229,10 @@ async def pipeline_for(self, org: str, kind: str, connector_id: str) -> Pipeline connector = await self._do( c, "GET", f"/v1/{_seg(org)}/{_collection(kind)}/{_seg(connector_id)}" ) + # The embed flow wires each connector into exactly one pipeline + # (Monad guarantees a pipeline has a single input, and embed never + # adds a connector to a second pipeline), so component_of has at most + # one entry and taking the first is unambiguous. pipelines = (connector or {}).get("component_of") or [] if not pipelines or not pipelines[0].get("id"): return PipelineStatus(hasPipeline=False, enabled=False)