use std::error::Error;
use std::fmt;
use std::time::{Duration, SystemTime};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Signal {
Errors,
Logs,
Traces,
}
impl Signal {
pub fn path(self) -> &'static str {
match self {
Self::Errors => "/v1/errors",
Self::Logs => "/v1/logs",
Self::Traces => "/v1/traces",
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Request {
pub signal: Signal,
pub url: String,
pub headers: Vec<(&'static str, String)>,
pub body: Vec<u8>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[must_use]
pub struct Response {
pub status: u16,
pub retry_after: Option<Duration>,
pub body: Vec<u8>,
}
impl Response {
pub fn new(status: u16) -> Self {
Self {
status,
retry_after: None,
body: Vec::new(),
}
}
pub fn with_retry_after_header(mut self, value: &str) -> Self {
self.retry_after = parse_retry_after(value);
self
}
pub fn with_body<B: Into<Vec<u8>>>(mut self, body: B) -> Self {
self.body = body.into();
self
}
}
fn parse_retry_after(value: &str) -> Option<Duration> {
let value = value.trim();
if let Ok(seconds) = value.parse::<u64>() {
return Some(Duration::from_secs(seconds));
}
let date = httpdate::parse_http_date(value).ok()?;
Some(date.duration_since(SystemTime::now()).unwrap_or_default())
}
pub trait Transport: Send + Sync + fmt::Debug + 'static {
fn send(&self, request: &Request) -> Result<Response, TransportError>;
}
#[derive(Debug)]
pub struct TransportError {
error: Box<dyn Error + Send + Sync>,
}
impl TransportError {
pub fn new<E: Into<Box<dyn Error + Send + Sync>>>(error: E) -> Self {
Self {
error: error.into(),
}
}
}
impl fmt::Display for TransportError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.error, f)
}
}
impl Error for TransportError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.error.source()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn retry_after_in_seconds() {
assert_eq!(parse_retry_after("60"), Some(Duration::from_secs(60)));
}
#[test]
fn retry_after_ignores_whitespace() {
assert_eq!(parse_retry_after(" 5 "), Some(Duration::from_secs(5)));
}
#[test]
fn retry_after_as_http_date() {
let in_two_minutes = SystemTime::now() + Duration::from_secs(120);
let header = httpdate::fmt_http_date(in_two_minutes);
let wait = parse_retry_after(&header).unwrap();
assert!(wait > Duration::from_secs(110) && wait <= Duration::from_secs(120));
}
#[test]
fn retry_after_in_the_past_means_no_wait() {
assert_eq!(
parse_retry_after("Wed, 21 Oct 2015 07:28:00 GMT"),
Some(Duration::ZERO)
);
}
#[test]
fn invalid_retry_after_is_ignored() {
assert_eq!(parse_retry_after("soon"), None);
}
#[test]
fn transport_errors_show_the_message_of_the_wrapped_error() {
let error = TransportError::new("connection refused");
assert_eq!(error.to_string(), "connection refused");
}
#[derive(Debug)]
struct ConnectError(std::io::Error);
impl fmt::Display for ConnectError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("could not connect")
}
}
impl Error for ConnectError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&self.0)
}
}
#[test]
fn transport_errors_return_the_cause_of_the_wrapped_error() {
let error = TransportError::new(ConnectError(std::io::Error::other("connection refused")));
assert_eq!(
error.source().map(ToString::to_string),
Some("connection refused".to_owned())
);
}
}