Files
aigc-home/calliope-backend/src/calliope/comfyui/endpoints.py
T

68 lines
2.4 KiB
Python

"""Shared helpers for ComfyUI multi-connection endpoints (HEL-611).
Every generation path (flow-internal video/asset jobs, playground, agent
tool calls) funnels through ``queue_manager.enqueue``, which stamps an
endpoint SNAPSHOT ``{id, name, base_url}`` into the job payload. The
worker resolves that snapshot at run time: a still-configured endpoint id
wins (fresh URL + token), a dangling id falls back to the snapshot URL,
and no snapshot at all falls back to the active endpoint.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from calliope.config import settings
if TYPE_CHECKING:
from calliope.comfyui.client import ComfyUIClient
def endpoint_snapshot(endpoint_id: str | None) -> dict[str, Any] | None:
"""Connection snapshot for the job payload — never includes the token.
Dangling ids fall back to the active endpoint (mirrors
``resolve_comfyui_endpoint``'s leniency) so an enqueue never hard-fails
because a connection was deleted between submit and stamp.
"""
endpoint = settings.resolve_comfyui_endpoint(endpoint_id)
if not endpoint:
return None
return {
"id": endpoint.get("id"),
"name": endpoint.get("name"),
"base_url": endpoint.get("base_url"),
}
def build_auth_headers(endpoint: dict[str, Any]) -> dict[str, str]:
"""Authorization headers for a stored endpoint (server-side only)."""
auth_type = endpoint.get("auth_type") or "none"
token = endpoint.get("auth_token") if isinstance(endpoint.get("auth_token"), str) else None
token = (token or "").strip()
if not token:
return {}
if auth_type == "bearer":
return {"Authorization": f"Bearer {token}"}
if auth_type == "header":
header = (endpoint.get("header_name") or "X-Api-Key").strip() or "X-Api-Key"
return {header: token}
return {}
def client_for(endpoint: dict[str, Any] | None) -> ComfyUIClient:
"""Build a ComfyUIClient for a stored endpoint (auth headers included).
``None`` falls back to the active endpoint, so legacy call sites keep
their behaviour but gain auth support.
"""
from calliope.comfyui.client import ComfyUIClient
if endpoint is None:
endpoint = settings.resolve_comfyui_endpoint(None)
if endpoint is None:
return ComfyUIClient()
return ComfyUIClient(
str(endpoint.get("base_url") or ""),
headers=build_auth_headers(endpoint),
)