fix:Apply suggestions from clippy 1.88

This commit is contained in:
houseme
2025-06-27 18:16:29 +08:00
parent 35489ea352
commit 749537664f
108 changed files with 642 additions and 682 deletions
+10 -10
View File
@@ -231,10 +231,10 @@ mod tests {
#[test]
fn test_const_str_concat_functionality() {
// Test const_str::concat macro functionality
let expected_address = format!(":{}", DEFAULT_PORT);
let expected_address = format!(":{DEFAULT_PORT}");
assert_eq!(DEFAULT_ADDRESS, expected_address);
let expected_console_address = format!(":{}", DEFAULT_CONSOLE_PORT);
let expected_console_address = format!(":{DEFAULT_CONSOLE_PORT}");
assert_eq!(DEFAULT_CONSOLE_ADDRESS, expected_console_address);
}
@@ -256,9 +256,9 @@ mod tests {
];
for constant in &string_constants {
assert!(!constant.is_empty(), "String constant should not be empty: {}", constant);
assert!(!constant.starts_with(' '), "String constant should not start with space: {}", constant);
assert!(!constant.ends_with(' '), "String constant should not end with space: {}", constant);
assert!(!constant.is_empty(), "String constant should not be empty: {constant}");
assert!(!constant.starts_with(' '), "String constant should not start with space: {constant}");
assert!(!constant.ends_with(' '), "String constant should not end with space: {constant}");
}
}
@@ -284,8 +284,8 @@ mod tests {
// These are default values, should be changed in production environments
println!("Security Warning: Default credentials detected!");
println!("Access Key: {}", DEFAULT_ACCESS_KEY);
println!("Secret Key: {}", DEFAULT_SECRET_KEY);
println!("Access Key: {DEFAULT_ACCESS_KEY}");
println!("Secret Key: {DEFAULT_SECRET_KEY}");
println!("These should be changed in production environments!");
// Verify that key lengths meet minimum security requirements
@@ -312,11 +312,11 @@ mod tests {
let ports = [DEFAULT_PORT, DEFAULT_CONSOLE_PORT];
let mut unique_ports = std::collections::HashSet::new();
for port in &ports {
assert!(unique_ports.insert(port), "Port {} is duplicated", port);
assert!(unique_ports.insert(port), "Port {port} is duplicated");
}
// Address format consistency
assert_eq!(DEFAULT_ADDRESS, format!(":{}", DEFAULT_PORT));
assert_eq!(DEFAULT_CONSOLE_ADDRESS, format!(":{}", DEFAULT_CONSOLE_PORT));
assert_eq!(DEFAULT_ADDRESS, format!(":{DEFAULT_PORT}"));
assert_eq!(DEFAULT_CONSOLE_ADDRESS, format!(":{DEFAULT_CONSOLE_PORT}"));
}
}
+3 -3
View File
@@ -178,7 +178,7 @@ impl From<uuid::Error> for Error {
impl From<rmp::decode::MarkerReadError> for Error {
fn from(e: rmp::decode::MarkerReadError) -> Self {
let serr = format!("{:?}", e);
let serr = format!("{e:?}");
Error::RmpDecodeMarkerRead(serr)
}
}
@@ -423,7 +423,7 @@ mod tests {
];
for kind in io_error_kinds {
let io_error = IoError::new(kind, format!("test error for {:?}", kind));
let io_error = IoError::new(kind, format!("test error for {kind:?}"));
let filemeta_error: Error = io_error.into();
match filemeta_error {
@@ -434,7 +434,7 @@ mod tests {
assert_eq!(extracted_io_error.kind(), kind);
assert!(extracted_io_error.to_string().contains("test error"));
}
_ => panic!("Expected Io variant for kind {:?}", kind),
_ => panic!("Expected Io variant for kind {kind:?}"),
}
}
}
+11 -11
View File
@@ -72,7 +72,7 @@ impl std::fmt::Display for ErasureAlgo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ErasureAlgo::Invalid => write!(f, "Invalid"),
ErasureAlgo::ReedSolomon => write!(f, "{}", ERASURE_ALGORITHM),
ErasureAlgo::ReedSolomon => write!(f, "{ERASURE_ALGORITHM}"),
}
}
}
@@ -312,53 +312,53 @@ impl FileInfo {
pub fn set_tier_free_version_id(&mut self, version_id: &str) {
self.metadata
.insert(format!("{}{}", RESERVED_METADATA_PREFIX_LOWER, TIER_FV_ID), version_id.to_string());
.insert(format!("{RESERVED_METADATA_PREFIX_LOWER}{TIER_FV_ID}"), version_id.to_string());
}
pub fn tier_free_version_id(&self) -> String {
self.metadata[&format!("{}{}", RESERVED_METADATA_PREFIX_LOWER, TIER_FV_ID)].clone()
self.metadata[&format!("{RESERVED_METADATA_PREFIX_LOWER}{TIER_FV_ID}")].clone()
}
pub fn set_tier_free_version(&mut self) {
self.metadata
.insert(format!("{}{}", RESERVED_METADATA_PREFIX_LOWER, TIER_FV_MARKER), "".to_string());
.insert(format!("{RESERVED_METADATA_PREFIX_LOWER}{TIER_FV_MARKER}"), "".to_string());
}
pub fn set_skip_tier_free_version(&mut self) {
self.metadata
.insert(format!("{}{}", RESERVED_METADATA_PREFIX_LOWER, TIER_SKIP_FV_ID), "".to_string());
.insert(format!("{RESERVED_METADATA_PREFIX_LOWER}{TIER_SKIP_FV_ID}"), "".to_string());
}
pub fn skip_tier_free_version(&self) -> bool {
self.metadata
.contains_key(&format!("{}{}", RESERVED_METADATA_PREFIX_LOWER, TIER_SKIP_FV_ID))
.contains_key(&format!("{RESERVED_METADATA_PREFIX_LOWER}{TIER_SKIP_FV_ID}"))
}
pub fn tier_free_version(&self) -> bool {
self.metadata
.contains_key(&format!("{}{}", RESERVED_METADATA_PREFIX_LOWER, TIER_FV_MARKER))
.contains_key(&format!("{RESERVED_METADATA_PREFIX_LOWER}{TIER_FV_MARKER}"))
}
pub fn set_inline_data(&mut self) {
self.metadata
.insert(format!("{}inline-data", RESERVED_METADATA_PREFIX_LOWER).to_owned(), "true".to_owned());
.insert(format!("{RESERVED_METADATA_PREFIX_LOWER}inline-data").to_owned(), "true".to_owned());
}
pub fn set_data_moved(&mut self) {
self.metadata
.insert(format!("{}data-moved", RESERVED_METADATA_PREFIX_LOWER).to_owned(), "true".to_owned());
.insert(format!("{RESERVED_METADATA_PREFIX_LOWER}data-moved").to_owned(), "true".to_owned());
}
pub fn inline_data(&self) -> bool {
self.metadata
.contains_key(format!("{}inline-data", RESERVED_METADATA_PREFIX_LOWER).as_str())
.contains_key(format!("{RESERVED_METADATA_PREFIX_LOWER}inline-data").as_str())
&& !self.is_remote()
}
/// Check if the object is compressed
pub fn is_compressed(&self) -> bool {
self.metadata
.contains_key(&format!("{}compression", RESERVED_METADATA_PREFIX_LOWER))
.contains_key(&format!("{RESERVED_METADATA_PREFIX_LOWER}compression"))
}
/// Check if the object is remote (transitioned to another tier)
+29 -31
View File
@@ -929,15 +929,13 @@ impl FileMetaVersion {
}
pub fn get_data_dir(&self) -> Option<Uuid> {
self.valid()
.then(|| {
if self.valid() { {
if self.version_type == VersionType::Object {
self.object.as_ref().map(|v| v.data_dir).unwrap_or_default()
} else {
None
}
})
.unwrap_or_default()
} } else { Default::default() }
}
pub fn get_version_id(&self) -> Option<Uuid> {
@@ -1028,7 +1026,7 @@ impl FileMetaVersion {
"v" => {
self.write_version = rmp::decode::read_int(&mut cur)?;
}
name => return Err(Error::other(format!("not suport field name {}", name))),
name => return Err(Error::other(format!("not suport field name {name}"))),
}
}
@@ -1325,7 +1323,7 @@ impl FileMetaVersionHeader {
let mut cur = Cursor::new(buf);
let alen = rmp::decode::read_array_len(&mut cur)?;
if alen != 7 {
return Err(Error::other(format!("version header array len err need 7 got {}", alen)));
return Err(Error::other(format!("version header array len err need 7 got {alen}")));
}
// version_id
@@ -1709,7 +1707,7 @@ impl MetaObject {
}
}
name => return Err(Error::other(format!("not suport field name {}", name))),
name => return Err(Error::other(format!("not suport field name {name}"))),
}
}
@@ -1938,19 +1936,19 @@ impl MetaObject {
pub fn set_transition(&mut self, fi: &FileInfo) {
self.meta_sys.insert(
format!("{}{}", RESERVED_METADATA_PREFIX_LOWER, TRANSITION_STATUS),
format!("{RESERVED_METADATA_PREFIX_LOWER}{TRANSITION_STATUS}"),
fi.transition_status.as_bytes().to_vec(),
);
self.meta_sys.insert(
format!("{}{}", RESERVED_METADATA_PREFIX_LOWER, TRANSITIONED_OBJECTNAME),
format!("{RESERVED_METADATA_PREFIX_LOWER}{TRANSITIONED_OBJECTNAME}"),
fi.transitioned_objname.as_bytes().to_vec(),
);
self.meta_sys.insert(
format!("{}{}", RESERVED_METADATA_PREFIX_LOWER, TRANSITIONED_VERSION_ID),
format!("{RESERVED_METADATA_PREFIX_LOWER}{TRANSITIONED_VERSION_ID}"),
fi.transition_version_id.unwrap().as_bytes().to_vec(),
);
self.meta_sys.insert(
format!("{}{}", RESERVED_METADATA_PREFIX_LOWER, TRANSITION_TIER),
format!("{RESERVED_METADATA_PREFIX_LOWER}{TRANSITION_TIER}"),
fi.transition_tier.as_bytes().to_vec(),
);
}
@@ -1968,12 +1966,12 @@ impl MetaObject {
pub fn inlinedata(&self) -> bool {
self.meta_sys
.contains_key(format!("{}inline-data", RESERVED_METADATA_PREFIX_LOWER).as_str())
.contains_key(format!("{RESERVED_METADATA_PREFIX_LOWER}inline-data").as_str())
}
pub fn reset_inline_data(&mut self) {
self.meta_sys
.remove(format!("{}inline-data", RESERVED_METADATA_PREFIX_LOWER).as_str());
.remove(format!("{RESERVED_METADATA_PREFIX_LOWER}inline-data").as_str());
}
/// Remove restore headers
@@ -2001,7 +1999,7 @@ impl MetaObject {
}
if let Some(status) = self
.meta_sys
.get(&format!("{}{}", RESERVED_METADATA_PREFIX_LOWER, TRANSITION_STATUS))
.get(&format!("{RESERVED_METADATA_PREFIX_LOWER}{TRANSITION_STATUS}"))
{
if *status == TRANSITION_COMPLETE.as_bytes().to_vec() {
let vid = Uuid::parse_str(&fi.tier_free_version_id());
@@ -2027,10 +2025,10 @@ impl MetaObject {
.meta_sys
.as_mut()
.unwrap()
.insert(format!("{}{}", RESERVED_METADATA_PREFIX_LOWER, FREE_VERSION), vec![]);
let tier_key = format!("{}{}", RESERVED_METADATA_PREFIX_LOWER, TRANSITION_TIER);
let tier_obj_key = format!("{}{}", RESERVED_METADATA_PREFIX_LOWER, TRANSITIONED_OBJECTNAME);
let tier_obj_vid_key = format!("{}{}", RESERVED_METADATA_PREFIX_LOWER, TRANSITIONED_VERSION_ID);
.insert(format!("{RESERVED_METADATA_PREFIX_LOWER}{FREE_VERSION}"), vec![]);
let tier_key = format!("{RESERVED_METADATA_PREFIX_LOWER}{TRANSITION_TIER}");
let tier_obj_key = format!("{RESERVED_METADATA_PREFIX_LOWER}{TRANSITIONED_OBJECTNAME}");
let tier_obj_vid_key = format!("{RESERVED_METADATA_PREFIX_LOWER}{TRANSITIONED_VERSION_ID}");
let aa = [tier_key, tier_obj_key, tier_obj_vid_key];
for (k, v) in &self.meta_sys {
@@ -2192,7 +2190,7 @@ impl MetaDeleteMarker {
self.meta_sys = Some(map);
}
name => return Err(Error::other(format!("not suport field name {}", name))),
name => return Err(Error::other(format!("not suport field name {name}"))),
}
}
@@ -2913,9 +2911,9 @@ mod test {
let serialization_time = start.elapsed();
println!("性能测试结果:");
println!(" 创建时间:{:?}", creation_time);
println!(" 解析时间:{:?}", parsing_time);
println!(" 序列化时间:{:?}", serialization_time);
println!(" 创建时间:{creation_time:?}");
println!(" 解析时间:{parsing_time:?}");
println!(" 序列化时间:{serialization_time:?}");
// 基本性能断言(这些值可能需要根据实际性能调整)
assert!(parsing_time.as_millis() < 100, "解析时间应该小于 100ms");
@@ -2986,7 +2984,7 @@ mod test {
for i in 0..10 {
let fm_clone: Arc<Mutex<FileMeta>> = Arc::clone(&fm);
let handle = tokio::spawn(async move {
let mut fi = crate::fileinfo::FileInfo::new(&format!("test-{}", i), 2, 1);
let mut fi = crate::fileinfo::FileInfo::new(&format!("test-{i}"), 2, 1);
fi.version_id = Some(Uuid::new_v4());
fi.mod_time = Some(OffsetDateTime::now_utc());
@@ -3013,19 +3011,19 @@ mod test {
// 测试空结构体的内存占用
let empty_fm = FileMeta::new();
let empty_size = mem::size_of_val(&empty_fm);
println!("Empty FileMeta size: {} bytes", empty_size);
println!("Empty FileMeta size: {empty_size} bytes");
// 测试包含大量版本的内存占用
let mut large_fm = FileMeta::new();
for i in 0..100 {
let mut fi = crate::fileinfo::FileInfo::new(&format!("test-{}", i), 2, 1);
let mut fi = crate::fileinfo::FileInfo::new(&format!("test-{i}"), 2, 1);
fi.version_id = Some(Uuid::new_v4());
fi.mod_time = Some(OffsetDateTime::now_utc());
large_fm.add_version(fi).unwrap();
}
let large_size = mem::size_of_val(&large_fm);
println!("Large FileMeta size: {} bytes", large_size);
println!("Large FileMeta size: {large_size} bytes");
// 验证内存使用是合理的(注意:size_of_val 只计算栈上的大小,不包括堆分配)
// 对于包含 Vec 的结构体,size_of_val 可能相同,因为 Vec 的容量在堆上
@@ -3041,7 +3039,7 @@ mod test {
// 添加相同时间戳的版本
let same_time = OffsetDateTime::now_utc();
for i in 0..5 {
let mut fi = crate::fileinfo::FileInfo::new(&format!("test-{}", i), 2, 1);
let mut fi = crate::fileinfo::FileInfo::new(&format!("test-{i}"), 2, 1);
fi.version_id = Some(Uuid::new_v4());
fi.mod_time = Some(same_time);
fm.add_version(fi).unwrap();
@@ -3122,7 +3120,7 @@ mod test {
// 测试适量用户元数据
for i in 0..10 {
obj.meta_user
.insert(format!("key-{:04}", i), format!("value-{:04}-{}", i, "x".repeat(10)));
.insert(format!("key-{i:04}"), format!("value-{:04}-{}", i, "x".repeat(10)));
}
// 验证可以序列化元数据
@@ -3146,7 +3144,7 @@ mod test {
// 添加对象版本
for i in 0..object_count {
let mut fi = crate::fileinfo::FileInfo::new(&format!("obj-{}", i), 2, 1);
let mut fi = crate::fileinfo::FileInfo::new(&format!("obj-{i}"), 2, 1);
fi.version_id = Some(Uuid::new_v4());
fi.mod_time = Some(OffsetDateTime::now_utc());
fm.add_version(fi).unwrap();
@@ -3240,11 +3238,11 @@ mod test {
// 创建两组不同的版本
for i in 0..3 {
let mut fi1 = crate::fileinfo::FileInfo::new(&format!("test1-{}", i), 2, 1);
let mut fi1 = crate::fileinfo::FileInfo::new(&format!("test1-{i}"), 2, 1);
fi1.version_id = Some(Uuid::new_v4());
fi1.mod_time = Some(OffsetDateTime::from_unix_timestamp(1000 + i * 10).unwrap());
let mut fi2 = crate::fileinfo::FileInfo::new(&format!("test2-{}", i), 2, 1);
let mut fi2 = crate::fileinfo::FileInfo::new(&format!("test2-{i}"), 2, 1);
fi2.version_id = Some(Uuid::new_v4());
fi2.mod_time = Some(OffsetDateTime::from_unix_timestamp(1005 + i * 10).unwrap());
+7 -7
View File
@@ -463,7 +463,7 @@ impl<W: AsyncWrite + Unpin> MetacacheWriter<W> {
pub async fn init(&mut self) -> Result<()> {
if !self.created {
rmp::encode::write_u8(&mut self.buf, METACACHE_STREAM_VERSION).map_err(|e| Error::other(format!("{:?}", e)))?;
rmp::encode::write_u8(&mut self.buf, METACACHE_STREAM_VERSION).map_err(|e| Error::other(format!("{e:?}")))?;
self.flush().await?;
self.created = true;
}
@@ -491,16 +491,16 @@ impl<W: AsyncWrite + Unpin> MetacacheWriter<W> {
pub async fn write_obj(&mut self, obj: &MetaCacheEntry) -> Result<()> {
self.init().await?;
rmp::encode::write_bool(&mut self.buf, true).map_err(|e| Error::other(format!("{:?}", e)))?;
rmp::encode::write_str(&mut self.buf, &obj.name).map_err(|e| Error::other(format!("{:?}", e)))?;
rmp::encode::write_bin(&mut self.buf, &obj.metadata).map_err(|e| Error::other(format!("{:?}", e)))?;
rmp::encode::write_bool(&mut self.buf, true).map_err(|e| Error::other(format!("{e:?}")))?;
rmp::encode::write_str(&mut self.buf, &obj.name).map_err(|e| Error::other(format!("{e:?}")))?;
rmp::encode::write_bin(&mut self.buf, &obj.metadata).map_err(|e| Error::other(format!("{e:?}")))?;
self.flush().await?;
Ok(())
}
pub async fn close(&mut self) -> Result<()> {
rmp::encode::write_bool(&mut self.buf, false).map_err(|e| Error::other(format!("{:?}", e)))?;
rmp::encode::write_bool(&mut self.buf, false).map_err(|e| Error::other(format!("{e:?}")))?;
self.flush().await?;
Ok(())
}
@@ -559,7 +559,7 @@ impl<R: AsyncRead + Unpin> MetacacheReader<R> {
let ver = match rmp::decode::read_u8(&mut self.read_more(2).await?) {
Ok(res) => res,
Err(err) => {
self.err = Some(Error::other(format!("{:?}", err)));
self.err = Some(Error::other(format!("{err:?}")));
0
}
};
@@ -852,7 +852,7 @@ mod tests {
let mut objs = Vec::new();
for i in 0..10 {
let info = MetaCacheEntry {
name: format!("item{}", i),
name: format!("item{i}"),
metadata: vec![0u8, 10],
cached: None,
reusable: false,
+1 -1
View File
@@ -98,7 +98,7 @@ pub fn create_complex_xlmeta() -> Result<Vec<u8>> {
let mut metadata = HashMap::new();
metadata.insert("Content-Type".to_string(), "application/octet-stream".to_string());
metadata.insert("X-Amz-Meta-Version".to_string(), i.to_string());
metadata.insert("X-Amz-Meta-Test".to_string(), format!("test-value-{}", i));
metadata.insert("X-Amz-Meta-Test".to_string(), format!("test-value-{i}"));
let object_version = MetaObject {
version_id: Some(version_id),
+15 -16
View File
@@ -37,12 +37,12 @@ async fn main() {
let server_addr = match parse_and_resolve_address(":3020") {
Ok(addr) => addr,
Err(e) => {
eprintln!("Failed to parse address: {}", e);
eprintln!("Failed to parse address: {e}");
return;
}
};
let listener = TcpListener::bind(server_addr).await.unwrap();
println!("Server running on {}", server_addr);
println!("Server running on {server_addr}");
// Self-checking after the service is started
tokio::spawn(async move {
@@ -52,7 +52,7 @@ async fn main() {
match is_service_active(server_addr).await {
Ok(true) => println!("Service health check: Successful - Service is running normally"),
Ok(false) => eprintln!("Service Health Check: Failed - Service Not Responded"),
Err(e) => eprintln!("Service health check errors:{}", e),
Err(e) => eprintln!("Service health check errors:{e}"),
}
});
@@ -60,7 +60,7 @@ async fn main() {
tokio::select! {
result = axum::serve(listener, app) => {
if let Err(e) = result {
eprintln!("Server error: {}", e);
eprintln!("Server error: {e}");
}
}
_ = tokio::signal::ctrl_c() => {
@@ -73,9 +73,9 @@ async fn main() {
async fn reset_webhook_count_with_path(axum::extract::Path(reason): axum::extract::Path<String>) -> Response<String> {
// Output the value of the current counter
let current_count = WEBHOOK_COUNT.load(Ordering::SeqCst);
println!("Current webhook count: {}", current_count);
println!("Current webhook count: {current_count}");
println!("Reset webhook count, reason: {}", reason);
println!("Reset webhook count, reason: {reason}");
// Reset the counter to 0
WEBHOOK_COUNT.store(0, Ordering::SeqCst);
println!("Webhook count has been reset to 0.");
@@ -84,8 +84,7 @@ async fn reset_webhook_count_with_path(axum::extract::Path(reason): axum::extrac
.header("Foo", "Bar")
.status(StatusCode::OK)
.body(format!(
"Webhook count reset successfully. Previous count: {}. Reason: {}",
current_count, reason
"Webhook count reset successfully. Previous count: {current_count}. Reason: {reason}"
))
.unwrap()
}
@@ -95,14 +94,14 @@ async fn reset_webhook_count_with_path(axum::extract::Path(reason): axum::extrac
async fn reset_webhook_count(Query(params): Query<ResetParams>, headers: HeaderMap) -> Response<String> {
// Output the value of the current counter
let current_count = WEBHOOK_COUNT.load(Ordering::SeqCst);
println!("Current webhook count: {}", current_count);
println!("Current webhook count: {current_count}");
let reason = params.reason.unwrap_or_else(|| "Reason not provided".to_string());
println!("Reset webhook count, reason: {}", reason);
println!("Reset webhook count, reason: {reason}");
for header in headers {
let (key, value) = header;
println!("Header: {:?}: {:?}", key, value);
println!("Header: {key:?}: {value:?}");
}
println!("Reset webhook count printed headers");
@@ -112,18 +111,18 @@ async fn reset_webhook_count(Query(params): Query<ResetParams>, headers: HeaderM
Response::builder()
.header("Foo", "Bar")
.status(StatusCode::OK)
.body(format!("Webhook count reset successfully current_count:{}", current_count))
.body(format!("Webhook count reset successfully current_count:{current_count}"))
.unwrap()
}
async fn is_service_active(addr: SocketAddr) -> Result<bool, String> {
let socket_addr = tokio::net::lookup_host(addr)
.await
.map_err(|e| format!("Unable to resolve host:{}", e))?
.map_err(|e| format!("Unable to resolve host:{e}"))?
.next()
.ok_or_else(|| "Address not found".to_string())?;
println!("Checking service status:{}", socket_addr);
println!("Checking service status:{socket_addr}");
match tokio::time::timeout(std::time::Duration::from_secs(5), tokio::net::TcpStream::connect(socket_addr)).await {
Ok(Ok(_)) => Ok(true),
@@ -131,7 +130,7 @@ async fn is_service_active(addr: SocketAddr) -> Result<bool, String> {
if e.kind() == std::io::ErrorKind::ConnectionRefused {
Ok(false)
} else {
Err(format!("Connection failed:{}", e))
Err(format!("Connection failed:{e}"))
}
}
Err(_) => Err("Connection timeout".to_string()),
@@ -149,7 +148,7 @@ async fn receive_webhook(Json(payload): Json<Value>) -> StatusCode {
let (year, month, day, hour, minute, second) = convert_seconds_to_date(seconds);
// output result
println!("current time:{:04}-{:02}-{:02} {:02}:{:02}:{:02}", year, month, day, hour, minute, second);
println!("current time:{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}");
println!(
"received a webhook request time:{} content:\n {}",
seconds,
+1 -1
View File
@@ -115,6 +115,6 @@ pub enum NotificationError {
impl From<url::ParseError> for TargetError {
fn from(err: url::ParseError) -> Self {
TargetError::Configuration(format!("URL parse error: {}", err))
TargetError::Configuration(format!("URL parse error: {err}"))
}
}
+1 -1
View File
@@ -413,7 +413,7 @@ impl Event {
owner_identity: Identity {
principal_id: "rustfs".to_string(),
},
arn: format!("arn:rustfs:s3:::{}", bucket),
arn: format!("arn:rustfs:s3:::{bucket}"),
},
object: Object {
key: key.to_string(),
+4 -4
View File
@@ -68,7 +68,7 @@ impl TargetFactory for WebhookTargetFactory {
let endpoint = get(ENV_WEBHOOK_ENDPOINT, WEBHOOK_ENDPOINT)
.ok_or_else(|| TargetError::Configuration("Missing webhook endpoint".to_string()))?;
let endpoint_url = Url::parse(&endpoint)
.map_err(|e| TargetError::Configuration(format!("Invalid endpoint URL: {} (value: '{}')", e, endpoint)))?;
.map_err(|e| TargetError::Configuration(format!("Invalid endpoint URL: {e} (value: '{endpoint}')")))?;
let auth_token = get(ENV_WEBHOOK_AUTH_TOKEN, WEBHOOK_AUTH_TOKEN).unwrap_or_default();
let queue_dir = get(ENV_WEBHOOK_QUEUE_DIR, WEBHOOK_QUEUE_DIR).unwrap_or(DEFAULT_DIR.to_string());
@@ -110,7 +110,7 @@ impl TargetFactory for WebhookTargetFactory {
debug!("endpoint: {}", endpoint);
let parsed_endpoint = endpoint.trim();
Url::parse(parsed_endpoint)
.map_err(|e| TargetError::Configuration(format!("Invalid endpoint URL: {} (value: '{}')", e, parsed_endpoint)))?;
.map_err(|e| TargetError::Configuration(format!("Invalid endpoint URL: {e} (value: '{parsed_endpoint}')")))?;
let client_cert = get(ENV_WEBHOOK_CLIENT_CERT, WEBHOOK_CLIENT_CERT).unwrap_or_default();
let client_key = get(ENV_WEBHOOK_CLIENT_KEY, WEBHOOK_CLIENT_KEY).unwrap_or_default();
@@ -151,7 +151,7 @@ impl TargetFactory for MQTTTargetFactory {
let broker =
get(ENV_MQTT_BROKER, MQTT_BROKER).ok_or_else(|| TargetError::Configuration("Missing MQTT broker".to_string()))?;
let broker_url = Url::parse(&broker)
.map_err(|e| TargetError::Configuration(format!("Invalid broker URL: {} (value: '{}')", e, broker)))?;
.map_err(|e| TargetError::Configuration(format!("Invalid broker URL: {e} (value: '{broker}')")))?;
let topic =
get(ENV_MQTT_TOPIC, MQTT_TOPIC).ok_or_else(|| TargetError::Configuration("Missing MQTT topic".to_string()))?;
@@ -217,7 +217,7 @@ impl TargetFactory for MQTTTargetFactory {
let broker =
get(ENV_MQTT_BROKER, MQTT_BROKER).ok_or_else(|| TargetError::Configuration("Missing MQTT broker".to_string()))?;
let url = Url::parse(&broker)
.map_err(|e| TargetError::Configuration(format!("Invalid broker URL: {} (value: '{}')", e, broker)))?;
.map_err(|e| TargetError::Configuration(format!("Invalid broker URL: {e} (value: '{broker}')")))?;
match url.scheme() {
"tcp" | "ssl" | "ws" | "wss" | "mqtt" | "mqtts" => {}
+2 -2
View File
@@ -472,9 +472,9 @@ impl Drop for NotificationSystem {
pub async fn load_config_from_file(path: &str, system: &NotificationSystem) -> Result<(), NotificationError> {
let config_data = tokio::fs::read(path)
.await
.map_err(|e| NotificationError::Configuration(format!("Failed to read config file: {}", e)))?;
.map_err(|e| NotificationError::Configuration(format!("Failed to read config file: {e}")))?;
let config = Config::unmarshal(config_data.as_slice())
.map_err(|e| NotificationError::Configuration(format!("Failed to parse config: {}", e)))?;
.map_err(|e| NotificationError::Configuration(format!("Failed to parse config: {e}")))?;
system.reload_config(config).await
}
+1 -1
View File
@@ -50,7 +50,7 @@ impl TargetRegistry {
let factory = self
.factories
.get(target_type)
.ok_or_else(|| TargetError::Configuration(format!("Unknown target type: {}", target_type)))?;
.ok_or_else(|| TargetError::Configuration(format!("Unknown target type: {target_type}")))?;
// Validate configuration before creating target
factory.validate_config(&id, config)?;
+3 -4
View File
@@ -62,7 +62,7 @@ impl std::fmt::Display for Key {
if self.compress {
file_name.push_str(COMPRESS_EXT);
}
write!(f, "{}", file_name)
write!(f, "{file_name}")
}
}
@@ -377,7 +377,7 @@ where
match deserializer.next() {
Some(Ok(item)) => items.push(item),
Some(Err(e)) => {
return Err(StoreError::Deserialization(format!("Failed to deserialize item in batch: {}", e)));
return Err(StoreError::Deserialization(format!("Failed to deserialize item in batch: {e}")));
}
None => {
// Reached end of stream sooner than item_count
@@ -393,8 +393,7 @@ where
} else if items.is_empty() {
// No items at all, but file existed
return Err(StoreError::Deserialization(format!(
"No items deserialized for key {} though file existed.",
key
"No items deserialized for key {key} though file existed."
)));
}
break;
+9 -9
View File
@@ -115,7 +115,7 @@ impl MQTTTarget {
error = %e,
"Failed to open store for MQTT target"
);
return Err(TargetError::Storage(format!("{}", e)));
return Err(TargetError::Storage(format!("{e}")));
}
Some(Box::new(store) as Box<dyn Store<Event, Error = StoreError, Key = Key> + Send + Sync>)
} else {
@@ -172,7 +172,7 @@ impl MQTTTarget {
if let Err(e) = new_client.subscribe(&args_clone.topic, args_clone.qos).await {
error!(target_id = %target_id_clone, error = %e, "Failed to subscribe to MQTT topic during init");
return Err(TargetError::Network(format!("MQTT subscribe failed: {}", e)));
return Err(TargetError::Network(format!("MQTT subscribe failed: {e}")));
}
let mut rx_guard = bg_task_manager.initial_cancel_rx.lock().await;
@@ -231,7 +231,7 @@ impl MQTTTarget {
.ok_or_else(|| TargetError::Configuration("MQTT client not initialized".to_string()))?;
let object_name = urlencoding::decode(&event.s3.object.key)
.map_err(|e| TargetError::Encoding(format!("Failed to decode object key: {}", e)))?;
.map_err(|e| TargetError::Encoding(format!("Failed to decode object key: {e}")))?;
let key = format!("{}/{}", event.s3.bucket.name, object_name);
@@ -242,11 +242,11 @@ impl MQTTTarget {
};
let data =
serde_json::to_vec(&log).map_err(|e| TargetError::Serialization(format!("Failed to serialize event: {}", e)))?;
serde_json::to_vec(&log).map_err(|e| TargetError::Serialization(format!("Failed to serialize event: {e}")))?;
// Vec<u8> Convert to String, only for printing logs
let data_string = String::from_utf8(data.clone())
.map_err(|e| TargetError::Encoding(format!("Failed to convert event data to UTF-8: {}", e)))?;
.map_err(|e| TargetError::Encoding(format!("Failed to convert event data to UTF-8: {e}")))?;
debug!("Sending event to mqtt target: {}, event log: {}", self.id, data_string);
client
@@ -258,7 +258,7 @@ impl MQTTTarget {
warn!(target_id = %self.id, error = %e, "Publish failed due to connection issue, marking as not connected.");
TargetError::NotConnected
} else {
TargetError::Request(format!("Failed to publish message: {}", e))
TargetError::Request(format!("Failed to publish message: {e}"))
}
})?;
@@ -476,7 +476,7 @@ impl Target for MQTTTarget {
}
Err(e) => {
error!(target_id = %self.id, error = %e, "Failed to save event to store");
return Err(TargetError::Storage(format!("Failed to save event to store: {}", e)));
return Err(TargetError::Storage(format!("Failed to save event to store: {e}")));
}
}
} else {
@@ -547,7 +547,7 @@ impl Target for MQTTTarget {
error = %e,
"Failed to get event from store"
);
return Err(TargetError::Storage(format!("Failed to get event from store: {}", e)));
return Err(TargetError::Storage(format!("Failed to get event from store: {e}")));
}
};
@@ -571,7 +571,7 @@ impl Target for MQTTTarget {
}
Err(e) => {
error!(target_id = %self.id, error = %e, "Failed to delete event from store after send.");
return Err(TargetError::Storage(format!("Failed to delete event from store: {}", e)));
return Err(TargetError::Storage(format!("Failed to delete event from store: {e}")));
}
}
+15 -15
View File
@@ -111,19 +111,19 @@ impl WebhookTarget {
if !args.client_cert.is_empty() && !args.client_key.is_empty() {
// Add client certificate
let cert = std::fs::read(&args.client_cert)
.map_err(|e| TargetError::Configuration(format!("Failed to read client cert: {}", e)))?;
.map_err(|e| TargetError::Configuration(format!("Failed to read client cert: {e}")))?;
let key = std::fs::read(&args.client_key)
.map_err(|e| TargetError::Configuration(format!("Failed to read client key: {}", e)))?;
.map_err(|e| TargetError::Configuration(format!("Failed to read client key: {e}")))?;
let identity = reqwest::Identity::from_pem(&[cert, key].concat())
.map_err(|e| TargetError::Configuration(format!("Failed to create identity: {}", e)))?;
.map_err(|e| TargetError::Configuration(format!("Failed to create identity: {e}")))?;
client_builder = client_builder.identity(identity);
}
let http_client = Arc::new(
client_builder
.build()
.map_err(|e| TargetError::Configuration(format!("Failed to build HTTP client: {}", e)))?,
.map_err(|e| TargetError::Configuration(format!("Failed to build HTTP client: {e}")))?,
);
// Build storage
@@ -138,7 +138,7 @@ impl WebhookTarget {
if let Err(e) = store.open() {
error!("Failed to open store for Webhook target {}: {}", target_id.id, e);
return Err(TargetError::Storage(format!("{}", e)));
return Err(TargetError::Storage(format!("{e}")));
}
// Make sure that the Store trait implemented by QueueStore matches the expected error type
@@ -154,7 +154,7 @@ impl WebhookTarget {
.endpoint
.port()
.unwrap_or_else(|| if args.endpoint.scheme() == "https" { 443 } else { 80 });
format!("{}:{}", host, port)
format!("{host}:{port}")
};
// Create a cancel channel
@@ -196,7 +196,7 @@ impl WebhookTarget {
async fn send(&self, event: &Event) -> Result<(), TargetError> {
info!("Webhook Sending event to webhook target: {}", self.id);
let object_name = urlencoding::decode(&event.s3.object.key)
.map_err(|e| TargetError::Encoding(format!("Failed to decode object key: {}", e)))?;
.map_err(|e| TargetError::Encoding(format!("Failed to decode object key: {e}")))?;
let key = format!("{}/{}", event.s3.bucket.name, object_name);
@@ -207,11 +207,11 @@ impl WebhookTarget {
};
let data =
serde_json::to_vec(&log).map_err(|e| TargetError::Serialization(format!("Failed to serialize event: {}", e)))?;
serde_json::to_vec(&log).map_err(|e| TargetError::Serialization(format!("Failed to serialize event: {e}")))?;
// Vec<u8> Convert to String
let data_string = String::from_utf8(data.clone())
.map_err(|e| TargetError::Encoding(format!("Failed to convert event data to UTF-8: {}", e)))?;
.map_err(|e| TargetError::Encoding(format!("Failed to convert event data to UTF-8: {e}")))?;
debug!("Sending event to webhook target: {}, event log: {}", self.id, data_string);
// build request
@@ -243,7 +243,7 @@ impl WebhookTarget {
if e.is_timeout() || e.is_connect() {
TargetError::NotConnected
} else {
TargetError::Request(format!("Failed to send request: {}", e))
TargetError::Request(format!("Failed to send request: {e}"))
}
})?;
@@ -275,7 +275,7 @@ impl Target for WebhookTarget {
async fn is_active(&self) -> Result<bool, TargetError> {
let socket_addr = lookup_host(&self.addr)
.await
.map_err(|e| TargetError::Network(format!("Failed to resolve host: {}", e)))?
.map_err(|e| TargetError::Network(format!("Failed to resolve host: {e}")))?
.next()
.ok_or_else(|| TargetError::Network("No address found".to_string()))?;
debug!("is_active socket addr: {},target id:{}", socket_addr, self.id.id);
@@ -289,7 +289,7 @@ impl Target for WebhookTarget {
if e.kind() == std::io::ErrorKind::ConnectionRefused {
Err(TargetError::NotConnected)
} else {
Err(TargetError::Network(format!("Connection failed: {}", e)))
Err(TargetError::Network(format!("Connection failed: {e}")))
}
}
Err(_) => Err(TargetError::Timeout("Connection timed out".to_string())),
@@ -301,7 +301,7 @@ impl Target for WebhookTarget {
// Call the store method directly, no longer need to acquire the lock
store
.put(event)
.map_err(|e| TargetError::Storage(format!("Failed to save event to store: {}", e)))?;
.map_err(|e| TargetError::Storage(format!("Failed to save event to store: {e}")))?;
debug!("Event saved to store for target: {}", self.id);
Ok(())
} else {
@@ -338,7 +338,7 @@ impl Target for WebhookTarget {
Ok(event) => event,
Err(StoreError::NotFound) => return Ok(()),
Err(e) => {
return Err(TargetError::Storage(format!("Failed to get event from store: {}", e)));
return Err(TargetError::Storage(format!("Failed to get event from store: {e}")));
}
};
@@ -355,7 +355,7 @@ impl Target for WebhookTarget {
Ok(_) => debug!("Event deleted from store for target: {}, key:{}, end", self.id, key.to_string()),
Err(e) => {
error!("Failed to delete event from store: {}", e);
return Err(TargetError::Storage(format!("Failed to delete event from store: {}", e)));
return Err(TargetError::Storage(format!("Failed to delete event from store: {e}")));
}
}
+1 -1
View File
@@ -199,7 +199,7 @@ impl FileSinkConfig {
let temp_dir = env::temp_dir().join("rustfs");
if let Err(e) = std::fs::create_dir_all(&temp_dir) {
eprintln!("Failed to create log directory: {}", e);
eprintln!("Failed to create log directory: {e}");
return "rustfs/rustfs.log".to_string();
}
temp_dir
+2 -2
View File
@@ -108,7 +108,7 @@ impl FileSink {
#[async_trait]
impl Sink for FileSink {
async fn write(&self, entry: &UnifiedLogEntry) {
let line = format!("{:?}\n", entry);
let line = format!("{entry:?}\n");
let mut writer = self.writer.lock().await;
if let Err(e) = writer.write_all(line.as_bytes()).await {
@@ -156,7 +156,7 @@ impl Drop for FileSink {
rt.block_on(async {
let mut writer = writer.lock().await;
if let Err(e) = writer.flush().await {
eprintln!("Failed to flush log file {}: {}", path, e);
eprintln!("Failed to flush log file {path}: {e}");
}
});
});
+10 -12
View File
@@ -65,18 +65,18 @@ impl Drop for OtelGuard {
fn drop(&mut self) {
if let Some(provider) = self.tracer_provider.take() {
if let Err(err) = provider.shutdown() {
eprintln!("Tracer shutdown error: {:?}", err);
eprintln!("Tracer shutdown error: {err:?}");
}
}
if let Some(provider) = self.meter_provider.take() {
if let Err(err) = provider.shutdown() {
eprintln!("Meter shutdown error: {:?}", err);
eprintln!("Meter shutdown error: {err:?}");
}
}
if let Some(provider) = self.logger_provider.take() {
if let Err(err) = provider.shutdown() {
eprintln!("Logger shutdown error: {:?}", err);
eprintln!("Logger shutdown error: {err:?}");
}
}
}
@@ -334,8 +334,7 @@ pub(crate) fn init_telemetry(config: &OtelConfig) -> OtelGuard {
let flexi_logger_result = flexi_logger::Logger::try_with_env_or_str(logger_level)
.unwrap_or_else(|e| {
eprintln!(
"Invalid logger level: {}, using default: {}, failed error: {:?}",
logger_level, DEFAULT_LOG_LEVEL, e
"Invalid logger level: {logger_level}, using default: {DEFAULT_LOG_LEVEL}, failed error: {e:?}"
);
flexi_logger::Logger::with(log_spec.clone())
})
@@ -356,19 +355,18 @@ pub(crate) fn init_telemetry(config: &OtelConfig) -> OtelGuard {
// Save the logger handle to keep the logging
flexi_logger_handle = Some(logger);
eprintln!("Flexi logger initialized with file logging to {}/{}.log", log_directory, log_filename);
eprintln!("Flexi logger initialized with file logging to {log_directory}/{log_filename}.log");
// Log logging of log cutting conditions
match (config.log_rotation_time.as_deref(), config.log_rotation_size_mb) {
(Some(time), Some(size)) => eprintln!(
"Log rotation configured for: every {} or when size exceeds {}MB, keeping {} files",
time, size, keep_files
"Log rotation configured for: every {time} or when size exceeds {size}MB, keeping {keep_files} files"
),
(Some(time), None) => eprintln!("Log rotation configured for: every {}, keeping {} files", time, keep_files),
(Some(time), None) => eprintln!("Log rotation configured for: every {time}, keeping {keep_files} files"),
(None, Some(size)) => {
eprintln!("Log rotation configured for: when size exceeds {}MB, keeping {} files", size, keep_files)
eprintln!("Log rotation configured for: when size exceeds {size}MB, keeping {keep_files} files")
}
_ => eprintln!("Log rotation configured for: daily, keeping {} files", keep_files),
_ => eprintln!("Log rotation configured for: daily, keeping {keep_files} files"),
}
} else {
eprintln!("Failed to initialize flexi_logger: {:?}", flexi_logger_result.err());
@@ -389,7 +387,7 @@ fn build_env_filter(logger_level: &str, default_level: Option<&str>) -> EnvFilte
if !matches!(logger_level, "trace" | "debug") {
let directives: SmallVec<[&str; 5]> = smallvec::smallvec!["hyper", "tonic", "h2", "reqwest", "tower"];
for directive in directives {
filter = filter.add_directive(format!("{}=off", directive).parse().unwrap());
filter = filter.add_directive(format!("{directive}=off").parse().unwrap());
}
}
+1 -1
View File
@@ -660,7 +660,7 @@ mod tests {
let json = index.to_json().unwrap();
let json_str = String::from_utf8(json).unwrap();
println!("json_str: {}", json_str);
println!("json_str: {json_str}");
// 验证 JSON 内容
assert!(json_str.contains("\"compressed\": 100"));
+2 -2
View File
@@ -191,7 +191,7 @@ mod tests {
// Extract ETag using our generic system
let extracted_etag = resolve_etag_generic(&mut compress_reader);
println!("📋 Extracted ETag: {:?}", extracted_etag);
println!("📋 Extracted ETag: {extracted_etag:?}");
assert_eq!(extracted_etag, Some("real_world_etag".to_string()));
@@ -206,7 +206,7 @@ mod tests {
let mut compress_reader2 = CompressReader::new(encrypt_reader2, CompressionAlgorithm::Zstd);
let trait_etag = resolve_etag_generic(&mut compress_reader2);
println!("📋 Trait-based ETag: {:?}", trait_etag);
println!("📋 Trait-based ETag: {trait_etag:?}");
assert_eq!(trait_etag, Some("core_etag".to_string()));
+1 -1
View File
@@ -112,7 +112,7 @@ mod tests {
// 读取超限,应该返回错误
let err = match read_full(&mut r, &mut buf).await {
Ok(n) => {
println!("Read {} bytes", n);
println!("Read {n} bytes");
assert_eq!(n, 3);
assert_eq!(&buf[..n], b"abc");
None
+4 -5
View File
@@ -396,7 +396,7 @@ mod tests {
let expected = format!("{:x}", hasher.finalize());
println!("expected: {}", expected);
println!("expected: {expected}");
let reader = Cursor::new(data.clone());
let reader = BufReader::new(reader);
@@ -485,8 +485,7 @@ mod tests {
// 验证 etag(注意:压缩会改变数据,所以这里的 etag 验证可能需要调整)
println!(
"Test completed successfully with compression: {}, encryption: {}",
is_compress, is_encrypt
"Test completed successfully with compression: {is_compress}, encryption: {is_encrypt}"
);
}
@@ -549,7 +548,7 @@ mod tests {
];
for algorithm in algorithms {
println!("\nTesting algorithm: {:?}", algorithm);
println!("\nTesting algorithm: {algorithm:?}");
let reader = BufReader::new(Cursor::new(data.clone()));
let reader = Box::new(WarpReader::new(reader));
@@ -576,7 +575,7 @@ mod tests {
// Verify
assert_eq!(decompressed_data.len(), data.len());
assert_eq!(&decompressed_data, &data);
println!(" ✓ Algorithm {:?} test passed", algorithm);
println!(" ✓ Algorithm {algorithm:?} test passed");
}
}
}
+8 -8
View File
@@ -26,7 +26,7 @@ static HTTP_DEBUG_LOG: bool = false;
#[inline(always)]
fn http_debug_log(args: std::fmt::Arguments) {
if HTTP_DEBUG_LOG {
println!("{}", args);
println!("{args}");
}
}
macro_rules! http_log {
@@ -87,7 +87,7 @@ impl HttpReader {
let resp = request
.send()
.await
.map_err(|e| Error::other(format!("HttpReader HTTP request error: {}", e)))?;
.map_err(|e| Error::other(format!("HttpReader HTTP request error: {e}")))?;
if resp.status().is_success().not() {
return Err(Error::other(format!(
@@ -98,7 +98,7 @@ impl HttpReader {
let stream = resp
.bytes_stream()
.map_err(|e| Error::other(format!("HttpReader stream error: {}", e)));
.map_err(|e| Error::other(format!("HttpReader stream error: {e}")));
Ok(Self {
inner: StreamReader::new(Box::pin(stream)),
@@ -250,8 +250,8 @@ impl HttpWriter {
}
Err(e) => {
// http_log!("[HttpWriter::spawn] HTTP request error: {e}");
let _ = err_tx.send(Error::other(format!("HTTP request failed: {}", e)));
return Err(Error::other(format!("HTTP request failed: {}", e)));
let _ = err_tx.send(Error::other(format!("HTTP request failed: {e}")));
return Err(Error::other(format!("HTTP request failed: {e}")));
}
}
@@ -298,7 +298,7 @@ impl AsyncWrite for HttpWriter {
self.sender
.try_send(Some(Bytes::copy_from_slice(buf)))
.map_err(|e| Error::other(format!("HttpWriter send error: {}", e)))?;
.map_err(|e| Error::other(format!("HttpWriter send error: {e}")))?;
Poll::Ready(Ok(buf.len()))
}
@@ -315,7 +315,7 @@ impl AsyncWrite for HttpWriter {
// http_log!("[HttpWriter::poll_shutdown] url: {}, method: {:?}", url, method);
self.sender
.try_send(None)
.map_err(|e| Error::other(format!("HttpWriter shutdown error: {}", e)))?;
.map_err(|e| Error::other(format!("HttpWriter shutdown error: {e}")))?;
// http_log!(
// "[HttpWriter::poll_shutdown] sent shutdown signal to HTTP request, url: {}, method: {:?}",
// url,
@@ -336,7 +336,7 @@ impl AsyncWrite for HttpWriter {
}
Poll::Ready(Err(e)) => {
// http_log!("[HttpWriter::poll_shutdown] HTTP request failed: {e}, url: {}, method: {:?}", url, method);
return Poll::Ready(Err(Error::other(format!("HTTP request failed: {}", e))));
return Poll::Ready(Err(Error::other(format!("HTTP request failed: {e}"))));
}
Poll::Pending => {
// http_log!("[HttpWriter::poll_shutdown] HTTP request pending, url: {}, method: {:?}", url, method);
+15 -18
View File
@@ -14,17 +14,16 @@ use tracing::{debug, warn};
/// This function loads a public certificate from the specified file.
pub fn load_certs(filename: &str) -> io::Result<Vec<CertificateDer<'static>>> {
// Open certificate file.
let cert_file = fs::File::open(filename).map_err(|e| certs_error(format!("failed to open {}: {}", filename, e)))?;
let cert_file = fs::File::open(filename).map_err(|e| certs_error(format!("failed to open {filename}: {e}")))?;
let mut reader = io::BufReader::new(cert_file);
// Load and return certificate.
let certs = certs(&mut reader)
.collect::<Result<Vec<_>, _>>()
.map_err(|e| certs_error(format!("certificate file {} format error:{:?}", filename, e)))?;
.map_err(|e| certs_error(format!("certificate file {filename} format error:{e:?}")))?;
if certs.is_empty() {
return Err(certs_error(format!(
"No valid certificate was found in the certificate file {}",
filename
"No valid certificate was found in the certificate file {filename}"
)));
}
Ok(certs)
@@ -34,11 +33,11 @@ pub fn load_certs(filename: &str) -> io::Result<Vec<CertificateDer<'static>>> {
/// This function loads a private key from the specified file.
pub fn load_private_key(filename: &str) -> io::Result<PrivateKeyDer<'static>> {
// Open keyfile.
let keyfile = fs::File::open(filename).map_err(|e| certs_error(format!("failed to open {}: {}", filename, e)))?;
let keyfile = fs::File::open(filename).map_err(|e| certs_error(format!("failed to open {filename}: {e}")))?;
let mut reader = io::BufReader::new(keyfile);
// Load and return a single private key.
private_key(&mut reader)?.ok_or_else(|| certs_error(format!("no private key found in {}", filename)))
private_key(&mut reader)?.ok_or_else(|| certs_error(format!("no private key found in {filename}")))
}
/// error function
@@ -58,8 +57,7 @@ pub fn load_all_certs_from_directory(
if !dir.exists() || !dir.is_dir() {
return Err(certs_error(format!(
"The certificate directory does not exist or is not a directory: {}",
dir_path
"The certificate directory does not exist or is not a directory: {dir_path}"
)));
}
@@ -71,10 +69,10 @@ pub fn load_all_certs_from_directory(
debug!("find the root directory certificate: {:?}", root_cert_path);
let root_cert_str = root_cert_path
.to_str()
.ok_or_else(|| certs_error(format!("Invalid UTF-8 in root certificate path: {:?}", root_cert_path)))?;
.ok_or_else(|| certs_error(format!("Invalid UTF-8 in root certificate path: {root_cert_path:?}")))?;
let root_key_str = root_key_path
.to_str()
.ok_or_else(|| certs_error(format!("Invalid UTF-8 in root key path: {:?}", root_key_path)))?;
.ok_or_else(|| certs_error(format!("Invalid UTF-8 in root key path: {root_key_path:?}")))?;
match load_cert_key_pair(root_cert_str, root_key_str) {
Ok((certs, key)) => {
// The root directory certificate is used as the default certificate and is stored using special keys.
@@ -95,7 +93,7 @@ pub fn load_all_certs_from_directory(
let domain_name = path
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| certs_error(format!("invalid domain name directory:{:?}", path)))?;
.ok_or_else(|| certs_error(format!("invalid domain name directory:{path:?}")))?;
// find certificate and private key files
let cert_path = path.join(RUSTFS_TLS_CERT); // e.g., rustfs_cert.pem
@@ -117,8 +115,7 @@ pub fn load_all_certs_from_directory(
if cert_key_pairs.is_empty() {
return Err(certs_error(format!(
"No valid certificate/private key pair found in directory {}",
dir_path
"No valid certificate/private key pair found in directory {dir_path}"
)));
}
@@ -165,7 +162,7 @@ pub fn create_multi_cert_resolver(
for (domain, (certs, key)) in cert_key_pairs {
// create a signature
let signing_key = rustls::crypto::aws_lc_rs::sign::any_supported_type(&key)
.map_err(|e| certs_error(format!("unsupported private key types:{}, err:{:?}", domain, e)))?;
.map_err(|e| certs_error(format!("unsupported private key types:{domain}, err:{e:?}")))?;
// create a CertifiedKey
let certified_key = CertifiedKey::new(certs, signing_key);
@@ -175,7 +172,7 @@ pub fn create_multi_cert_resolver(
// add certificate to resolver
resolver
.add(&domain, certified_key)
.map_err(|e| certs_error(format!("failed to add a domain name certificate:{},err: {:?}", domain, e)))?;
.map_err(|e| certs_error(format!("failed to add a domain name certificate:{domain},err: {e:?}")))?;
}
}
@@ -343,10 +340,10 @@ mod tests {
];
for (input, _expected_pattern) in test_cases {
let error1 = certs_error(format!("failed to open test.pem: {}", input));
let error1 = certs_error(format!("failed to open test.pem: {input}"));
assert!(error1.to_string().contains(input));
let error2 = certs_error(format!("failed to open key.pem: {}", input));
let error2 = certs_error(format!("failed to open key.pem: {input}"));
assert!(error2.to_string().contains(input));
}
}
@@ -455,6 +452,6 @@ mod tests {
let error_size = mem::size_of_val(&error);
// Error should not be excessively large
assert!(error_size < 1024, "Error size should be reasonable, got {} bytes", error_size);
assert!(error_size < 1024, "Error size should be reasonable, got {error_size} bytes");
}
}
+2 -2
View File
@@ -44,7 +44,7 @@ impl std::str::FromStr for CompressionAlgorithm {
"brotli" => Ok(CompressionAlgorithm::Brotli),
"snappy" => Ok(CompressionAlgorithm::Snappy),
"none" => Ok(CompressionAlgorithm::None),
_ => Err(std::io::Error::other(format!("Unsupported compression algorithm: {}", s))),
_ => Err(std::io::Error::other(format!("Unsupported compression algorithm: {s}"))),
}
}
}
@@ -243,7 +243,7 @@ mod tests {
println!("Compression results:");
for (name, dur, size) in &times {
println!("{}: {} bytes, {:?}", name, size, dur);
println!("{name}: {size} bytes, {dur:?}");
}
// All should decompress to the original
assert_eq!(decompress_block(&gzip, CompressionAlgorithm::Gzip).unwrap(), data);
+1 -1
View File
@@ -54,7 +54,7 @@ mod tests {
assert!(path.exists(), "The project root directory does not exist:{}", path.display());
println!("The test is passed, the project root directory:{}", path.display());
}
Err(e) => panic!("Failed to get the project root directory:{}", e),
Err(e) => panic!("Failed to get the project root directory:{e}"),
}
}
}
+4 -4
View File
@@ -29,7 +29,7 @@ pub async fn read_full<R: AsyncRead + Send + Sync + Unpin>(mut reader: R, mut bu
}
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
format!("read {} bytes, error: {}", total, e),
format!("read {total} bytes, error: {e}"),
));
}
};
@@ -116,7 +116,7 @@ mod tests {
rev[total - n..total].copy_from_slice(&buf[..n]);
count += 1;
println!("count: {}, total: {}, n: {}", count, total, n);
println!("count: {count}, total: {total}, n: {n}");
}
assert_eq!(total, size);
@@ -167,8 +167,8 @@ mod tests {
for &v in &[1u64, 127, 128, 255, 300, 16384, u32::MAX as u64] {
let n = put_uvarint(&mut buf, v);
let (decoded, m) = uvarint(&buf[..n]);
assert_eq!(decoded, v, "decode mismatch for {}", v);
assert_eq!(m as usize, n, "length mismatch for {}", v);
assert_eq!(decoded, v, "decode mismatch for {v}");
assert_eq!(m as usize, n, "length mismatch for {v}");
}
}
+12 -12
View File
@@ -40,16 +40,16 @@ mod tests {
assert!(ip.is_some(), "Should be able to get local IP address");
if let Some(ip_addr) = ip {
println!("Local IP address: {}", ip_addr);
println!("Local IP address: {ip_addr}");
// Verify that the returned IP address is valid
match ip_addr {
IpAddr::V4(ipv4) => {
assert!(!ipv4.is_unspecified(), "IPv4 should not be unspecified (0.0.0.0)");
println!("Got IPv4 address: {}", ipv4);
println!("Got IPv4 address: {ipv4}");
}
IpAddr::V6(ipv6) => {
assert!(!ipv6.is_unspecified(), "IPv6 should not be unspecified (::)");
println!("Got IPv6 address: {}", ipv6);
println!("Got IPv6 address: {ipv6}");
}
}
}
@@ -63,9 +63,9 @@ mod tests {
// Verify that the returned string can be parsed as a valid IP address
let parsed_ip: Result<IpAddr, _> = ip_string.parse();
assert!(parsed_ip.is_ok(), "Returned string should be a valid IP address: {}", ip_string);
assert!(parsed_ip.is_ok(), "Returned string should be a valid IP address: {ip_string}");
println!("Local IP with default: {}", ip_string);
println!("Local IP with default: {ip_string}");
}
#[test]
@@ -91,22 +91,22 @@ mod tests {
match ip {
IpAddr::V4(ipv4) => {
// Test IPv4 address properties
println!("IPv4 address: {}", ipv4);
println!("IPv4 address: {ipv4}");
assert!(!ipv4.is_multicast(), "Local IP should not be multicast");
assert!(!ipv4.is_broadcast(), "Local IP should not be broadcast");
// Check if it's a private address (usually local IP is private)
let is_private = ipv4.is_private();
let is_loopback = ipv4.is_loopback();
println!("IPv4 is private: {}, is loopback: {}", is_private, is_loopback);
println!("IPv4 is private: {is_private}, is loopback: {is_loopback}");
}
IpAddr::V6(ipv6) => {
// Test IPv6 address properties
println!("IPv6 address: {}", ipv6);
println!("IPv6 address: {ipv6}");
assert!(!ipv6.is_multicast(), "Local IP should not be multicast");
let is_loopback = ipv6.is_loopback();
println!("IPv6 is loopback: {}", is_loopback);
println!("IPv6 is loopback: {is_loopback}");
}
}
}
@@ -126,7 +126,7 @@ mod tests {
let back_to_string = parsed_ip.to_string();
// For standard IP addresses, round-trip conversion should be consistent
println!("Original: {}, Parsed back: {}", ip_string, back_to_string);
println!("Original: {ip_string}, Parsed back: {back_to_string}");
}
#[test]
@@ -186,7 +186,7 @@ mod tests {
// If it's not a loopback address, it should be routable
if !ipv4.is_loopback() {
println!("Got routable IPv4: {}", ipv4);
println!("Got routable IPv4: {ipv4}");
}
}
IpAddr::V6(ipv6) => {
@@ -194,7 +194,7 @@ mod tests {
assert!(!ipv6.is_unspecified(), "Should not be ::");
if !ipv6.is_loopback() {
println!("Got routable IPv6: {}", ipv6);
println!("Got routable IPv6: {ipv6}");
}
}
}
+6 -9
View File
@@ -111,7 +111,7 @@ pub fn get_available_port() -> u16 {
pub fn must_get_local_ips() -> std::io::Result<Vec<IpAddr>> {
match netif::up() {
Ok(up) => Ok(up.map(|x| x.address().to_owned()).collect()),
Err(err) => Err(std::io::Error::other(format!("Unable to get IP addresses of this host: {}", err))),
Err(err) => Err(std::io::Error::other(format!("Unable to get IP addresses of this host: {err}"))),
}
}
@@ -260,7 +260,7 @@ pub fn parse_and_resolve_address(addr_str: &str) -> std::io::Result<SocketAddr>
let port_str = port;
let port: u16 = port_str
.parse()
.map_err(|e| std::io::Error::other(format!("Invalid port format: {}, err:{:?}", addr_str, e)))?;
.map_err(|e| std::io::Error::other(format!("Invalid port format: {addr_str}, err:{e:?}")))?;
let final_port = if port == 0 {
get_available_port() // assume get_available_port is available here
} else {
@@ -342,7 +342,7 @@ mod test {
for (addr, expected) in test_cases {
let result = is_socket_addr(addr);
assert_eq!(expected, result, "addr: '{}', expected: {}, got: {}", addr, expected, result);
assert_eq!(expected, result, "addr: '{addr}', expected: {expected}, got: {result}");
}
}
@@ -353,7 +353,7 @@ mod test {
for addr in valid_cases {
let result = check_local_server_addr(addr);
assert!(result.is_ok(), "Expected '{}' to be valid, but got error: {:?}", addr, result);
assert!(result.is_ok(), "Expected '{addr}' to be valid, but got error: {result:?}");
}
// Test invalid addresses
@@ -368,15 +368,12 @@ mod test {
for (addr, expected_error_pattern) in invalid_cases {
let result = check_local_server_addr(addr);
assert!(result.is_err(), "Expected '{}' to be invalid, but it was accepted: {:?}", addr, result);
assert!(result.is_err(), "Expected '{addr}' to be invalid, but it was accepted: {result:?}");
let error_msg = result.unwrap_err().to_string();
assert!(
error_msg.contains(expected_error_pattern) || error_msg.contains("invalid socket address"),
"Error message '{}' doesn't contain expected pattern '{}' for address '{}'",
error_msg,
expected_error_pattern,
addr
"Error message '{error_msg}' doesn't contain expected pattern '{expected_error_pattern}' for address '{addr}'"
);
}
}
+2 -2
View File
@@ -60,7 +60,7 @@ mod tests {
let temp_dir = tempfile::tempdir().unwrap();
let info = get_info(temp_dir.path()).unwrap();
println!("Disk Info: {:?}", info);
println!("Disk Info: {info:?}");
assert!(info.total > 0);
assert!(info.free > 0);
@@ -98,7 +98,7 @@ mod tests {
let result = same_disk(path1, path2).unwrap();
// Since both temporary directories are created in the same file system,
// they should be on the same disk in most cases
println!("Path1: {}, Path2: {}, Same disk: {}", path1, path2, result);
println!("Path1: {path1}, Path2: {path2}, Same disk: {result}");
// Test passes if the function doesn't panic - the actual result depends on test environment
}
+4 -4
View File
@@ -44,7 +44,7 @@ pub fn retain_slash(s: &str) -> String {
if s.ends_with(SLASH_SEPARATOR) {
s.to_string()
} else {
format!("{}{}", s, SLASH_SEPARATOR)
format!("{s}{SLASH_SEPARATOR}")
}
}
@@ -91,7 +91,7 @@ pub fn path_join_buf(elements: &[&str]) -> String {
let clean_path = cpath.to_string_lossy();
if trailing_slash {
return format!("{}{}", clean_path, SLASH_SEPARATOR);
return format!("{clean_path}{SLASH_SEPARATOR}");
}
clean_path.to_string()
}
@@ -265,9 +265,9 @@ mod tests {
#[test]
fn test_base_dir_from_prefix() {
let a = "da/";
println!("---- in {}", a);
println!("---- in {a}");
let a = base_dir_from_prefix(a);
println!("---- out {}", a);
println!("---- out {a}");
}
#[test]
+5 -7
View File
@@ -7,7 +7,7 @@ pub fn parse_bool(str: &str) -> Result<bool> {
match str {
"1" | "t" | "T" | "true" | "TRUE" | "True" | "on" | "ON" | "On" | "enabled" => Ok(true),
"0" | "f" | "F" | "false" | "FALSE" | "False" | "off" | "OFF" | "Off" | "disabled" => Ok(false),
_ => Err(Error::other(format!("ParseBool: parsing {}", str))),
_ => Err(Error::other(format!("ParseBool: parsing {str}"))),
}
}
@@ -208,8 +208,7 @@ pub fn find_ellipses_patterns(arg: &str) -> Result<ArgPattern> {
Some(caps) => caps,
None => {
return Err(Error::other(format!(
"Invalid ellipsis format in ({}), Ellipsis range must be provided in format {{N...M}} where N and M are positive integers, M must be greater than N, with an allowed minimum range of 4",
arg
"Invalid ellipsis format in ({arg}), Ellipsis range must be provided in format {{N...M}} where N and M are positive integers, M must be greater than N, with an allowed minimum range of 4"
)));
}
};
@@ -248,8 +247,7 @@ pub fn find_ellipses_patterns(arg: &str) -> Result<ArgPattern> {
|| p.suffix.contains(CLOSE_BRACES)
{
return Err(Error::other(format!(
"Invalid ellipsis format in ({}), Ellipsis range must be provided in format {{N...M}} where N and M are positive integers, M must be greater than N, with an allowed minimum range of 4",
arg
"Invalid ellipsis format in ({arg}), Ellipsis range must be provided in format {{N...M}} where N and M are positive integers, M must be greater than N, with an allowed minimum range of 4"
)));
}
}
@@ -300,7 +298,7 @@ pub fn parse_ellipses_range(pattern: &str) -> Result<Vec<String>> {
if ellipses_range[0].starts_with('0') && ellipses_range[0].len() > 1 {
ret.push(format!("{:0width$}", i, width = ellipses_range[1].len()));
} else {
ret.push(format!("{}", i));
ret.push(format!("{i}"));
}
}
@@ -381,7 +379,7 @@ mod tests {
for (i, args, expected) in test_cases {
let ret = has_ellipses(&args);
assert_eq!(ret, expected, "Test{}: Expected {}, got {}", i, expected, ret);
assert_eq!(ret, expected, "Test{i}: Expected {expected}, got {ret}");
}
}
+15 -15
View File
@@ -95,7 +95,7 @@ impl UserAgent {
let cpu_info = if arch == "aarch64" { "Apple" } else { "Intel" };
// Convert to User-Agent format
format!("Macintosh; {} Mac OS X {}_{}_{}", cpu_info, major, minor, patch)
format!("Macintosh; {cpu_info} Mac OS X {major}_{minor}_{patch}")
}
#[cfg(not(target_os = "macos"))]
@@ -145,40 +145,40 @@ mod tests {
fn test_user_agent_format_basis() {
let ua = get_user_agent(ServiceType::Basis);
assert!(ua.starts_with("Mozilla/5.0"));
assert!(ua.contains(&format!("RustFS/{}", VERSION).to_string()));
println!("User-Agent: {}", ua);
assert!(ua.contains(&format!("RustFS/{VERSION}").to_string()));
println!("User-Agent: {ua}");
}
#[test]
fn test_user_agent_format_core() {
let ua = get_user_agent(ServiceType::Core);
assert!(ua.starts_with("Mozilla/5.0"));
assert!(ua.contains(&format!("RustFS/{} (core)", VERSION).to_string()));
println!("User-Agent: {}", ua);
assert!(ua.contains(&format!("RustFS/{VERSION} (core)").to_string()));
println!("User-Agent: {ua}");
}
#[test]
fn test_user_agent_format_event() {
let ua = get_user_agent(ServiceType::Event);
assert!(ua.starts_with("Mozilla/5.0"));
assert!(ua.contains(&format!("RustFS/{} (event)", VERSION).to_string()));
println!("User-Agent: {}", ua);
assert!(ua.contains(&format!("RustFS/{VERSION} (event)").to_string()));
println!("User-Agent: {ua}");
}
#[test]
fn test_user_agent_format_logger() {
let ua = get_user_agent(ServiceType::Logger);
assert!(ua.starts_with("Mozilla/5.0"));
assert!(ua.contains(&format!("RustFS/{} (logger)", VERSION).to_string()));
println!("User-Agent: {}", ua);
assert!(ua.contains(&format!("RustFS/{VERSION} (logger)").to_string()));
println!("User-Agent: {ua}");
}
#[test]
fn test_user_agent_format_custom() {
let ua = get_user_agent(ServiceType::Custom("monitor".to_string()));
assert!(ua.starts_with("Mozilla/5.0"));
assert!(ua.contains(&format!("RustFS/{} (monitor)", VERSION).to_string()));
println!("User-Agent: {}", ua);
assert!(ua.contains(&format!("RustFS/{VERSION} (monitor)").to_string()));
println!("User-Agent: {ua}");
}
#[test]
@@ -189,9 +189,9 @@ mod tests {
let ua_logger = get_user_agent(ServiceType::Logger);
let ua_custom = get_user_agent(ServiceType::Custom("monitor".to_string()));
println!("Core User-Agent: {}", ua_core);
println!("Event User-Agent: {}", ua_event);
println!("Logger User-Agent: {}", ua_logger);
println!("Custom User-Agent: {}", ua_custom);
println!("Core User-Agent: {ua_core}");
println!("Event User-Agent: {ua_event}");
println!("Logger User-Agent: {ua_logger}");
println!("Custom User-Agent: {ua_custom}");
}
}
+13 -17
View File
@@ -347,11 +347,11 @@ mod tests {
fn test_compression_format_debug() {
// Test Debug trait implementation
let format = CompressionFormat::Gzip;
let debug_str = format!("{:?}", format);
let debug_str = format!("{format:?}");
assert_eq!(debug_str, "Gzip");
let unknown_format = CompressionFormat::Unknown;
let unknown_debug_str = format!("{:?}", unknown_format);
let unknown_debug_str = format!("{unknown_format:?}");
assert_eq!(unknown_debug_str, "Unknown");
}
@@ -419,7 +419,7 @@ mod tests {
for format in supported_formats {
let cursor = Cursor::new(sample_content);
let decoder_result = format.get_decoder(cursor);
assert!(decoder_result.is_ok(), "Format {:?} should create decoder successfully", format);
assert!(decoder_result.is_ok(), "Format {format:?} should create decoder successfully");
}
}
@@ -453,7 +453,7 @@ mod tests {
for format in all_formats {
// Verify each format has corresponding Debug implementation
let _debug_str = format!("{:?}", format);
let _debug_str = format!("{format:?}");
// Verify each format has corresponding PartialEq implementation
assert_eq!(format, format);
@@ -480,9 +480,7 @@ mod tests {
assert_eq!(
CompressionFormat::from_extension(ext),
expected_format,
"Extension '{}' should map to {:?}",
ext,
expected_format
"Extension '{ext}' should map to {expected_format:?}"
);
}
}
@@ -502,7 +500,7 @@ mod tests {
for (format, expected_str) in format_strings {
assert_eq!(
format!("{:?}", format),
format!("{format:?}"),
expected_str,
"Format {:?} should have string representation '{}'",
format,
@@ -531,14 +529,13 @@ mod tests {
// Verify enum size is reasonable
let size = mem::size_of::<CompressionFormat>();
assert!(size <= 8, "CompressionFormat should be memory efficient, got {} bytes", size);
assert!(size <= 8, "CompressionFormat should be memory efficient, got {size} bytes");
// Verify Option<CompressionFormat> size
let option_size = mem::size_of::<Option<CompressionFormat>>();
assert!(
option_size <= 16,
"Option<CompressionFormat> should be efficient, got {} bytes",
option_size
"Option<CompressionFormat> should be efficient, got {option_size} bytes"
);
}
@@ -567,8 +564,7 @@ mod tests {
let is_known = format != CompressionFormat::Unknown;
assert_eq!(
is_known, should_be_known,
"Extension '{}' recognition mismatch: expected {}, got {}",
ext, should_be_known, is_known
"Extension '{ext}' recognition mismatch: expected {should_be_known}, got {is_known}"
);
}
}
@@ -601,7 +597,7 @@ mod tests {
for (format, ext) in consistency_tests {
let parsed_format = CompressionFormat::from_extension(ext);
assert_eq!(parsed_format, format, "Extension '{}' should consistently map to {:?}", ext, format);
assert_eq!(parsed_format, format, "Extension '{ext}' should consistently map to {format:?}");
}
}
@@ -770,7 +766,7 @@ mod tests {
for ext in unknown_extensions {
let format = CompressionFormat::from_extension(ext);
assert_eq!(format, CompressionFormat::Unknown, "Extension '{}' should default to Unknown", ext);
assert_eq!(format, CompressionFormat::Unknown, "Extension '{ext}' should default to Unknown");
}
}
@@ -929,7 +925,7 @@ mod tests {
for level in levels {
// 验证每个级别都有对应的 Debug 实现
let _debug_str = format!("{:?}", level);
let _debug_str = format!("{level:?}");
}
}
@@ -955,7 +951,7 @@ mod tests {
let _supported = format.is_supported();
// 验证 Debug 实现
let _debug = format!("{:?}", format);
let _debug = format!("{format:?}");
}
}
}