Buckets:

download
raw
27.6 kB
"""API Channel implementation using EnterpriseWorkflowServer."""
import asyncio
import logging
from typing import Any, Callable, Dict, Optional, Sequence
# `uvicorn` and `starlette` are OPTIONAL dependencies under the `server` extra.
# Per `rules/dependencies.md` § "Declared = Imported": optional-extra imports
# MUST raise loudly with an actionable error naming the extra.
try:
import uvicorn
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import Response
except ImportError as exc: # pragma: no cover — covered by structural invariant test
raise ImportError(
"kailash.channels.api_channel requires server dependencies (starlette, "
"uvicorn). Install with: pip install 'kailash[server]'"
) from exc
from ..servers import EnterpriseWorkflowServer
from ..utils.http_errors import safe_http_detail
from ..workflow import Workflow
from .base import (
Channel,
ChannelConfig,
ChannelEvent,
ChannelResponse,
ChannelStatus,
ChannelType,
)
logger = logging.getLogger(__name__)
class APIChannel(Channel):
"""HTTP API channel implementation using EnterpriseWorkflowServer.
This channel provides RESTful API access to workflows and session management
through the existing EnterpriseWorkflowServer infrastructure.
"""
def __init__(
self,
config: ChannelConfig,
workflow_server: Optional[EnterpriseWorkflowServer] = None,
):
"""Initialize API channel.
Args:
config: Channel configuration
workflow_server: Optional existing workflow server, will create one if not provided
"""
super().__init__(config)
# Create or use provided workflow server
if workflow_server:
self.workflow_server = workflow_server
else:
self.workflow_server = self._create_workflow_server()
self.app: Any = (
self.workflow_server.app
) # FastAPI instance; typed Any to avoid circular nexus import
self._server: Optional[uvicorn.Server] = None
self._server_task: Optional[asyncio.Task] = None
# Add channel-specific endpoints
self._setup_channel_endpoints()
logger.info(
f"Initialized API channel {self.name} on {config.host}:{config.port}"
)
def _create_workflow_server(self) -> EnterpriseWorkflowServer:
"""Create a new workflow server with channel configuration."""
# Extract server config from channel config
server_title = self.config.extra_config.get("title", f"{self.name} API Server")
server_description = self.config.extra_config.get(
"description", f"API server for {self.name} channel"
)
# CORS configuration
cors_origins = self.config.extra_config.get("cors_origins", [])
return EnterpriseWorkflowServer(
title=server_title,
description=server_description,
cors_origins=cors_origins,
# `ChannelConfig.enable_auth` was reported by /channel/info and
# read by NO enforcement path -- a documented security control
# that did nothing (zero-tolerance.md Rule 3c, noted in the #2025
# analysis). It is now load-bearing: it decides whether this
# channel keeps the server's fail-closed gate, and
# `auth_config` (already on ChannelConfig, likewise unused)
# supplies the credential.
#
# `None` means UNSTATED, and inherits the server's fail-closed
# default (#2072) -- an APIChannel is an HTTP server exposing
# POST /workflows/{name}/execute, so a caller who never considered
# authentication must not silently get an open one. Mapping the
# old `False` default straight through here would have left this
# channel serving exactly the anonymous workflow execution the
# rest of this change closes (security.md § Enforcement-Surface
# Parity). An EXPLICIT `enable_auth=False` is still honoured, and
# is never silent: resolve_server_auth logs a WARN naming the
# exposure and its wiring (security.md § Secure-Default).
require_auth=(
True if self.config.enable_auth is None else self.config.enable_auth
),
auth_config=self.config.auth_config or None,
enable_durability=self.config.extra_config.get("enable_durability", True),
enable_resource_management=self.config.extra_config.get(
"enable_resource_management", True
),
enable_async_execution=self.config.extra_config.get(
"enable_async_execution", True
),
enable_health_checks=self.config.extra_config.get(
"enable_health_checks", True
),
)
def _setup_channel_endpoints(self) -> None:
"""Add channel-specific endpoints to the FastAPI app."""
@self.app.get("/channel/info")
async def get_channel_info():
"""Get information about this API channel."""
return {
"channel_name": self.name,
"channel_type": self.channel_type.value,
"status": self.status.value,
"config": {
"host": self.config.host,
"port": self.config.port,
"enable_sessions": self.config.enable_sessions,
# Reports what this channel ACTUALLY enforces, not the raw
# tri-state: an unstated `None` inherits the server's
# fail-closed gate, so it is reported as True (#2072).
"enable_auth": self.config.enable_auth is not False,
"enable_event_routing": self.config.enable_event_routing,
},
}
@self.app.post("/channel/events")
async def emit_channel_event(request: Request):
"""Emit an event through this channel."""
try:
data = await request.json()
event = ChannelEvent(
event_id=data.get(
"event_id", f"api_{asyncio.get_event_loop().time()}"
),
channel_name=self.name,
channel_type=self.channel_type,
event_type=data.get("event_type", "api_event"),
payload=data.get("payload", {}),
session_id=data.get("session_id"),
metadata=data.get("metadata", {}),
)
await self.emit_event(event)
return {"status": "success", "event_id": event.event_id}
except Exception as e:
raise HTTPException(
status_code=400,
detail=safe_http_detail(
e,
logger=logger,
context="emit channel event",
status_code=400,
),
) from e
@self.app.get("/channel/status")
async def get_channel_status():
"""Get detailed channel status."""
return await self.get_status()
@self.app.get("/channel/health")
async def get_channel_health():
"""Get channel health check."""
health = await self.health_check()
status_code = 200 if health["healthy"] else 503
return Response(
content=str(health),
status_code=status_code,
media_type="application/json",
)
async def start(self) -> None:
"""Start the API channel server."""
if self.status == ChannelStatus.RUNNING:
logger.warning(f"API channel {self.name} is already running")
return
try:
self.status = ChannelStatus.STARTING
self._setup_event_queue()
# Configure uvicorn server
config = uvicorn.Config(
app=self.app,
host=self.config.host,
port=self.config.port or 8000,
log_level="info" if logger.isEnabledFor(logging.INFO) else "warning",
access_log=False, # We'll handle our own logging
)
self._server = uvicorn.Server(config)
# Start server in background task
self._server_task = asyncio.create_task(self._server.serve())
# Wait a moment for server to start
await asyncio.sleep(0.1)
self.status = ChannelStatus.RUNNING
# Emit startup event
await self.emit_event(
ChannelEvent(
event_id=f"api_startup_{asyncio.get_event_loop().time()}",
channel_name=self.name,
channel_type=self.channel_type,
event_type="channel_started",
payload={"host": self.config.host, "port": self.config.port},
)
)
logger.info(
f"API channel {self.name} started on {self.config.host}:{self.config.port}"
)
except Exception as e:
self.status = ChannelStatus.ERROR
logger.error(f"Failed to start API channel {self.name}: {e}")
raise
async def stop(self) -> None:
"""Stop the API channel server.
Returns only once the server task has actually finished; the channel is
then ``STOPPED``.
If THIS coroutine is cancelled while it waits -- a shutdown deadline
expiring, a supervising task group tearing down -- the
``CancelledError`` propagates to the caller rather than being absorbed.
The channel is left ``STOPPING``, which is the truthful record: the
server task was not established as stopped. Call ``stop()`` again to
finish; the retained task handle is what makes that retry possible.
``_cleanup`` runs on EVERY exit path including that one, because it
cancels ``_running_task`` -- a DIFFERENT task from ``_server_task`` --
and the dominant real trigger for the cancelled path is a task group or
``asyncio.timeout`` tearing down, where nobody calls ``stop()`` a second
time. Skipping it there orphans a pending task ("Task was destroyed but
it is pending") and keeps the runtime reference alive, which is a
LEAK introduced in the act of fixing the swallowed cancellation.
"""
if self.status == ChannelStatus.STOPPED:
return
# Tracks whether the try-path already ran cleanup. The guard below CANNOT
# key on `status is not STOPPED`: once the status became conditional, a
# normal return with incomplete cleanup leaves STOPPING, which satisfies
# that test and runs `_cleanup` a SECOND time -- re-cancelling, burning
# another bounded join, and emitting a duplicate WARN on a path that did
# not leave the frame early at all.
cleanup_ran = False
try:
self.status = ChannelStatus.STOPPING
# Emit shutdown event
await self.emit_event(
ChannelEvent(
event_id=f"api_shutdown_{asyncio.get_event_loop().time()}",
channel_name=self.name,
channel_type=self.channel_type,
event_type="channel_stopping",
payload={},
)
)
# Stop the uvicorn server
if self._server:
self._server.should_exit = True
# Cancel the server task and establish that it stopped.
#
# ``await self._server_task`` inside ``except CancelledError: pass``
# cannot tell two different events apart, because both arrive at
# that await as the same exception type:
#
# 1. the server task ending in the cancellation we just
# requested -- expected, and the reason the handler exists;
# 2. THIS coroutine being cancelled by somebody else while it
# waits -- a shutdown deadline, a task group tearing down.
#
# Case 2 was therefore swallowed and the caller received a clean
# ``STOPPED`` for a stop that never finished. Worse, ``await task``
# makes the server task the awaited future, so cancelling the
# caller only re-requested cancellation of a task that already
# ignored it -- nothing reached this frame and the caller could be
# stranded indefinitely.
#
# ``asyncio.wait`` observes the task's completion without re-raising
# what the task ended with, and parks on its own future, so only a
# cancellation aimed at THIS coroutine surfaces here -- and it
# propagates. Same shape as the monitoring-stop fix in
# ``kailash/visualization/api.py`` (bb8a3f966).
if self._server_task and not self._server_task.done():
task = self._server_task
task.cancel()
await asyncio.wait({task})
# A task that died of a REAL error still surfaces, exactly as
# it did when this awaited the task directly; observing
# completion must not turn a crash into a silent clean stop.
if not task.cancelled():
server_error = task.exception()
if server_error is not None:
raise server_error
# STOPPED only when cleanup actually COMPLETED. An event task that
# ignored its cancellation is still live, and a status field is a
# return value an orchestrator acts on -- STOPPING is then the
# truthful record, exactly as it is on the cancelled path above.
cleaned = await self._cleanup()
cleanup_ran = True
self.status = self._status_after_cleanup(cleaned)
if self.status is ChannelStatus.STOPPED:
logger.info(f"API channel {self.name} stopped")
elif self.status is ChannelStatus.ERROR:
# NOT "stop it again". The event task died of a real error, so
# it is already gone and a retry would find nothing to cancel
# and report a clean STOPPED over a failed teardown (#2021).
logger.warning(
"API channel %s stop did NOT complete: its event task "
"FAILED. The channel is ERROR; retrying stop() will not "
"address it",
self.name,
)
else:
# The status says STOPPING; the log must not say "stopped".
# Gating the inner cleanup log and leaving this one one line
# away would be the same over-claiming shape, unfixed.
logger.warning(
"API channel %s stop did NOT complete; channel is STOPPING "
"and can be stopped again",
self.name,
)
except Exception as e:
# Deliberately ``Exception``, not ``BaseException``:
# ``CancelledError`` must pass through untouched so a caller
# cancelled mid-stop is not reclassified as a channel ERROR. The
# channel stays ``STOPPING``, which says the stop began and did not
# finish.
self.status = ChannelStatus.ERROR
logger.error(f"Error stopping API channel {self.name}: {e}")
raise
finally:
# The success path already ran ``_cleanup`` above and reached
# ``STOPPED``; anything else left this frame early -- a propagating
# ``CancelledError``, or an error re-raised as ERROR -- with
# ``_running_task`` still live. Cancelling it is synchronous, so the
# cancel lands even when the subsequent await is itself cancelled.
if not cleanup_ran:
try:
await self._cleanup()
except Exception:
# ``_cleanup`` swallows only ``CancelledError`` (base.py),
# so a ``_running_task`` that died of a REAL error re-raises
# here -- out of the ``finally`` -- and REPLACES the
# CancelledError this method exists to let through,
# demoting it to ``__context__``. That is the swallowed-
# cancellation defect F13 closed, reintroduced one layer
# down inside its own fix. ``Exception``, not
# ``BaseException``: a CancelledError raised by
# ``_cleanup``'s own await IS the caller's cancellation
# continuing and must replace nothing.
logger.warning(
"API channel %s: cleanup failed during an interrupted "
"stop; the original cancellation is preserved",
self.name,
exc_info=True,
)
async def handle_request(self, request: Dict[str, Any]) -> ChannelResponse:
"""Handle a request through the API channel.
Args:
request: Request data with workflow execution parameters
Returns:
ChannelResponse with execution results
"""
try:
workflow_name = request.get("workflow_name")
if not workflow_name:
return ChannelResponse(success=False, error="workflow_name is required")
# Check if workflow exists
if workflow_name not in self.workflow_server.workflows:
return ChannelResponse(
success=False, error=f"Workflow '{workflow_name}' not found"
)
# Execute workflow through server's runtime
workflow_registration = self.workflow_server.workflows[workflow_name]
inputs = request.get("inputs", {})
# Emit request event
await self.emit_event(
ChannelEvent(
event_id=f"api_request_{asyncio.get_event_loop().time()}",
channel_name=self.name,
channel_type=self.channel_type,
event_type="workflow_request",
payload={"workflow_name": workflow_name, "inputs": inputs},
session_id=request.get("session_id"),
)
)
# Execute workflow
if workflow_registration.type == "embedded":
workflow = workflow_registration.workflow
from kailash.workflow.input_envelope import bind_parameter_envelope
# Bind BOTH shapes: this channel serves the same registrations
# as the HTTP route, so a workflow reading `parameters.get(...)`
# must resolve here too. Passing `inputs` raw bound only bare
# top-level names and raised NameError for the convention.
#
# `inputs` here is NOT the opt-OUT form WorkflowRequest draws
# against `parameters`. Per the structural rule in
# `kailash/workflow/input_envelope.py`: WorkflowRequest offers
# the caller TWO slots so it can honour a choice; this handler
# offers ONE, so that slot is the arguments slot and binds.
# Reading the shared field NAME as the discriminator would
# leave this channel with no envelope path at all.
results, run_id = self.workflow_server.runtime.execute(
workflow, parameters=bind_parameter_envelope(inputs)
)
else:
# Handle proxied workflows
return ChannelResponse(
success=False,
error="Proxied workflows not yet supported in APIChannel",
)
# Emit completion event
await self.emit_event(
ChannelEvent(
event_id=f"api_completion_{asyncio.get_event_loop().time()}",
channel_name=self.name,
channel_type=self.channel_type,
event_type="workflow_completed",
payload={
"workflow_name": workflow_name,
"run_id": run_id,
"success": True,
},
session_id=request.get("session_id"),
)
)
return ChannelResponse(
success=True,
data={
"results": results,
"run_id": run_id,
"workflow_name": workflow_name,
},
metadata={"channel": self.name, "type": "api"},
)
except Exception as e:
detail = safe_http_detail(e, logger=logger, context="handle API request")
# Emit error event
await self.emit_event(
ChannelEvent(
event_id=f"api_error_{asyncio.get_event_loop().time()}",
channel_name=self.name,
channel_type=self.channel_type,
event_type="workflow_error",
payload={"error": detail, "request": request},
session_id=request.get("session_id"),
)
)
return ChannelResponse(
success=False,
error=detail,
metadata={"channel": self.name, "type": "api"},
)
def register_workflow(
self,
name: str,
workflow: Workflow,
description: Optional[str] = None,
tags: Optional[list] = None,
) -> None:
"""Register a workflow with this API channel.
Args:
name: Workflow name
workflow: Workflow instance
description: Optional description
tags: Optional tags
"""
self.workflow_server.register_workflow(
name=name, workflow=workflow, description=description or "", tags=tags or []
)
logger.info(f"Registered workflow '{name}' with API channel {self.name}")
def proxy_workflow(
self,
name: str,
proxy_url: str,
health_check: Optional[str] = None,
description: Optional[str] = None,
tags: Optional[list] = None,
*,
allowed_paths: Optional[list] = None,
allowed_methods: Optional[list] = None,
auth_dependency: Optional[Callable[..., Any]] = None,
forward_credentials: bool = False,
blocked_networks: Optional[Sequence[Any]] = None,
allow_metadata_destination: bool = False,
require_public_destination: bool = False,
max_response_bytes: Optional[int] = None,
) -> None:
"""Register a proxied workflow with this API channel.
Delegates to :meth:`kailash.servers.WorkflowServer.proxy_workflow`,
which is fail-closed since issue #2025: it raises unless an
authentication control and an explicit ``allowed_paths`` allowlist are
supplied.
Every security-relevant argument of the underlying call is forwarded
here rather than defaulted locally (``security.md`` § Multi-Site Kwarg
Plumbing). Without this plumbing the gate would be unconfigurable
through the channel, which makes it a gate that gets worked around by
whoever needs to configure it.
Args:
name: Workflow name
proxy_url: URL to proxy requests to
health_check: Optional health check endpoint
description: Optional description
tags: Optional tags
allowed_paths: **Required** by the underlying server. Paths that
may be forwarded; ``["*"]`` for every path, written down
explicitly.
allowed_methods: HTTP methods to forward. Defaults to ``["GET"]``.
auth_dependency: FastAPI dependency protecting the route. When
omitted, the underlying server's ``auth_manager`` supplies one.
forward_credentials: Forward the caller's credential headers to the
backend. Defaults to False (stripped).
blocked_networks: Extra CIDR blocks the destination may not
resolve into (issue #2091).
allow_metadata_destination: Permit a cloud-metadata / link-local
destination. Defaults to False; logs a WARNING when set.
require_public_destination: Also refuse RFC1918 and loopback
destinations. Defaults to False.
max_response_bytes: Largest backend response body this route will
buffer (issue #2085). Defaults to 64 MiB; larger responses are
refused with 502 rather than truncated.
Raises:
ProxyAuthNotConfiguredError: No authentication control configured.
BlockedDestinationError: ``proxy_url`` resolves into the blocked
destination set (issue #2091).
ValueError: ``allowed_paths`` missing or invalid.
"""
self.workflow_server.proxy_workflow(
name=name,
proxy_url=proxy_url,
health_check=health_check or "/health",
description=description or "",
tags=tags or [],
allowed_paths=allowed_paths,
allowed_methods=allowed_methods,
auth_dependency=auth_dependency,
forward_credentials=forward_credentials,
blocked_networks=blocked_networks,
allow_metadata_destination=allow_metadata_destination,
require_public_destination=require_public_destination,
max_response_bytes=max_response_bytes,
)
logger.info(
f"Registered proxied workflow '{name}' with API channel {self.name}"
)
async def health_check(self) -> Dict[str, Any]:
"""Perform comprehensive health check."""
base_health = await super().health_check()
# Add API-specific health checks
api_checks = {
"server_running": self._server is not None
and not (self._server_task and self._server_task.done()),
"workflows_registered": len(self.workflow_server.workflows) > 0,
"enterprise_features": {
"durability": self.workflow_server.enable_durability,
"resource_management": self.workflow_server.enable_resource_management,
"async_execution": self.workflow_server.enable_async_execution,
"health_checks": self.workflow_server.enable_health_checks,
},
}
all_healthy = base_health["healthy"] and all(api_checks.values())
return {
**base_health,
"healthy": all_healthy,
"checks": {**base_health["checks"], **api_checks},
"workflows": list(self.workflow_server.workflows.keys()),
"enterprise_info": api_checks["enterprise_features"],
}

Xet Storage Details

Size:
27.6 kB
·
Xet hash:
33e85b9c77be2152d1a794d22b366a07b50521ec064b8bffdcc475575d412d9d

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.