#![warn(rust_2018_idioms, missing_docs)]
#![warn(clippy::dbg_macro, clippy::print_stdout)]
#![doc = include_str!("../README.md")]
pub mod errors;
pub mod meta;
pub use crate::errors::{ClientError, ClientResult};
use crate::meta::{FileInfo, PromptInfo};
use bytes::Bytes;
use cfg_if::cfg_if;
use errors::{ApiBody, ApiError};
use futures_util::StreamExt;
use meta::{Event, History, Prompt};
use reqwest::{
Body, IntoUrl, Response,
multipart::{self},
};
use serde::Serialize;
use serde_json::{Value, json};
use std::{
collections::HashMap,
ops::{Deref, DerefMut},
};
use tokio::{sync::mpsc, task::JoinHandle};
use tokio_stream::wrappers::ReceiverStream;
use tokio_tungstenite::{
connect_async,
tungstenite::{self, Message},
};
use url::Url;
use uuid::Uuid;
pub struct ClientBuilder {
base_url: Url,
channel_bound: usize,
}
impl ClientBuilder {
pub fn new(base_url: impl IntoUrl) -> ClientResult<Self> {
Ok(Self {
base_url: base_url.into_url()?,
channel_bound: 100,
})
}
pub async fn build(self) -> ClientResult<(ComfyUIClient, EventStream)> {
let base_url = self.base_url;
let http_client = reqwest::Client::new();
let client_id = Uuid::new_v4().to_string();
let (ev_tx, ev_rx) = mpsc::channel(self.channel_bound);
let ws_url = Self::generate_websocket_url(base_url.clone(), &client_id)?;
let (stream, _) = if ws_url.scheme() == "wss" {
cfg_if! {
if #[cfg(feature = "rustls")] {
let root_store = rustls::RootCertStore {
roots: webpki_roots::TLS_SERVER_ROOTS.into(),
};
let config = rustls::ClientConfig::builder()
.with_root_certificates(root_store)
.with_no_client_auth();
tokio_tungstenite::connect_async_tls_with_config(
ws_url,
None,
false,
Some(tokio_tungstenite::Connector::Rustls(std::sync::Arc::new(config))),
)
.await?
} else {
connect_async(ws_url).await?
}
}
} else {
connect_async(ws_url).await?
};
let stream_handle = tokio::spawn(async move {
let (_, mut read_stream) = stream.split();
while let Some(msg) = read_stream.next().await {
let ev = EventStream::handle_message(msg);
let Some(ev) = ev.transpose() else {
continue;
};
if ev_tx.send(ev).await.is_err() {
break;
}
}
});
let rx_stream = ReceiverStream::new(ev_rx);
let client = ComfyUIClient {
base_url,
http_client,
client_id,
};
let stream = EventStream {
stream_handle,
rx_stream,
};
Ok((client, stream))
}
pub async fn build_only_http(self) -> ClientResult<ComfyUIClient> {
let base_url = self.base_url;
let http_client = reqwest::Client::new();
let client_id = Uuid::new_v4().to_string();
Ok(ComfyUIClient {
base_url,
http_client,
client_id,
})
}
fn generate_websocket_url(base_url: Url, client_id: &str) -> ClientResult<Url> {
let mut ws_url = base_url;
let scheme = if ws_url.scheme() == "https" {
"wss"
} else {
"ws"
};
ws_url
.set_scheme(scheme)
.map_err(|_| ClientError::SetWsScheme)?;
ws_url = ws_url.join("ws")?;
ws_url.query_pairs_mut().append_pair("clientId", client_id);
Ok(ws_url)
}
}
pub struct ComfyUIClient {
client_id: String,
base_url: Url,
http_client: reqwest::Client,
}
impl ComfyUIClient {
pub async fn get_history(&self, prompt_id: &str) -> ClientResult<Option<History>> {
let resp = self
.http_client
.get(self.base_url.join(&format!("history/{prompt_id}"))?)
.send()
.await?;
let resp = Self::error_for_status(resp).await?;
let mut histories = resp.json::<HashMap<String, History>>().await?;
Ok(histories.remove(prompt_id))
}
pub async fn get_prompt(&self) -> ClientResult<PromptInfo> {
let resp = self
.http_client
.get(self.base_url.join("prompt")?)
.send()
.await?;
let resp = Self::error_for_status(resp).await?;
Ok(resp.json().await?)
}
pub async fn get_view(&self, file_info: &FileInfo) -> ClientResult<Bytes> {
let resp = self
.http_client
.get(self.base_url.join("view")?)
.query(file_info)
.send()
.await?;
let resp = Self::error_for_status(resp).await?;
Ok(resp.bytes().await?)
}
pub async fn post_prompt_str(&self, prompt: &str) -> ClientResult<Prompt> {
let prompt = serde_json::from_str::<Value>(prompt)?;
self.post_prompt_value(&prompt).await
}
pub async fn post_prompt<T: Serialize>(&self, prompt: &T) -> ClientResult<Prompt> {
let prompt = serde_json::to_value(prompt)?;
self.post_prompt_value(&prompt).await
}
pub async fn post_prompt_value(&self, prompt: &Value) -> ClientResult<Prompt> {
let data = json!({"client_id": &self.client_id, "prompt": prompt});
let resp = self
.http_client
.post(self.base_url.join("prompt")?)
.json(&data)
.send()
.await?;
let resp = Self::error_for_status(resp).await?;
Ok(resp.json().await?)
}
pub async fn upload_image(
&self, body: impl Into<Body>, info: &FileInfo, overwrite: bool,
) -> ClientResult<FileInfo> {
let part = multipart::Part::stream(body).file_name(info.filename.to_string());
let mut form = multipart::Form::new()
.part("image", part)
.text("overwrite", overwrite.to_string())
.text("type", info.r#type.to_string());
if !info.subfolder.is_empty() {
form = form.text("subfolder", info.subfolder.to_string());
}
let resp = self
.http_client
.post(self.base_url.join("upload/image")?)
.multipart(form)
.send()
.await?;
let resp = Self::error_for_status(resp).await?;
Ok(resp.json().await?)
}
async fn error_for_status(resp: Response) -> ClientResult<Response> {
let status = resp.status();
if status.is_client_error() || status.is_server_error() {
let body = resp.text().await?;
let body = match serde_json::from_str::<Value>(&body) {
Ok(value) => ApiBody::Json(value),
Err(_) => ApiBody::Text(body),
};
Err(ApiError { status, body }.into())
} else {
Ok(resp)
}
}
}
pub struct EventStream {
stream_handle: JoinHandle<()>,
rx_stream: ReceiverStream<ClientResult<Event>>,
}
impl EventStream {
fn handle_message(msg: tungstenite::Result<Message>) -> ClientResult<Option<Event>> {
let msg = msg?;
match msg {
Message::Text(b) => {
let value = serde_json::from_slice::<Value>(b.as_bytes())?;
match serde_json::from_value::<Event>(value.clone()) {
Ok(ev) => Ok(Some(ev)),
Err(_) => Ok(Some(Event::Unknown(value))),
}
}
_ => Ok(None),
}
}
}
impl Drop for EventStream {
fn drop(&mut self) {
self.stream_handle.abort();
}
}
impl Deref for EventStream {
type Target = ReceiverStream<ClientResult<Event>>;
fn deref(&self) -> &Self::Target {
&self.rx_stream
}
}
impl DerefMut for EventStream {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.rx_stream
}
}