use anyhow::{anyhow, Result};
use bytes::Bytes;
use reqwest::{Client, StatusCode};
use std::time::Duration;
use url::Url;
use super::types::{HistoryEntry, HistoryResponse, PromptResponse};
use crate::services::comfy::types::ImageOutput;
#[derive(Debug, Clone)]
pub struct ComfyConfig {
pub base_url: Url,
pub http_timeout: Duration,
pub poll_timeout: Duration,
pub poll_interval: Duration,
}
impl ComfyConfig {
pub fn new(base_url: Url) -> Self {
Self {
base_url,
http_timeout: Duration::from_secs(30),
poll_timeout: Duration::from_secs(300),
poll_interval: Duration::from_millis(500),
}
}
}
pub struct ComfyClient {
config: ComfyConfig,
client: Client,
}
impl ComfyClient {
pub fn new(config: ComfyConfig) -> Result<Self> {
let client = Client::builder().timeout(config.http_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 payload = serde_json::json!({ "prompt": workflow });
let response = self.client.post(url).json(&payload).send().await?;
if !response.status().is_success() {
let status = response.status();
let text = response.text().await.unwrap_or_default();
return Err(anyhow!("ComfyUI submit failed ({}): {}", status, text));
}
let prompt_res: PromptResponse = response.json().await?;
Ok(prompt_res.prompt_id)
}
pub async fn get_history(&self, prompt_id: &str) -> Result<Option<HistoryEntry>> {
let url = self.config.base_url.join(&format!("/history/{}", prompt_id))?;
let response = self.client.get(url).send().await?;
if response.status() == StatusCode::NOT_FOUND {
return Ok(None);
}
if !response.status().is_success() {
let status = response.status();
let text = response.text().await.unwrap_or_default();
return Err(anyhow!("ComfyUI history failed ({}): {}", status, text));
}
let history: HistoryResponse = response.json().await?;
Ok(history.get(prompt_id).cloned())
}
pub async fn download_image(&self, image: &ImageOutput) -> Result<Bytes> {
let mut url = self.config.base_url.join("/view")?;
url.query_pairs_mut()
.append_pair("filename", &image.filename)
.append_pair("subfolder", &image.subfolder)
.append_pair("type", &image.image_type);
let response = self.client.get(url).send().await?;
if !response.status().is_success() {
let status = response.status();
let text = response.text().await.unwrap_or_default();
return Err(anyhow!("ComfyUI download failed ({}): {}", status, text));
}
Ok(response.bytes().await?)
}
pub async fn wait_for_completion(&self, prompt_id: &str) -> Result<HistoryEntry> {
let start = std::time::Instant::now();
while start.elapsed() < self.config.poll_timeout {
if let Some(history) = self.get_history(prompt_id).await? {
if let Some(error) = history.error {
return Err(anyhow!("ComfyUI execution failed: {}", error.message));
}
if history.is_complete() {
return Ok(history);
}
}
tokio::time::sleep(self.config.poll_interval).await;
}
Err(anyhow!("ComfyUI job timed out after {} seconds", self.config.poll_timeout.as_secs()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::services::comfy::types::ImageOutput;
use wiremock::matchers::{body_json, method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};
#[tokio::test]
async fn test_submit_prompt() {
let mock_server = MockServer::start().await;
let expected_prompt_id = "test_prompt_123";
Mock::given(method("POST"))
.and(path("/prompt"))
.and(body_json(serde_json::json!({ "prompt": { "test": true } })))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(serde_json::json!({ "prompt_id": expected_prompt_id })),
)
.mount(&mock_server)
.await;
let base_url = Url::parse(&mock_server.uri()).unwrap();
let config = ComfyConfig::new(base_url);
let client = ComfyClient::new(config).unwrap();
let workflow = serde_json::json!({ "test": true });
let prompt_id = client.submit_prompt(&workflow).await.unwrap();
assert_eq!(prompt_id, expected_prompt_id);
}
#[tokio::test]
async fn test_get_history_not_found() {
let mock_server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/history/unknown"))
.respond_with(ResponseTemplate::new(404))
.mount(&mock_server)
.await;
let base_url = Url::parse(&mock_server.uri()).unwrap();
let config = ComfyConfig::new(base_url);
let client = ComfyClient::new(config).unwrap();
let history = client.get_history("unknown").await.unwrap();
assert!(history.is_none());
}
#[tokio::test]
async fn test_download_image() {
let mock_server = MockServer::start().await;
let image_bytes = vec![1, 2, 3, 4];
Mock::given(method("GET"))
.and(path("/view"))
.and(query_param("filename", "test.png"))
.and(query_param("subfolder", ""))
.and(query_param("type", "output"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(image_bytes.clone()))
.mount(&mock_server)
.await;
let base_url = Url::parse(&mock_server.uri()).unwrap();
let config = ComfyConfig::new(base_url);
let client = ComfyClient::new(config).unwrap();
let image = ImageOutput {
filename: "test.png".to_string(),
subfolder: "".to_string(),
image_type: "output".to_string(),
};
let bytes = client.download_image(&image).await.unwrap();
assert_eq!(bytes.to_vec(), image_bytes);
}
#[tokio::test]
async fn test_wait_for_completion() {
let mock_server = MockServer::start().await;
let prompt_id = "test_prompt";
Mock::given(method("GET"))
.and(path(&format!("/history/{}", prompt_id)))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
prompt_id: {
"outputs": {
"9": {
"images": [
{
"filename": "image.png",
"subfolder": "",
"type": "output"
}
]
}
}
}
})))
.mount(&mock_server)
.await;
let base_url = Url::parse(&mock_server.uri()).unwrap();
let config = ComfyConfig {
base_url,
http_timeout: Duration::from_secs(10),
poll_timeout: Duration::from_secs(10),
poll_interval: Duration::from_millis(10),
};
let client = ComfyClient::new(config).unwrap();
let history = client.wait_for_completion(prompt_id).await.unwrap();
assert!(history.is_complete());
assert!(history.outputs.contains_key("9"));
let images = history.outputs.get("9").unwrap();
assert!(!images.images.is_empty());
}
}