vc-runtime 0.1.0

Runtime backend for Visual Compiler
Documentation
//! ComfyUI HTTP client.

use super::error::ComfyApiError;
use anyhow::Result;
use serde::Deserialize;
use std::time::Duration;
use url::Url;
use vc_shared::hashing::Sha256Digest;

#[derive(Debug, Clone)]
pub struct ComfyConfig {
    pub base_url: Url,
    pub timeout: Duration,
    pub poll_timeout: Duration,
    pub poll_interval: Duration,
}

impl ComfyConfig {
    pub fn new(
        base_url: Url,
        timeout_secs: u64,
        poll_timeout_secs: u64,
        poll_interval_ms: u64,
    ) -> Self {
        Self {
            base_url,
            timeout: Duration::from_secs(timeout_secs),
            poll_timeout: Duration::from_secs(poll_timeout_secs),
            poll_interval: Duration::from_millis(poll_interval_ms),
        }
    }
}

#[derive(Debug, Clone)]
pub struct ComfyClient {
    config: ComfyConfig,
    client: reqwest::Client,
}

impl ComfyClient {
    pub fn new(config: ComfyConfig) -> Result<Self> {
        let client = reqwest::Client::builder().timeout(config.timeout).build()?;
        Ok(Self { config, client })
    }

    pub async fn submit_prompt(&self, workflow: &serde_json::Value) -> Result<String> {
        let url = self.config.base_url.join("/prompt")?;
        let response = self.client.post(url).json(workflow).send().await?;
        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await?;
            return Err(ComfyApiError::Api { status, body }.into());
        }
        let json: serde_json::Value = response.json().await?;
        let prompt_id = json["prompt_id"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("Missing prompt_id in response"))?
            .to_string();
        Ok(prompt_id)
    }

    pub async fn wait_for_completion(&self, prompt_id: &str) -> Result<ComfyHistory> {
        let start = std::time::Instant::now();
        let url = self.config.base_url.join("/history")?;
        while start.elapsed() < self.config.poll_timeout {
            let response = self.client.get(url.clone()).send().await?;
            if !response.status().is_success() {
                let status = response.status();
                let body = response.text().await?;
                return Err(ComfyApiError::Api { status, body }.into());
            }
            let history: ComfyHistoryResponse = response.json().await?;
            if let Some(entry) = history.get(prompt_id) {
                if entry.outputs.is_some() {
                    return Ok(entry.clone());
                }
            }
            tokio::time::sleep(self.config.poll_interval).await;
        }
        Err(ComfyApiError::Timeout { duration_secs: self.config.poll_timeout.as_secs() }.into())
    }

    pub async fn download_image(&self, image: &ComfyImage) -> Result<Vec<u8>> {
        let url = self.config.base_url.join(&format!("/view?filename={}", image.filename))?;
        let response = self.client.get(url).send().await?;
        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await?;
            return Err(ComfyApiError::Api { status, body }.into());
        }
        let bytes = response.bytes().await?;
        Ok(bytes.to_vec())
    }
}

// --- Data Types ---

#[derive(Debug, Clone, Deserialize)]
pub struct ComfyHistoryResponse {
    #[serde(flatten)]
    pub entries: std::collections::HashMap<String, ComfyHistory>,
}

impl ComfyHistoryResponse {
    pub fn get(&self, prompt_id: &str) -> Option<&ComfyHistory> {
        self.entries.get(prompt_id)
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct ComfyHistory {
    #[serde(default)]
    pub outputs: Option<std::collections::HashMap<String, ComfyOutputGroup>>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ComfyOutputGroup {
    #[serde(default)]
    pub images: Vec<ComfyImage>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ComfyImage {
    pub filename: String,
    pub subfolder: String,
    #[serde(rename = "type")]
    pub kind: String,
}

// --- Helper: download_and_hash ---

pub async fn download_and_hash(
    client: &ComfyClient,
    image: &ComfyImage,
) -> Result<(Vec<u8>, Sha256Digest)> {
    let bytes = client.download_image(image).await?;
    let hash = vc_shared::hashing::sha256(&bytes);
    Ok((bytes, hash))
}