fix: 修复ComfyUI SDK的cargo check和clippy警告

- 修复ComfyUIError中WebSocket变体过大的问题,使用Box包装
- 添加自定义From实现处理Box包装的WebSocket错误
- 修复所有格式化字符串警告,使用内联格式化
- 移除无用的类型转换(reqwest::Error::from)
- 修复代码质量问题:
  - 简化if语句嵌套
  - 使用?操作符替代显式错误处理
  - 优化map迭代方式
  - 使用is_some_and替代map_or

修复内容:
- 44个clippy警告全部解决
- 所有测试通过
- cargo check --lib 无错误无警告
This commit is contained in:
2025-08-08 16:12:25 +08:00
parent e874d281e0
commit e69ce2b817
9 changed files with 63 additions and 71 deletions

View File

@@ -66,11 +66,11 @@ impl ComfyUIClient {
pub async fn connect(&mut self) -> Result<()> {
// Test HTTP connection first
self.http_client.get_queue().await
.map_err(|e| ComfyUIError::connection(format!("HTTP connection failed: {}", e)))?;
.map_err(|e| ComfyUIError::connection(format!("HTTP connection failed: {e}")))?;
// Connect WebSocket
self.ws_client.connect().await
.map_err(|e| ComfyUIError::connection(format!("WebSocket connection failed: {}", e)))?;
.map_err(|e| ComfyUIError::connection(format!("WebSocket connection failed: {e}")))?;
log::info!("Successfully connected to ComfyUI server");
Ok(())
@@ -107,7 +107,7 @@ impl ComfyUIClient {
let prompt_response = self.http_client.queue_prompt(&prompt_request).await?;
let prompt_id = prompt_response.prompt_id.clone();
log::info!("Submitted prompt with ID: {}", prompt_id);
log::info!("Submitted prompt with ID: {prompt_id}");
// Wait for completion if WebSocket is connected
if self.ws_client.is_connected().await {
@@ -186,8 +186,7 @@ impl ComfyUIClient {
// Check timeout
if start_time.elapsed() > timeout_duration {
return Err(ComfyUIError::timeout(format!(
"Execution timed out after {:?}",
timeout_duration
"Execution timed out after {timeout_duration:?}"
)));
}
@@ -210,7 +209,7 @@ impl ComfyUIClient {
}
}
Err(e) => {
log::warn!("Error checking history: {}", e);
log::warn!("Error checking history: {e}");
}
}

View File

@@ -74,9 +74,9 @@ impl HTTPClient {
let response = request.send().await?;
if !response.status().is_success() {
return Err(ComfyUIError::Http(reqwest::Error::from(
return Err(ComfyUIError::Http(
response.error_for_status().unwrap_err()
)));
));
}
let data: T = response.json().await?;
@@ -115,9 +115,9 @@ impl HTTPClient {
let response = request.send().await?;
if !response.status().is_success() {
return Err(ComfyUIError::Http(reqwest::Error::from(
return Err(ComfyUIError::Http(
response.error_for_status().unwrap_err()
)));
));
}
let data: T = response.json().await?;
@@ -144,7 +144,7 @@ impl HTTPClient {
/// Gets execution history
pub async fn get_history(&self, max_items: Option<u32>) -> Result<HashMap<String, HistoryItem>> {
let endpoint = if let Some(max) = max_items {
format!("/history?max_items={}", max)
format!("/history?max_items={max}")
} else {
"/history".to_string()
};
@@ -154,7 +154,7 @@ impl HTTPClient {
/// Gets history for a specific prompt
pub async fn get_history_by_prompt(&self, prompt_id: &str) -> Result<HashMap<String, HistoryItem>> {
let endpoint = format!("/history/{}", prompt_id);
let endpoint = format!("/history/{prompt_id}");
self.get_with_retry(&endpoint).await
}
@@ -164,9 +164,9 @@ impl HTTPClient {
let response = self.client.delete(url).send().await?;
if !response.status().is_success() {
return Err(ComfyUIError::Http(reqwest::Error::from(
return Err(ComfyUIError::Http(
response.error_for_status().unwrap_err()
)));
));
}
Ok(())
@@ -179,9 +179,9 @@ impl HTTPClient {
let response = self.client.post(url).json(&body).send().await?;
if !response.status().is_success() {
return Err(ComfyUIError::Http(reqwest::Error::from(
return Err(ComfyUIError::Http(
response.error_for_status().unwrap_err()
)));
));
}
Ok(())
@@ -209,7 +209,7 @@ impl HTTPClient {
let part = multipart::Part::bytes(file_bytes)
.file_name(filename.to_string())
.mime_str("image/*")
.map_err(|e| ComfyUIError::new(format!("Invalid MIME type: {}", e)))?;
.map_err(|e| ComfyUIError::new(format!("Invalid MIME type: {e}")))?;
let form = multipart::Form::new()
.part("image", part)
@@ -219,9 +219,7 @@ impl HTTPClient {
let response = self.client.post(url).multipart(form).send().await?;
if !response.status().is_success() {
return Err(ComfyUIError::Http(reqwest::Error::from(
response.error_for_status().unwrap_err()
)));
return Err(ComfyUIError::Http(response.error_for_status().unwrap_err()));
}
let upload_response: UploadImageResponse = response.json().await?;
@@ -230,23 +228,21 @@ impl HTTPClient {
/// Gets an image by filename
pub async fn get_image(&self, filename: &str, subfolder: Option<&str>, image_type: Option<&str>) -> Result<bytes::Bytes> {
let mut endpoint = format!("/view?filename={}", filename);
let mut endpoint = format!("/view?filename={filename}");
if let Some(subfolder) = subfolder {
endpoint.push_str(&format!("&subfolder={}", subfolder));
endpoint.push_str(&format!("&subfolder={subfolder}"));
}
if let Some(image_type) = image_type {
endpoint.push_str(&format!("&type={}", image_type));
endpoint.push_str(&format!("&type={image_type}"));
}
let url = self.build_url(&endpoint)?;
let response = self.client.get(url).send().await?;
if !response.status().is_success() {
return Err(ComfyUIError::Http(reqwest::Error::from(
response.error_for_status().unwrap_err()
)));
return Err(ComfyUIError::Http(response.error_for_status().unwrap_err()));
}
let bytes = response.bytes().await?;
@@ -255,10 +251,10 @@ impl HTTPClient {
/// Gets image metadata
pub async fn get_view_metadata(&self, filename: &str, subfolder: Option<&str>) -> Result<ViewMetadata> {
let mut endpoint = format!("/view_metadata/{}", filename);
let mut endpoint = format!("/view_metadata/{filename}");
if let Some(subfolder) = subfolder {
endpoint.push_str(&format!("?subfolder={}", subfolder));
endpoint.push_str(&format!("?subfolder={subfolder}"));
}
self.get_with_retry(&endpoint).await
@@ -268,7 +264,7 @@ impl HTTPClient {
pub fn outputs_to_urls(&self, outputs: &HashMap<String, serde_json::Value>) -> Vec<String> {
let mut urls = Vec::new();
for (_node_id, output) in outputs {
for output in outputs.values() {
if let Some(output_obj) = output.as_object() {
if let Some(images) = output_obj.get("images").and_then(|v| v.as_array()) {
for image in images {
@@ -280,8 +276,7 @@ impl HTTPClient {
) {
let base_url_str = self.base_url.as_str().trim_end_matches('/');
let url = format!(
"{}/view?filename={}&subfolder={}&type={}",
base_url_str, filename, subfolder, image_type
"{base_url_str}/view?filename={filename}&subfolder={subfolder}&type={image_type}"
);
urls.push(url);
}
@@ -300,9 +295,7 @@ impl HTTPClient {
let response = self.client.post(url).send().await?;
if !response.status().is_success() {
return Err(ComfyUIError::Http(reqwest::Error::from(
response.error_for_status().unwrap_err()
)));
return Err(ComfyUIError::Http(response.error_for_status().unwrap_err()));
}
Ok(())
@@ -314,9 +307,7 @@ impl HTTPClient {
let response = self.client.post(url).send().await?;
if !response.status().is_success() {
return Err(ComfyUIError::Http(reqwest::Error::from(
response.error_for_status().unwrap_err()
)));
return Err(ComfyUIError::Http(response.error_for_status().unwrap_err()));
}
Ok(())

View File

@@ -53,7 +53,7 @@ impl WebSocketClient {
}
let ws_url = self.build_websocket_url()?;
log::info!("Connecting to WebSocket: {}", ws_url);
log::info!("Connecting to WebSocket: {ws_url}");
let (ws_stream, _) = connect_async(&ws_url).await?;
let (_ws_sender, mut ws_receiver) = ws_stream.split();
@@ -78,7 +78,7 @@ impl WebSocketClient {
match message {
Some(Ok(Message::Text(text))) => {
if let Err(e) = Self::handle_message(&text, &event_emitter).await {
log::error!("Error handling WebSocket message: {}", e);
log::error!("Error handling WebSocket message: {e}");
}
}
Some(Ok(Message::Close(_))) => {
@@ -86,7 +86,7 @@ impl WebSocketClient {
break;
}
Some(Err(e)) => {
log::error!("WebSocket error: {}", e);
log::error!("WebSocket error: {e}");
break;
}
None => {
@@ -168,7 +168,7 @@ impl WebSocketClient {
/// Handles incoming WebSocket messages
async fn handle_message(text: &str, event_emitter: &EventEmitter) -> Result<()> {
let message: WSMessage = serde_json::from_str(text)
.map_err(|e| ComfyUIError::new(format!("Failed to parse WebSocket message: {}", e)))?;
.map_err(|e| ComfyUIError::new(format!("Failed to parse WebSocket message: {e}")))?;
match message {
WSMessage::Progress { data } => {
@@ -204,7 +204,7 @@ impl WebSocketClient {
event_emitter.emit_error(error).await;
}
WSMessage::Unknown => {
log::debug!("Received unknown WebSocket message: {}", text);
log::debug!("Received unknown WebSocket message: {text}");
}
}