From f84cdeb7dbf9e8506fb24e446bf78e2932e0bc1a Mon Sep 17 00:00:00 2001 From: Emmanuel Bosquet Date: Wed, 24 Apr 2024 17:30:51 +0200 Subject: [PATCH 1/2] use std::time instead of crate time --- Cargo.lock | 1 - bin/Cargo.toml | 2 +- command/src/logging/access_logs.rs | 11 ++--- command/src/logging/display.rs | 8 +-- command/src/logging/logs.rs | 1 + lib/src/backends.rs | 5 +- lib/src/http.rs | 16 +++--- lib/src/https.rs | 16 +++--- lib/src/lib.rs | 32 +++++------- lib/src/metrics/mod.rs | 2 +- lib/src/protocol/kawa_h1/mod.rs | 13 ++--- lib/src/protocol/proxy_protocol/expect.rs | 5 +- lib/src/router/mod.rs | 7 ++- lib/src/server.rs | 24 ++++----- lib/src/socket.rs | 5 +- lib/src/tcp.rs | 8 +-- lib/src/timer.rs | 60 +++++++++++++---------- 17 files changed, 100 insertions(+), 116 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 65da4ac15..0cf24f310 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1688,7 +1688,6 @@ dependencies = [ "tempfile", "termion", "thiserror", - "time", ] [[package]] diff --git a/bin/Cargo.toml b/bin/Cargo.toml index d132fdb46..bc042aa5b 100644 --- a/bin/Cargo.toml +++ b/bin/Cargo.toml @@ -30,7 +30,7 @@ paw = "^1.0.0" serde = { version = "^1.0.197", features = ["derive"] } serde_json = "^1.0.116" prost = "^0.12.4" -time = "^0.3.36" +# time = "^0.3.36" tempfile = "^3.10.1" termion = "^3.0.0" thiserror = "^1.0.58" diff --git a/command/src/logging/access_logs.rs b/command/src/logging/access_logs.rs index 42ad85b4c..85231067a 100644 --- a/command/src/logging/access_logs.rs +++ b/command/src/logging/access_logs.rs @@ -1,7 +1,6 @@ -use std::{collections::BTreeMap, mem::ManuallyDrop, net::SocketAddr}; +use std::{collections::BTreeMap, mem::ManuallyDrop, net::SocketAddr, time::Duration}; use rusty_ulid::Ulid; -use time::Duration; use crate::{ logging::{LogLevel, Rfc3339Time}, @@ -160,7 +159,7 @@ impl RequestRecord<'_> { backend_id: self.context.backend_id.duplicate(), bytes_in: self.bytes_in as u64, bytes_out: self.bytes_out as u64, - client_rtt: self.client_rtt.map(|t| t.whole_microseconds() as u64), + client_rtt: self.client_rtt.map(|t| t.as_micros() as u64), cluster_id: self.context.cluster_id.duplicate(), endpoint: ProtobufEndpoint { inner: Some(endpoint), @@ -168,9 +167,9 @@ impl RequestRecord<'_> { message: self.message.duplicate(), protocol: self.protocol.duplicate(), request_id: self.context.request_id.into(), - response_time: self.response_time.whole_microseconds() as u64, - server_rtt: self.server_rtt.map(|t| t.whole_microseconds() as u64), - service_time: self.service_time.whole_microseconds() as u64, + response_time: self.response_time.as_micros() as u64, + server_rtt: self.server_rtt.map(|t| t.as_micros() as u64), + service_time: self.service_time.as_micros() as u64, session_address: self.session_address.map(Into::into), tags: self .tags diff --git a/command/src/logging/display.rs b/command/src/logging/display.rs index 287df6669..3ec1b9fe7 100644 --- a/command/src/logging/display.rs +++ b/command/src/logging/display.rs @@ -77,19 +77,19 @@ impl fmt::Display for LogDuration { match self.0 { None => write!(f, "-"), Some(duration) => { - let secs = duration.whole_seconds(); + let secs = duration.as_secs(); if secs >= 10 { return write!(f, "{secs}s"); } - let ms = duration.whole_milliseconds(); + let ms = duration.as_millis(); if ms < 10 { - let us = duration.whole_microseconds(); + let us = duration.as_millis(); if us >= 10 { return write!(f, "{us}μs"); } - let ns = duration.whole_nanoseconds(); + let ns = duration.as_nanos(); return write!(f, "{ns}ns"); } diff --git a/command/src/logging/logs.rs b/command/src/logging/logs.rs index a63fcaeb6..eb110bfa2 100644 --- a/command/src/logging/logs.rs +++ b/command/src/logging/logs.rs @@ -1007,6 +1007,7 @@ pub struct Rfc3339Time { pub inner: ::time::OffsetDateTime, } +/// yields (Rfc3339Time, unix_epoch) pub fn now() -> (Rfc3339Time, i128) { let t = time::OffsetDateTime::now_utc(); ( diff --git a/lib/src/backends.rs b/lib/src/backends.rs index 1ee7f04a1..96c587efd 100644 --- a/lib/src/backends.rs +++ b/lib/src/backends.rs @@ -1,7 +1,6 @@ -use std::{cell::RefCell, collections::HashMap, net::SocketAddr, rc::Rc}; +use std::{cell::RefCell, collections::HashMap, net::SocketAddr, rc::Rc, time::Duration}; use mio::net::TcpStream; -use time::Duration; use sozu_command::{ proto::command::{Event, EventKind, LoadBalancingAlgorithms, LoadBalancingParams, LoadMetric}, @@ -130,7 +129,7 @@ impl Backend { } pub fn set_connection_time(&mut self, dur: Duration) { - self.connection_time.observe(dur.whole_nanoseconds() as f64); + self.connection_time.observe(dur.as_nanos() as f64); } pub fn peak_ewma_connection(&mut self) -> f64 { diff --git a/lib/src/http.rs b/lib/src/http.rs index 671a2ecb5..716bea2db 100644 --- a/lib/src/http.rs +++ b/lib/src/http.rs @@ -6,6 +6,7 @@ use std::{ os::unix::io::AsRawFd, rc::{Rc, Weak}, str::from_utf8_unchecked, + time::{Duration, Instant}, }; use mio::{ @@ -14,7 +15,6 @@ use mio::{ Interest, Registry, Token, }; use rusty_ulid::Ulid; -use time::{Duration, Instant}; use sozu_command::{ logging::CachedTags, @@ -473,11 +473,7 @@ impl L7ListenerHandler for HttpListener { let now = Instant::now(); if let Route::ClusterId(cluster) = &route { - time!( - "frontend_matching_time", - cluster, - (now - start).whole_milliseconds() - ); + time!("frontend_matching_time", cluster, (now - start).as_millis()); } Ok(route) @@ -921,10 +917,10 @@ impl ProxyConfiguration for HttpProxy { let session = HttpSession::new( owned.answers.clone(), - Duration::seconds(owned.config.back_timeout as i64), - Duration::seconds(owned.config.connect_timeout as i64), - Duration::seconds(owned.config.front_timeout as i64), - Duration::seconds(owned.config.request_timeout as i64), + Duration::from_secs(owned.config.back_timeout as u64), + Duration::from_secs(owned.config.connect_timeout as u64), + Duration::from_secs(owned.config.front_timeout as u64), + Duration::from_secs(owned.config.request_timeout as u64), owned.config.expect_proxy, listener.clone(), Rc::downgrade(&self.pool), diff --git a/lib/src/https.rs b/lib/src/https.rs index dfe20d17f..63ea28a83 100644 --- a/lib/src/https.rs +++ b/lib/src/https.rs @@ -7,6 +7,7 @@ use std::{ rc::{Rc, Weak}, str::{from_utf8, from_utf8_unchecked}, sync::Arc, + time::{Duration, Instant}, }; use mio::{ @@ -32,7 +33,6 @@ use rustls::{ SupportedCipherSuite, }; use rusty_ulid::Ulid; -use time::{Duration, Instant}; use sozu_command::{ certificate::Fingerprint, @@ -607,11 +607,7 @@ impl L7ListenerHandler for HttpsListener { let now = Instant::now(); if let Route::ClusterId(cluster) = &route { - time!( - "frontend_matching_time", - cluster, - (now - start).whole_milliseconds() - ); + time!("frontend_matching_time", cluster, (now - start).as_millis()); } Ok(route) @@ -1232,10 +1228,10 @@ impl ProxyConfiguration for HttpsProxy { let session = Rc::new(RefCell::new(HttpsSession::new( owned.answers.clone(), - Duration::seconds(owned.config.back_timeout as i64), - Duration::seconds(owned.config.connect_timeout as i64), - Duration::seconds(owned.config.front_timeout as i64), - Duration::seconds(owned.config.request_timeout as i64), + Duration::from_secs(owned.config.back_timeout as u64), + Duration::from_secs(owned.config.connect_timeout as u64), + Duration::from_secs(owned.config.front_timeout as u64), + Duration::from_secs(owned.config.request_timeout as u64), owned.config.expect_proxy, listener.clone(), Rc::downgrade(&self.pool), diff --git a/lib/src/lib.rs b/lib/src/lib.rs index 291b30d57..9cd8f4097 100644 --- a/lib/src/lib.rs +++ b/lib/src/lib.rs @@ -343,6 +343,7 @@ use std::{ net::SocketAddr, rc::Rc, str, + time::{Duration, Instant}, }; use backends::BackendError; @@ -351,7 +352,6 @@ use mio::{net::TcpStream, Interest, Token}; use protocol::http::{answers::TemplateError, parser::Method}; use router::RouterError; use socket::ServerBindError; -use time::{Duration, Instant}; use tls::CertificateResolverError; use sozu_command::{ @@ -945,8 +945,8 @@ impl SessionMetrics { pub fn new(wait_time: Option) -> SessionMetrics { SessionMetrics { start: Some(Instant::now()), - service_time: Duration::seconds(0), - wait_time: wait_time.unwrap_or_else(|| Duration::seconds(0)), + service_time: Duration::from_secs(0), + wait_time: wait_time.unwrap_or_else(|| Duration::from_secs(0)), bin: 0, bout: 0, service_start: None, @@ -962,8 +962,8 @@ impl SessionMetrics { pub fn reset(&mut self) { self.start = None; - self.service_time = Duration::seconds(0); - self.wait_time = Duration::seconds(0); + self.service_time = Duration::from_secs(0); + self.wait_time = Duration::from_secs(0); self.bin = 0; self.bout = 0; self.service_start = None; @@ -1009,7 +1009,7 @@ impl SessionMetrics { pub fn response_time(&self) -> Duration { match self.start { Some(start) => Instant::now() - start, - None => Duration::seconds(0), + None => Duration::from_secs(0), } } @@ -1045,26 +1045,18 @@ impl SessionMetrics { let service_time = self.service_time(); if let Some(cluster_id) = context.cluster_id { - time!( - "response_time", - cluster_id, - response_time.whole_milliseconds() - ); - time!( - "service_time", - cluster_id, - service_time.whole_milliseconds() - ); + time!("response_time", cluster_id, response_time.as_millis()); + time!("service_time", cluster_id, service_time.as_millis()); } - time!("response_time", response_time.whole_milliseconds()); - time!("service_time", service_time.whole_milliseconds()); + time!("response_time", response_time.as_millis()); + time!("service_time", service_time.as_millis()); if let Some(backend_id) = self.backend_id.as_ref() { if let Some(backend_response_time) = self.backend_response_time() { record_backend_metrics!( context.cluster_id.as_str_or("-"), backend_id, - backend_response_time.whole_milliseconds(), + backend_response_time.as_millis(), self.backend_connection_time(), self.backend_bin, self.backend_bout @@ -1121,7 +1113,7 @@ impl PeakEWMA { self.rtt = rtt; } else { // new_rtt = old_rtt * e^(-elapsed/decay) + observed_rtt * (1 - e^(-elapsed/decay)) - let weight = (-1.0 * dur.whole_nanoseconds() as f64 / self.decay).exp(); + let weight = (-1.0 * dur.as_nanos() as f64 / self.decay).exp(); self.rtt = self.rtt * weight + rtt * (1.0 - weight); } diff --git a/lib/src/metrics/mod.rs b/lib/src/metrics/mod.rs index e71d143c3..fd1754e9a 100644 --- a/lib/src/metrics/mod.rs +++ b/lib/src/metrics/mod.rs @@ -403,7 +403,7 @@ macro_rules! record_backend_metrics ( m.receive_metric("bytes_out", Some(cluster_id), Some(backend_id), MetricValue::Count($bout as i64)); m.receive_metric("backend_response_time", Some(cluster_id), Some(backend_id), MetricValue::Time($response_time as usize)); if let Some(t) = $backend_connection_time { - m.receive_metric("backend_connection_time", Some(cluster_id), Some(backend_id), MetricValue::Time(t.whole_milliseconds() as usize)); + m.receive_metric("backend_connection_time", Some(cluster_id), Some(backend_id), MetricValue::Time(t.as_millis() as usize)); } m.receive_metric("requests", Some(cluster_id), Some(backend_id), MetricValue::Count(1)); diff --git a/lib/src/protocol/kawa_h1/mod.rs b/lib/src/protocol/kawa_h1/mod.rs index 0444437e7..22e55911b 100644 --- a/lib/src/protocol/kawa_h1/mod.rs +++ b/lib/src/protocol/kawa_h1/mod.rs @@ -8,6 +8,7 @@ use std::{ io::ErrorKind, net::{Shutdown, SocketAddr}, rc::{Rc, Weak}, + time::{Duration, Instant}, }; use mio::{net::TcpStream, Interest, Token}; @@ -17,7 +18,7 @@ use sozu_command::{ logging::EndpointRecord, proto::command::{Event, EventKind, ListenerType}, }; -use time::{Duration, Instant}; +// use time::{Duration, Instant}; use crate::{ backends::{Backend, BackendError}, @@ -1052,7 +1053,7 @@ impl Http { let now = Instant::now(); let dur = now - *stop_instant; - if dur > Duration::seconds(1) { + if dur > Duration::from_secs(1) { return self.test_backend_socket(); } } @@ -1844,7 +1845,7 @@ impl SessionState // we do not have a complete answer TimeoutStatus::Request => { self.set_answer(DefaultAnswer::Answer408 { - duration: self.container_frontend_timeout.duration().to_string(), + duration: self.container_frontend_timeout.duration_fmt(), }); self.writable(metrics) } @@ -1853,7 +1854,7 @@ impl SessionState // this case is ambiguous, as it is the frontend timeout that triggers while we were waiting for response // the timeout responsibility should have switched before self.set_answer(DefaultAnswer::Answer504 { - duration: self.container_backend_timeout.duration().to_string(), + duration: self.container_backend_timeout.duration_fmt(), }); self.writable(metrics) } @@ -1874,13 +1875,13 @@ impl SessionState "got backend timeout while waiting for a request, this should not happen" ); self.set_answer(DefaultAnswer::Answer504 { - duration: self.container_backend_timeout.duration().to_string(), + duration: self.container_backend_timeout.duration_fmt(), }); self.writable(metrics) } TimeoutStatus::WaitingForResponse => { self.set_answer(DefaultAnswer::Answer504 { - duration: self.container_backend_timeout.duration().to_string(), + duration: self.container_backend_timeout.duration_fmt(), }); self.writable(metrics) } diff --git a/lib/src/protocol/proxy_protocol/expect.rs b/lib/src/protocol/proxy_protocol/expect.rs index 1452dba09..031d1cdf9 100644 --- a/lib/src/protocol/proxy_protocol/expect.rs +++ b/lib/src/protocol/proxy_protocol/expect.rs @@ -310,10 +310,9 @@ mod expect_test { net::{IpAddr, Ipv4Addr, SocketAddr}, sync::{Arc, Barrier}, thread::{self, JoinHandle}, + time::Duration, }; - use time::Duration; - use crate::protocol::proxy_protocol::header::*; // Flow diagram of the test below @@ -349,7 +348,7 @@ mod expect_test { } let mut session_metrics = SessionMetrics::new(None); - let container_frontend_timeout = TimeoutContainer::new(Duration::seconds(10), Token(0)); + let container_frontend_timeout = TimeoutContainer::new(Duration::from_secs(10), Token(0)); let mut expect_pp = ExpectProxyProtocol::new( container_frontend_timeout, session_stream, diff --git a/lib/src/router/mod.rs b/lib/src/router/mod.rs index 1001c72a8..acc37e9a6 100644 --- a/lib/src/router/mod.rs +++ b/lib/src/router/mod.rs @@ -1,10 +1,9 @@ pub mod pattern_trie; pub mod trie; -use std::str::from_utf8; +use std::{str::from_utf8, time::Instant}; use regex::bytes::Regex; -use time::Instant; use sozu_command::{ proto::command::{PathRule as CommandPathRule, PathRuleKind, RulePosition}, @@ -441,7 +440,7 @@ impl DomainRule { let start = Instant::now(); let is_a_match = r.is_match(hostname); let now = Instant::now(); - time!("regex_matching_time", (now - start).whole_milliseconds()); + time!("regex_matching_time", (now - start).as_millis()); is_a_match } } @@ -521,7 +520,7 @@ impl PathRule { let start = Instant::now(); let is_a_match = regex.is_match(path); let now = Instant::now(); - time!("regex_matching_time", (now - start).whole_milliseconds()); + time!("regex_matching_time", (now - start).as_millis()); if is_a_match { PathRuleResult::Regex diff --git a/lib/src/server.rs b/lib/src/server.rs index 8e0c3e01c..50879a024 100644 --- a/lib/src/server.rs +++ b/lib/src/server.rs @@ -5,6 +5,7 @@ use std::{ io::Error as IoError, os::unix::io::{AsRawFd, FromRawFd}, rc::Rc, + time::{Duration, Instant}, }; use mio::{ @@ -12,7 +13,6 @@ use mio::{ Events, Interest, Poll, Token, }; use slab::Slab; -use time::{Duration, Instant}; use sozu_command::{ channel::Channel, @@ -374,7 +374,9 @@ impl Server { })); let mut server = Server { - accept_queue_timeout: Duration::seconds(i64::from(server_config.accept_queue_timeout)), + accept_queue_timeout: Duration::from_secs(u64::from( + server_config.accept_queue_timeout, + )), accept_queue: VecDeque::new(), accept_ready: HashSet::new(), backends, @@ -389,7 +391,7 @@ impl Server { last_zombie_check: Instant::now(), // to be reset on server run loop_start: Instant::now(), // to be reset on server run max_poll_errors: 10000, // TODO: make it configurable? - poll_timeout: Some(Duration::milliseconds(1000)), // TODO: make it configurable? + poll_timeout: Some(Duration::from_millis(1000)), // TODO: make it configurable? poll, scm_listeners: None, scm, @@ -397,7 +399,7 @@ impl Server { should_poll_at: None, shutting_down: None, tcp, - zombie_check_interval: Duration::seconds(i64::from( + zombie_check_interval: Duration::from_secs(u64::from( server_config.zombie_check_interval, )), }; @@ -491,10 +493,7 @@ impl Server { } let after_epoll = Instant::now(); - time!( - "epoll_time", - (after_epoll - self.loop_start).whole_milliseconds() - ); + time!("epoll_time", (after_epoll - self.loop_start).as_millis()); self.loop_start = after_epoll; self.send_queue(); @@ -609,10 +608,7 @@ impl Server { fn reset_loop_time_and_get_timeout(&mut self) -> Option { let now = Instant::now(); - time!( - "event_loop_time", - (now - self.loop_start).whole_milliseconds() - ); + time!("event_loop_time", (now - self.loop_start).as_millis()); let timeout = match self.should_poll_at.as_ref() { None => self.poll_timeout, @@ -787,7 +783,7 @@ impl Server { if new_sessions_count < sessions_count { let now = Instant::now(); if let Some(last) = self.last_shutting_down_message { - if (now - last) > Duration::seconds(5) { + if (now - last) > Duration::from_secs(5) { info!( "closed {} sessions, {} sessions left, base_sessions_count = {}", sessions_count - new_sessions_count, @@ -1538,7 +1534,7 @@ impl Server { pub fn create_sessions(&mut self) { while let Some((sock, token, protocol, timestamp)) = self.accept_queue.pop_back() { let wait_time = Instant::now() - timestamp; - time!("accept_queue.wait_time", wait_time.whole_milliseconds()); + time!("accept_queue.wait_time", wait_time.as_millis()); if wait_time > self.accept_queue_timeout { incr!("accept_queue.timeout"); continue; diff --git a/lib/src/socket.rs b/lib/src/socket.rs index afa951dae..1a494264e 100644 --- a/lib/src/socket.rs +++ b/lib/src/socket.rs @@ -496,14 +496,13 @@ pub fn server_bind(addr: SocketAddr) -> Result { /// Socket statistics pub mod stats { - use std::os::fd::AsRawFd; - use time::Duration; + use std::{os::fd::AsRawFd, time::Duration}; use internal::{TcpInfo, OPT_LEVEL, OPT_NAME}; /// Round trip time for a TCP socket pub fn socket_rtt(socket: &A) -> Option { - socket_info(socket.as_raw_fd()).map(|info| Duration::microseconds(info.rtt() as i64)) + socket_info(socket.as_raw_fd()).map(|info| Duration::from_micros(info.rtt() as u64)) } #[cfg(unix)] diff --git a/lib/src/tcp.rs b/lib/src/tcp.rs index 2967e798a..4e4c51209 100644 --- a/lib/src/tcp.rs +++ b/lib/src/tcp.rs @@ -5,6 +5,7 @@ use std::{ net::{Shutdown, SocketAddr}, os::unix::io::AsRawFd, rc::Rc, + time::{Duration, Instant}, }; use mio::{ @@ -12,7 +13,6 @@ use mio::{ Registry, Token, }; use rusty_ulid::Ulid; -use time::{Duration, Instant}; use sozu_command::{ config::MAX_LOOP_ITERATIONS, @@ -815,7 +815,7 @@ impl TcpSession { } let connect_timeout_duration = - Duration::seconds(self.listener.borrow().config.connect_timeout as i64); + Duration::from_secs(self.listener.borrow().config.connect_timeout as u64); self.container_backend_timeout .set_duration(connect_timeout_duration); self.container_backend_timeout.set(back_token); @@ -1408,8 +1408,8 @@ impl ProxyConfiguration for TcpProxy { back_buffer, None, owned.cluster_id.clone(), - Duration::seconds(owned.config.back_timeout as i64), - Duration::seconds(owned.config.front_timeout as i64), + Duration::from_secs(owned.config.back_timeout as u64), + Duration::from_secs(owned.config.front_timeout as u64), front_buffer, frontend_token, listener.clone(), diff --git a/lib/src/timer.rs b/lib/src/timer.rs index fd852a182..0a7e632e1 100644 --- a/lib/src/timer.rs +++ b/lib/src/timer.rs @@ -2,17 +2,20 @@ //! //! code imported from mio-extras //! License: MIT or Apache 2.0 -use std::{cmp, iter, u64, usize}; +use std::{ + cmp, iter, + time::{Duration, Instant}, + u64, usize, +}; use mio::Token; use slab::Slab; -use time::{Duration, Instant}; use crate::server::TIMER; // Conversion utilities mod convert { - use time::Duration; + use std::time::Duration; /// Convert a `Duration` to milliseconds, rounding up and saturating at /// `u64::MAX`. @@ -20,7 +23,7 @@ mod convert { /// The saturating is fine because `u64::MAX` milliseconds are still many /// million years. pub fn millis(duration: Duration) -> u64 { - u64::try_from(duration.whole_milliseconds()).unwrap_or(u64::MAX) + u64::try_from(duration.as_millis()).unwrap_or(u64::MAX) } } @@ -143,6 +146,11 @@ impl TimeoutContainer { self.duration } + /// format timeout duration + pub fn duration_fmt(&self) -> String { + format!("{:?}", self.duration) + } + pub fn cancel(&mut self) -> bool { match self.timeout.take() { None => { @@ -182,7 +190,7 @@ impl TimeoutContainer { impl std::ops::Drop for TimeoutContainer { fn drop(&mut self) { if self.cancel() { - debug!("Cancel a dangling timeout that haven't be handled in session lifecycle, token ({:?}), duration {}", self.token, self.duration); + debug!("Cancel a dangling timeout that haven't be handled in session lifecycle, token ({:?}), duration {}", self.token, self.duration_fmt()); } } } @@ -244,7 +252,7 @@ impl Builder { impl Default for Builder { fn default() -> Builder { Builder { - tick: Duration::milliseconds(100), + tick: Duration::from_millis(100), num_slots: 1 << 8, capacity: 1 << 16, } @@ -468,7 +476,7 @@ impl Timer { pub fn next_poll_date(&self) -> Option { self.next_tick().map(|tick| { - self.start + Duration::milliseconds(self.tick_ms.saturating_mul(tick) as i64) + self.start + Duration::from_millis(self.tick_ms.saturating_mul(tick) as u64) }) } @@ -509,13 +517,13 @@ impl Entry { #[cfg(test)] mod test { use super::*; - use time::{Duration, Instant}; + use std::time::{Duration, Instant}; #[test] pub fn test_timeout_next_tick() { let mut t = timer(); - t.set_timeout_at(Duration::milliseconds(100), "a"); + t.set_timeout_at(Duration::from_millis(100), "a"); let mut tick = ms_to_tick(&t, 50); assert_eq!(None, t.poll_to(tick)); @@ -537,7 +545,7 @@ mod test { pub fn test_clearing_timeout() { let mut t = timer(); - let to = t.set_timeout_at(Duration::milliseconds(100), "a"); + let to = t.set_timeout_at(Duration::from_millis(100), "a"); assert_eq!("a", t.cancel_timeout(&to).unwrap()); let mut tick = ms_to_tick(&t, 100); @@ -553,8 +561,8 @@ mod test { pub fn test_multiple_timeouts_same_tick() { let mut t = timer(); - t.set_timeout_at(Duration::milliseconds(100), "a"); - t.set_timeout_at(Duration::milliseconds(100), "b"); + t.set_timeout_at(Duration::from_millis(100), "a"); + t.set_timeout_at(Duration::from_millis(100), "b"); let mut rcv = vec![]; @@ -577,11 +585,11 @@ mod test { pub fn test_multiple_timeouts_diff_tick() { let mut t = timer(); - t.set_timeout_at(Duration::milliseconds(110), "a"); - t.set_timeout_at(Duration::milliseconds(220), "b"); - t.set_timeout_at(Duration::milliseconds(230), "c"); - t.set_timeout_at(Duration::milliseconds(440), "d"); - t.set_timeout_at(Duration::milliseconds(560), "e"); + t.set_timeout_at(Duration::from_millis(110), "a"); + t.set_timeout_at(Duration::from_millis(220), "b"); + t.set_timeout_at(Duration::from_millis(230), "c"); + t.set_timeout_at(Duration::from_millis(440), "d"); + t.set_timeout_at(Duration::from_millis(560), "e"); let mut tick = ms_to_tick(&t, 100); assert_eq!(Some("a"), t.poll_to(tick)); @@ -611,10 +619,10 @@ mod test { pub fn test_catching_up() { let mut t = timer(); - t.set_timeout_at(Duration::milliseconds(110), "a"); - t.set_timeout_at(Duration::milliseconds(220), "b"); - t.set_timeout_at(Duration::milliseconds(230), "c"); - t.set_timeout_at(Duration::milliseconds(440), "d"); + t.set_timeout_at(Duration::from_millis(110), "a"); + t.set_timeout_at(Duration::from_millis(220), "b"); + t.set_timeout_at(Duration::from_millis(230), "c"); + t.set_timeout_at(Duration::from_millis(440), "d"); let tick = ms_to_tick(&t, 600); assert_eq!(Some("a"), t.poll_to(tick)); @@ -628,9 +636,9 @@ mod test { pub fn test_timeout_hash_collision() { let mut t = timer(); - t.set_timeout_at(Duration::milliseconds(100), "a"); + t.set_timeout_at(Duration::from_millis(100), "a"); t.set_timeout_at( - Duration::milliseconds((100 + TICK * SLOTS as u64) as i64), + Duration::from_millis((100 + TICK * SLOTS as u64) as u64), "b", ); @@ -651,9 +659,9 @@ mod test { pub fn test_clearing_timeout_between_triggers() { let mut t = timer(); - let a = t.set_timeout_at(Duration::milliseconds(100), "a"); - let _ = t.set_timeout_at(Duration::milliseconds(100), "b"); - let _ = t.set_timeout_at(Duration::milliseconds(200), "c"); + let a = t.set_timeout_at(Duration::from_millis(100), "a"); + let _ = t.set_timeout_at(Duration::from_millis(100), "b"); + let _ = t.set_timeout_at(Duration::from_millis(200), "c"); let mut tick = ms_to_tick(&t, 100); assert_eq!(Some("b"), t.poll_to(tick)); From 3816cbf4e03093b82e2cd871ddaf58b9104252c2 Mon Sep 17 00:00:00 2001 From: Emmanuel Bosquet Date: Wed, 24 Apr 2024 17:47:18 +0200 Subject: [PATCH 2/2] apply clippy suggestions --- bin/Cargo.toml | 1 - lib/src/http.rs | 2 +- lib/src/https.rs | 2 +- lib/src/protocol/kawa_h1/answers.rs | 2 +- lib/src/protocol/kawa_h1/diagnostics.rs | 11 ++++------- lib/src/protocol/kawa_h1/mod.rs | 10 +++++----- lib/src/server.rs | 4 ++-- lib/src/tcp.rs | 2 +- lib/src/timer.rs | 22 ++++++++++++---------- 9 files changed, 27 insertions(+), 29 deletions(-) diff --git a/bin/Cargo.toml b/bin/Cargo.toml index bc042aa5b..a43e3cf94 100644 --- a/bin/Cargo.toml +++ b/bin/Cargo.toml @@ -30,7 +30,6 @@ paw = "^1.0.0" serde = { version = "^1.0.197", features = ["derive"] } serde_json = "^1.0.116" prost = "^0.12.4" -# time = "^0.3.36" tempfile = "^3.10.1" termion = "^3.0.0" thiserror = "^1.0.58" diff --git a/lib/src/http.rs b/lib/src/http.rs index 716bea2db..b1be32ec9 100644 --- a/lib/src/http.rs +++ b/lib/src/http.rs @@ -580,7 +580,7 @@ impl HttpProxy { .listeners .values() .find(|listener| listener.borrow().address == address) - .ok_or(ProxyError::NoListenerFound(address.clone()))?; + .ok_or(ProxyError::NoListenerFound(address))?; let mut owned = listener.borrow_mut(); diff --git a/lib/src/https.rs b/lib/src/https.rs index 63ea28a83..abe29af4a 100644 --- a/lib/src/https.rs +++ b/lib/src/https.rs @@ -987,7 +987,7 @@ impl HttpsProxy { .listeners .values() .find(|listener| listener.borrow().address == address) - .ok_or(ProxyError::NoListenerFound(address.clone()))?; + .ok_or(ProxyError::NoListenerFound(address))?; let mut owned = listener.borrow_mut(); diff --git a/lib/src/protocol/kawa_h1/answers.rs b/lib/src/protocol/kawa_h1/answers.rs index 6c4ab2056..f589a972a 100644 --- a/lib/src/protocol/kawa_h1/answers.rs +++ b/lib/src/protocol/kawa_h1/answers.rs @@ -114,7 +114,7 @@ impl Template { .collect::>(); let answer = answer .replace("\r\n", "\n") - .replace("\n", "\r\n") + .replace('\n', "\r\n") .into_bytes(); let len = answer.len(); diff --git a/lib/src/protocol/kawa_h1/diagnostics.rs b/lib/src/protocol/kawa_h1/diagnostics.rs index 3cb787748..be9fcd431 100644 --- a/lib/src/protocol/kawa_h1/diagnostics.rs +++ b/lib/src/protocol/kawa_h1/diagnostics.rs @@ -16,11 +16,7 @@ fn hex_dump(buffer: &[u8], window: usize, start: usize, end: usize) -> String { for c in slice { let _ = write!(result, " {c:02x}"); } - result.push_str( - &std::iter::repeat(' ') - .take((window + start - end) * 3 + 4) - .collect::(), - ); + result.push_str(&" ".repeat((window + start - end) * 3 + 4)); result.push_str(&String::from_utf8_lossy(slice).escape_debug().to_string()); } else { let slice1 = &buffer[start..start + window - 1]; @@ -112,10 +108,11 @@ Invalid: pub fn diagnostic_413_507(parsing_phase: ParsingPhase) -> String { match parsing_phase { kawa::ParsingPhase::StatusLine => { - format!("Request line is too long. Note that an URL should not exceed 2083 characters.") + "Request line is too long. Note that an URL should not exceed 2083 characters." + .to_string() } kawa::ParsingPhase::Headers | kawa::ParsingPhase::Cookies { .. } => { - format!("Headers are too long. All headers should fit in a single buffer.") + "Headers are too long. All headers should fit in a single buffer.".to_string() } phase => format!("Unexpected parsing phase: {phase:?}"), } diff --git a/lib/src/protocol/kawa_h1/mod.rs b/lib/src/protocol/kawa_h1/mod.rs index 22e55911b..abceb7715 100644 --- a/lib/src/protocol/kawa_h1/mod.rs +++ b/lib/src/protocol/kawa_h1/mod.rs @@ -1212,7 +1212,7 @@ impl Http SessionState // we do not have a complete answer TimeoutStatus::Request => { self.set_answer(DefaultAnswer::Answer408 { - duration: self.container_frontend_timeout.duration_fmt(), + duration: self.container_frontend_timeout.to_string(), }); self.writable(metrics) } @@ -1854,7 +1854,7 @@ impl SessionState // this case is ambiguous, as it is the frontend timeout that triggers while we were waiting for response // the timeout responsibility should have switched before self.set_answer(DefaultAnswer::Answer504 { - duration: self.container_backend_timeout.duration_fmt(), + duration: self.container_backend_timeout.to_string(), }); self.writable(metrics) } @@ -1875,13 +1875,13 @@ impl SessionState "got backend timeout while waiting for a request, this should not happen" ); self.set_answer(DefaultAnswer::Answer504 { - duration: self.container_backend_timeout.duration_fmt(), + duration: self.container_backend_timeout.to_string(), }); self.writable(metrics) } TimeoutStatus::WaitingForResponse => { self.set_answer(DefaultAnswer::Answer504 { - duration: self.container_backend_timeout.duration_fmt(), + duration: self.container_backend_timeout.to_string(), }); self.writable(metrics) } diff --git a/lib/src/server.rs b/lib/src/server.rs index 50879a024..5a1d1488e 100644 --- a/lib/src/server.rs +++ b/lib/src/server.rs @@ -606,7 +606,7 @@ impl Server { } } - fn reset_loop_time_and_get_timeout(&mut self) -> Option { + fn reset_loop_time_and_get_timeout(&mut self) -> Option { let now = Instant::now(); time!("event_loop_time", (now - self.loop_start).as_millis()); @@ -632,7 +632,7 @@ impl Server { }; self.loop_start = now; - timeout.and_then(|t| std::time::Duration::try_from(t).ok()) + timeout } /// Returns true if hardstop diff --git a/lib/src/tcp.rs b/lib/src/tcp.rs index 4e4c51209..669b6d5fc 100644 --- a/lib/src/tcp.rs +++ b/lib/src/tcp.rs @@ -1064,7 +1064,7 @@ impl TcpListener { registry .register(&mut listener, self.token, Interest::READABLE) - .map_err(|io_err| ProxyError::RegisterListener(io_err))?; + .map_err(ProxyError::RegisterListener)?; self.listener = Some(listener); self.active = true; diff --git a/lib/src/timer.rs b/lib/src/timer.rs index 0a7e632e1..9d9b98521 100644 --- a/lib/src/timer.rs +++ b/lib/src/timer.rs @@ -3,7 +3,9 @@ //! code imported from mio-extras //! License: MIT or Apache 2.0 use std::{ - cmp, iter, + cmp, + fmt::Display, + iter, time::{Duration, Instant}, u64, usize, }; @@ -146,11 +148,6 @@ impl TimeoutContainer { self.duration } - /// format timeout duration - pub fn duration_fmt(&self) -> String { - format!("{:?}", self.duration) - } - pub fn cancel(&mut self) -> bool { match self.timeout.take() { None => { @@ -187,10 +184,16 @@ impl TimeoutContainer { } } +impl Display for TimeoutContainer { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self.duration) + } +} + impl std::ops::Drop for TimeoutContainer { fn drop(&mut self) { if self.cancel() { - debug!("Cancel a dangling timeout that haven't be handled in session lifecycle, token ({:?}), duration {}", self.token, self.duration_fmt()); + debug!("Cancel a dangling timeout that haven't be handled in session lifecycle, token ({:?}), duration {}", self.token, self); } } } @@ -475,9 +478,8 @@ impl Timer { } pub fn next_poll_date(&self) -> Option { - self.next_tick().map(|tick| { - self.start + Duration::from_millis(self.tick_ms.saturating_mul(tick) as u64) - }) + self.next_tick() + .map(|tick| self.start + Duration::from_millis(self.tick_ms.saturating_mul(tick))) } fn slot_for(&self, tick: Tick) -> usize {