Skip to content

Commit

Permalink
Merge pull request #1102 from sozu-proxy/use-std-time
Browse files Browse the repository at this point in the history
Use std::time instead of crate time where possible
  • Loading branch information
FlorentinDUBOIS authored Apr 29, 2024
2 parents 5ce5c5a + 3816cbf commit 34d8b93
Show file tree
Hide file tree
Showing 19 changed files with 114 additions and 132 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion bin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
11 changes: 5 additions & 6 deletions command/src/logging/access_logs.rs
Original file line number Diff line number Diff line change
@@ -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},
Expand Down Expand Up @@ -160,17 +159,17 @@ 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),
},
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
Expand Down
8 changes: 4 additions & 4 deletions command/src/logging/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}

Expand Down
1 change: 1 addition & 0 deletions command/src/logging/logs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
(
Expand Down
5 changes: 2 additions & 3 deletions lib/src/backends.rs
Original file line number Diff line number Diff line change
@@ -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},
Expand Down Expand Up @@ -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 {
Expand Down
18 changes: 7 additions & 11 deletions lib/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::{
os::unix::io::AsRawFd,
rc::{Rc, Weak},
str::from_utf8_unchecked,
time::{Duration, Instant},
};

use mio::{
Expand All @@ -14,7 +15,6 @@ use mio::{
Interest, Registry, Token,
};
use rusty_ulid::Ulid;
use time::{Duration, Instant};

use sozu_command::{
logging::CachedTags,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -584,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();

Expand Down Expand Up @@ -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),
Expand Down
18 changes: 7 additions & 11 deletions lib/src/https.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::{
rc::{Rc, Weak},
str::{from_utf8, from_utf8_unchecked},
sync::Arc,
time::{Duration, Instant},
};

use mio::{
Expand All @@ -32,7 +33,6 @@ use rustls::{
SupportedCipherSuite,
};
use rusty_ulid::Ulid;
use time::{Duration, Instant};

use sozu_command::{
certificate::Fingerprint,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -991,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();

Expand Down Expand Up @@ -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),
Expand Down
32 changes: 12 additions & 20 deletions lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,7 @@ use std::{
net::SocketAddr,
rc::Rc,
str,
time::{Duration, Instant},
};

use backends::BackendError;
Expand All @@ -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::{
Expand Down Expand Up @@ -945,8 +945,8 @@ impl SessionMetrics {
pub fn new(wait_time: Option<Duration>) -> 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,
Expand All @@ -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;
Expand Down Expand Up @@ -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),
}
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
}

Expand Down
2 changes: 1 addition & 1 deletion lib/src/metrics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
2 changes: 1 addition & 1 deletion lib/src/protocol/kawa_h1/answers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ impl Template {
.collect::<Vec<_>>();
let answer = answer
.replace("\r\n", "\n")
.replace("\n", "\r\n")
.replace('\n', "\r\n")
.into_bytes();

let len = answer.len();
Expand Down
11 changes: 4 additions & 7 deletions lib/src/protocol/kawa_h1/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<String>(),
);
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];
Expand Down Expand Up @@ -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:?}"),
}
Expand Down
Loading

0 comments on commit 34d8b93

Please sign in to comment.