use std::time::{Duration, Instant};
use crate::net::{ReadError, Stage, read_capped};
use crate::error::Error;
use crate::pricing::Pricing;
use crate::redaction::body_preview;
pub(crate) const MAX_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
const MSG_MAX: usize = 512;
pub(crate) struct RawResponse {
pub status: http::StatusCode,
pub content_type: Option<String>,
pub body: Vec<u8>,
pub retry_after: Option<Duration>,
pub www_authenticate: Option<String>,
pub x_txid: Option<String>,
pub rate_limit: Option<(u64, u64, u64)>,
}
impl std::fmt::Debug for RawResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RawResponse")
.field("status", &self.status)
.field("content_type", &self.content_type)
.field("body_len", &self.body.len())
.field("retry_after", &self.retry_after)
.field("www_authenticate", &self.www_authenticate)
.field("x_txid", &self.x_txid)
.field("rate_limit", &self.rate_limit)
.finish()
}
}
pub(crate) fn parse_retry_after(raw: &str) -> Option<Duration> {
let raw = raw.trim();
if let Ok(secs) = raw.parse::<u64>() {
return Some(Duration::from_secs(secs));
}
let when = httpdate::parse_http_date(raw).ok()?;
Some(
when.duration_since(std::time::SystemTime::now())
.unwrap_or(Duration::ZERO),
)
}
pub(crate) fn execute_get(
agent: &ureq::Agent,
url: crate::Url,
bearer: &str,
pricing: Pricing,
request_timeout: Duration,
) -> Result<RawResponse, Error> {
let deadline = Instant::now()
.checked_add(request_timeout)
.unwrap_or_else(Instant::now);
let sent = agent
.get(url.as_str())
.header("authorization", &format!("Bearer {bearer}"))
.call();
let mut resp = match sent {
Ok(r) => r,
Err(e) => {
let message = body_preview(&crate::net::redact_ureq_error(&e), MSG_MAX);
return Err(match crate::net::classify(&e) {
Stage::NotSent => Error::TransportNotSent { message, pricing },
Stage::Unknown => Error::TransportUnknown { message, pricing },
});
}
};
let status = resp.status();
let header = |k: &str| {
resp.headers()
.get(k)
.and_then(|v| v.to_str().ok())
.map(str::to_owned)
};
let content_type = header("content-type");
let www_authenticate = header("www-authenticate");
let retry_after = header("retry-after").as_deref().and_then(parse_retry_after);
let x_txid = header("x-txid");
let num = |k: &str| header(k).and_then(|v| v.trim().parse::<u64>().ok());
let rate_limit = match (
num("ratelimit-device-data-per-vehicle-limit"),
num("ratelimit-device-data-per-vehicle-remaining"),
num("ratelimit-device-data-per-vehicle-reset"),
) {
(Some(l), Some(r), Some(rs)) => Some((l, r, rs)),
_ => None,
};
if status.is_redirection() {
return Err(Error::Api {
status,
message: body_preview(
&format!("unexpected redirect ({status}); fleetwire does not follow redirects"),
MSG_MAX,
),
retry_after,
body_preview: String::new(),
pricing,
txid: x_txid,
});
}
let body = match read_capped(
&mut resp.body_mut().as_reader(),
MAX_RESPONSE_BYTES,
deadline,
) {
Ok(body) => body,
Err(ReadError::CapExceeded) => {
return Err(Error::TransportUnknown {
message: body_preview(
&format!("response too large (cap {MAX_RESPONSE_BYTES} bytes)"),
MSG_MAX,
),
pricing,
});
}
Err(ReadError::Deadline) => {
return Err(Error::TransportUnknown {
message: body_preview("request timed out", MSG_MAX),
pricing,
});
}
Err(ReadError::Io(e)) => {
return Err(Error::TransportUnknown {
message: body_preview(&crate::redaction::redact_transport_error(&e), MSG_MAX),
pricing,
});
}
};
Ok(RawResponse {
status,
content_type,
body,
retry_after,
www_authenticate,
x_txid,
rate_limit,
})
}
#[cfg(test)]
mod tests;