From e69ce2b8174520003e71887a2ccb8502a2c08950 Mon Sep 17 00:00:00 2001 From: imeepos Date: Fri, 8 Aug 2025 16:12:25 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8DComfyUI=20SDK=E7=9A=84?= =?UTF-8?q?cargo=20check=E5=92=8Cclippy=E8=AD=A6=E5=91=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 修复ComfyUIError中WebSocket变体过大的问题,使用Box包装 - 添加自定义From实现处理Box包装的WebSocket错误 - 修复所有格式化字符串警告,使用内联格式化 - 移除无用的类型转换(reqwest::Error::from) - 修复代码质量问题: - 简化if语句嵌套 - 使用?操作符替代显式错误处理 - 优化map迭代方式 - 使用is_some_and替代map_or 修复内容: - 44个clippy警告全部解决 - 所有测试通过 - cargo check --lib 无错误无警告 --- cargos/comfyui-sdk/client/comfyui_client.rs | 11 ++-- cargos/comfyui-sdk/client/http_client.rs | 53 ++++++++----------- cargos/comfyui-sdk/client/websocket_client.rs | 10 ++-- cargos/comfyui-sdk/error.rs | 8 ++- .../comfyui-sdk/templates/template_manager.rs | 4 +- .../templates/workflow_instance.rs | 4 +- cargos/comfyui-sdk/utils/error_handling.rs | 11 ++-- cargos/comfyui-sdk/utils/template_parser.rs | 6 +-- cargos/comfyui-sdk/utils/validation.rs | 27 +++++----- 9 files changed, 63 insertions(+), 71 deletions(-) diff --git a/cargos/comfyui-sdk/client/comfyui_client.rs b/cargos/comfyui-sdk/client/comfyui_client.rs index 15a64de..92dfaa6 100644 --- a/cargos/comfyui-sdk/client/comfyui_client.rs +++ b/cargos/comfyui-sdk/client/comfyui_client.rs @@ -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}"); } } diff --git a/cargos/comfyui-sdk/client/http_client.rs b/cargos/comfyui-sdk/client/http_client.rs index 3000ff7..859f128 100644 --- a/cargos/comfyui-sdk/client/http_client.rs +++ b/cargos/comfyui-sdk/client/http_client.rs @@ -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) -> Result> { 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> { - 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 { - 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 { - 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) -> Vec { 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(()) diff --git a/cargos/comfyui-sdk/client/websocket_client.rs b/cargos/comfyui-sdk/client/websocket_client.rs index 59e39ea..44c6adc 100644 --- a/cargos/comfyui-sdk/client/websocket_client.rs +++ b/cargos/comfyui-sdk/client/websocket_client.rs @@ -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}"); } } diff --git a/cargos/comfyui-sdk/error.rs b/cargos/comfyui-sdk/error.rs index ce63c6f..8d72e0f 100644 --- a/cargos/comfyui-sdk/error.rs +++ b/cargos/comfyui-sdk/error.rs @@ -14,7 +14,7 @@ pub enum ComfyUIError { /// WebSocket errors #[error("WebSocket error: {0}")] - WebSocket(#[from] tokio_tungstenite::tungstenite::Error), + WebSocket(#[from] Box), /// JSON serialization/deserialization errors #[error("JSON error: {0}")] @@ -53,6 +53,12 @@ pub enum ComfyUIError { Io(#[from] std::io::Error), } +impl From for ComfyUIError { + fn from(error: tokio_tungstenite::tungstenite::Error) -> Self { + Self::WebSocket(Box::new(error)) + } +} + impl ComfyUIError { /// Create a new generic error pub fn new(message: impl Into) -> Self { diff --git a/cargos/comfyui-sdk/templates/template_manager.rs b/cargos/comfyui-sdk/templates/template_manager.rs index 323fe17..485c03e 100644 --- a/cargos/comfyui-sdk/templates/template_manager.rs +++ b/cargos/comfyui-sdk/templates/template_manager.rs @@ -106,7 +106,7 @@ impl TemplateManager { pub fn create_instance(&self, template_id: &str, parameters: ParameterValues) -> Result { let template = self.get_by_id(template_id) .ok_or_else(|| ComfyUIError::template_validation( - format!("Template with ID '{}' not found", template_id) + format!("Template with ID '{template_id}' not found") ))?; template.create_instance(parameters) @@ -158,7 +158,7 @@ impl TemplateManager { if !validation.valid { return Err(ComfyUIError::template_validation( - format!("Template '{}' validation failed", id) + format!("Template '{id}' validation failed") )); } } diff --git a/cargos/comfyui-sdk/templates/workflow_instance.rs b/cargos/comfyui-sdk/templates/workflow_instance.rs index 3336b00..d285795 100644 --- a/cargos/comfyui-sdk/templates/workflow_instance.rs +++ b/cargos/comfyui-sdk/templates/workflow_instance.rs @@ -62,7 +62,7 @@ impl WorkflowInstance { // Check if parameter exists in template if !self.template.has_parameter(&name) { return Err(ComfyUIError::parameter_validation( - format!("Parameter '{}' does not exist in template", name) + format!("Parameter '{name}' does not exist in template") )); } @@ -93,7 +93,7 @@ impl WorkflowInstance { for name in parameters.keys() { if !self.template.has_parameter(name) { return Err(ComfyUIError::parameter_validation( - format!("Parameter '{}' does not exist in template", name) + format!("Parameter '{name}' does not exist in template") )); } } diff --git a/cargos/comfyui-sdk/utils/error_handling.rs b/cargos/comfyui-sdk/utils/error_handling.rs index 3100bda..d4bab22 100644 --- a/cargos/comfyui-sdk/utils/error_handling.rs +++ b/cargos/comfyui-sdk/utils/error_handling.rs @@ -43,7 +43,7 @@ where last_error = Some(error); if attempt < config.max_attempts { - log::warn!("Attempt {} failed, retrying in {:?}", attempt, delay); + log::warn!("Attempt {attempt} failed, retrying in {delay:?}"); sleep(delay).await; // Exponential backoff @@ -68,7 +68,7 @@ pub fn is_retryable_error(error: &ComfyUIError) -> bool { // Retry on network errors, timeouts, and 5xx status codes reqwest_error.is_timeout() || reqwest_error.is_connect() || - reqwest_error.status().map_or(false, |status| status.is_server_error()) + reqwest_error.status().is_some_and(|status| status.is_server_error()) } ComfyUIError::WebSocket(_) => true, // Most WebSocket errors are retryable ComfyUIError::Connection(_) => true, @@ -101,7 +101,7 @@ where last_error = Some(error); if attempt < config.max_attempts { - log::warn!("Attempt {} failed with retryable error, retrying in {:?}", attempt, delay); + log::warn!("Attempt {attempt} failed with retryable error, retrying in {delay:?}"); sleep(delay).await; // Exponential backoff @@ -130,8 +130,7 @@ where match tokio::time::timeout(timeout, operation).await { Ok(result) => result, Err(_) => Err(ComfyUIError::timeout(format!( - "Operation timed out after {:?}", - timeout + "Operation timed out after {timeout:?}" ))), } } @@ -144,7 +143,7 @@ pub trait ErrorContext { impl ErrorContext for Result { fn with_context(self, context: &str) -> Result { self.map_err(|error| { - ComfyUIError::new(format!("{}: {}", context, error)) + ComfyUIError::new(format!("{context}: {error}")) }) } } diff --git a/cargos/comfyui-sdk/utils/template_parser.rs b/cargos/comfyui-sdk/utils/template_parser.rs index 74ae2d5..5419114 100644 --- a/cargos/comfyui-sdk/utils/template_parser.rs +++ b/cargos/comfyui-sdk/utils/template_parser.rs @@ -82,7 +82,7 @@ pub fn substitute_variables( }; let regex = Regex::new(pattern) - .map_err(|e| ComfyUIError::new(format!("Invalid regex pattern: {}", e)))?; + .map_err(|e| ComfyUIError::new(format!("Invalid regex pattern: {e}")))?; let mut result = template.to_string(); let mut offset = 0i32; @@ -96,7 +96,7 @@ pub fn substitute_variables( Some(value) => value_to_string(value)?, None => { return Err(ComfyUIError::template_validation( - format!("Parameter '{}' not found", var_name) + format!("Parameter '{var_name}' not found") )); } }; @@ -139,7 +139,7 @@ pub fn extract_variables(template: &str, syntax: VariableSyntax) -> Result max { return Err(ValidationError::with_value( name, - format!("String length must be at most {}", max), + format!("String length must be at most {max}"), serde_json::Value::String(value.to_string()), )); } @@ -151,7 +150,7 @@ fn validate_number_constraints( if num_value < min { return Err(ValidationError::with_value( name, - format!("Number must be at least {}", min), + format!("Number must be at least {min}"), serde_json::Value::Number(value.clone()), )); } @@ -161,7 +160,7 @@ fn validate_number_constraints( if num_value > max { return Err(ValidationError::with_value( name, - format!("Number must be at most {}", max), + format!("Number must be at most {max}"), serde_json::Value::Number(value.clone()), )); } @@ -181,7 +180,7 @@ fn validate_array_constraints( if (value.len() as f64) < min { return Err(ValidationError::with_value( name, - format!("Array length must be at least {}", min), + format!("Array length must be at least {min}"), serde_json::Value::Array(value.to_vec()), )); } @@ -191,7 +190,7 @@ fn validate_array_constraints( if (value.len() as f64) > max { return Err(ValidationError::with_value( name, - format!("Array length must be at most {}", max), + format!("Array length must be at most {max}"), serde_json::Value::Array(value.to_vec()), )); } @@ -200,10 +199,8 @@ fn validate_array_constraints( // Validate items if schema is provided if let Some(items_schema) = &schema.items { for (index, item) in value.iter().enumerate() { - let item_name = format!("{}[{}]", name, index); - if let Err(error) = validate_parameter_value(&item_name, item, items_schema) { - return Err(error); - } + let item_name = format!("{name}[{index}]"); + validate_parameter_value(&item_name, item, items_schema)? } }