use std::io::{self, Read as _, Write};
use std::thread;
use std::time::Duration;
use serde::de::DeserializeOwned;
use sha2::{Digest as _, Sha256};
use stratum_node_core::{NostrSecretKey, Sha256Digest};
use crate::client::{self, MAX_RESPONSE_BYTES};
use crate::error::CliError;
use crate::origin::GateTarget;
use crate::output::{sanitize, Output};
use crate::redact;
use crate::wire::ErrorEnvelope;
const USER_AGENT: &str = concat!("stratum/", env!("CARGO_PKG_VERSION"));
pub(crate) const JSON: &str = "application/json";
pub(crate) const LD_JSON: &str = "application/ld+json";
pub(crate) const ANY: &str = "*/*";
pub(crate) const MAX_RESOURCE_BYTES: u64 = 1024 * 1024 * 1024;
pub(crate) const MAX_LISTING_BYTES: u64 = 64 * 1024 * 1024;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const RESPONSE_TIMEOUT: Duration = Duration::from_secs(60);
const BODY_TIMEOUT: Duration = Duration::from_secs(600);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Route {
Admission,
Pod,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Precondition<'a> {
None,
IfMatch(&'a str),
CreateOnly,
}
#[derive(Debug, Clone, Default)]
pub(crate) struct Head {
pub(crate) status: u16,
pub(crate) content_type: Option<String>,
pub(crate) etag: Option<String>,
pub(crate) retry_after: Option<String>,
}
impl Head {
pub(crate) fn is_success(&self) -> bool {
(200..300).contains(&self.status)
}
pub(crate) fn is_redirect(&self) -> bool {
(300..400).contains(&self.status)
}
}
#[derive(Debug)]
pub(crate) struct Buffered {
pub(crate) head: Head,
pub(crate) body: Vec<u8>,
}
impl Buffered {
pub(crate) fn into_json<T: DeserializeOwned>(
self,
route: Route,
) -> Result<(T, serde_json::Value), CliError> {
if !self.head.is_success() {
return Err(self.into_error(route));
}
let value: serde_json::Value = serde_json::from_slice(&self.body).map_err(|_| {
CliError::Protocol(format!(
"HTTP {} with a body that is not JSON",
self.head.status
))
})?;
let typed = T::deserialize(&value).map_err(|err| {
CliError::Protocol(format!(
"HTTP {} body does not match the API contract: {}",
self.head.status,
sanitize(&err.to_string())
))
})?;
Ok((typed, value))
}
pub(crate) fn into_error(self, route: Route) -> CliError {
error_from(&self.head, &self.body, route)
}
}
pub(crate) fn error_from(head: &Head, body: &[u8], route: Route) -> CliError {
let retry = head
.retry_after
.as_deref()
.map(|value| format!(" (retry after {})", sanitize(value)))
.unwrap_or_default();
if let Ok(envelope) = serde_json::from_slice::<ErrorEnvelope>(body) {
let details = envelope
.error
.errors
.iter()
.chain(&envelope.errors)
.map(|entry| match &entry.path {
Some(path) => sanitize(&format!("{path}: {}", entry.message)),
None => sanitize(&entry.message),
})
.collect();
return CliError::Server {
status: head.status,
code: sanitize(&envelope.error.code),
message: format!("{}{retry}", sanitize(&envelope.error.message)),
details,
};
}
match route {
Route::Admission => {
CliError::Protocol(format!("HTTP {} without the error envelope", head.status))
}
Route::Pod => CliError::Server {
status: head.status,
code: code_for_status(head.status),
message: format!("HTTP {} from the pod server{retry}", head.status),
details: Vec::new(),
},
}
}
fn code_for_status(status: u16) -> String {
match status {
400 => "bad_request",
401 => "unauthorized",
403 => "forbidden",
404 => "not_found",
405 => "method_not_allowed",
408 => "request_timeout",
409 => "conflict",
412 => "precondition_failed",
413 => "payload_too_large",
415 => "unsupported_media_type",
421 => "misdirected_request",
429 => "too_many_requests",
500 => "internal",
502 => "bad_gateway",
504 => "gateway_timeout",
507 => "insufficient_storage",
other => return format!("http_{other}"),
}
.to_owned()
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Streamed {
pub(crate) size: u64,
pub(crate) sha256: Sha256Digest,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Request<'a> {
pub(crate) method: &'a str,
pub(crate) path: &'a str,
pub(crate) accept: &'a str,
pub(crate) body: Option<(&'a [u8], &'a str)>,
pub(crate) precondition: Precondition<'a>,
}
impl<'a> Request<'a> {
pub(crate) fn new(method: &'a str, path: &'a str, accept: &'a str) -> Self {
Self {
method,
path,
accept,
body: None,
precondition: Precondition::None,
}
}
pub(crate) fn with_body(mut self, body: &'a [u8], content_type: &'a str) -> Self {
self.body = Some((body, content_type));
self
}
pub(crate) fn with_precondition(mut self, precondition: Precondition<'a>) -> Self {
self.precondition = precondition;
self
}
}
#[derive(Debug)]
pub(crate) struct GateClient {
target: GateTarget,
agent: ureq::Agent,
busy: Option<BusyRetries>,
}
#[derive(Debug, Clone, Copy)]
struct BusyRetries {
attempts: u32,
output: Output,
}
pub(crate) const BUSY_RETRIES: u32 = 3;
const MAX_RETRY_DELAY: Duration = Duration::from_secs(30);
const DATE_RETRY_DELAY: Duration = Duration::from_secs(5);
impl GateClient {
pub(crate) fn new(target: GateTarget) -> Self {
let config = ureq::Agent::config_builder()
.proxy(None)
.max_redirects(0)
.http_status_as_error(false)
.https_only(false)
.user_agent(USER_AGENT)
.accept(ureq::config::AutoHeaderValue::None)
.accept_encoding(ureq::config::AutoHeaderValue::None)
.timeout_connect(Some(CONNECT_TIMEOUT))
.timeout_recv_response(Some(RESPONSE_TIMEOUT))
.timeout_send_body(Some(BODY_TIMEOUT))
.timeout_recv_body(Some(BODY_TIMEOUT))
.max_idle_connections(0)
.build();
Self {
target,
agent: ureq::Agent::new_with_config(config),
busy: None,
}
}
pub(crate) fn with_busy_retries(mut self, output: Output) -> Self {
self.busy = Some(BusyRetries {
attempts: BUSY_RETRIES,
output,
});
self
}
fn retry_delay(&self, head: &Head, attempt: u32) -> Result<Option<Duration>, CliError> {
let Some(busy) = self.busy else {
return Ok(None);
};
if head.status != 503 || attempt >= busy.attempts {
return Ok(None);
}
let Some(value) = head.retry_after.as_deref() else {
return Ok(None);
};
let delay = value
.trim()
.parse::<u64>()
.map_or(DATE_RETRY_DELAY, Duration::from_secs)
.min(MAX_RETRY_DELAY);
busy.output.note(&format!(
"the gate is busy (503); retrying in {} s, signed afresh (retry {} of {})",
delay.as_secs(),
attempt + 1,
busy.attempts
))?;
Ok(Some(delay))
}
pub(crate) fn target(&self) -> &GateTarget {
&self.target
}
pub(crate) fn url(&self, path: &str) -> String {
self.target.origin().url(path)
}
pub(crate) fn sign(
&self,
key: &NostrSecretKey,
request: &Request<'_>,
) -> Result<String, CliError> {
let url = self.url(request.path);
let authorization = client::sign(
key,
request.method,
&url,
request.body.map(|(bytes, _)| bytes),
)?;
redact::register_text_secret(&authorization);
Ok(authorization)
}
pub(crate) fn fetch(
&self,
request: &Request<'_>,
key: Option<&NostrSecretKey>,
limit: u64,
) -> Result<Buffered, CliError> {
let mut attempt = 0;
loop {
let authorization = match key {
Some(key) => Some(self.sign(key, request)?),
None => None,
};
let response = self.fetch_with(request, authorization.as_deref(), limit)?;
match self.retry_delay(&response.head, attempt)? {
Some(delay) => {
thread::sleep(delay);
attempt += 1;
}
None => return Ok(response),
}
}
}
pub(crate) fn fetch_with(
&self,
request: &Request<'_>,
authorization: Option<&str>,
limit: u64,
) -> Result<Buffered, CliError> {
let url = self.url(request.path);
let mut response = self.send(request, authorization)?;
let head = head_of(&response);
let mut body = Vec::new();
copy_capped(&mut response, &url, &mut body, limit)?;
Ok(Buffered { head, body })
}
pub(crate) fn stream(
&self,
request: &Request<'_>,
key: &NostrSecretKey,
sink: &mut dyn Write,
limit: u64,
) -> Result<(Head, Result<Streamed, Vec<u8>>), CliError> {
let url = self.url(request.path);
let mut attempt = 0;
loop {
let authorization = self.sign(key, request)?;
let mut response = self.send(request, Some(&authorization))?;
let head = head_of(&response);
if head.is_success() {
let streamed = copy_capped(&mut response, &url, sink, limit)?;
return Ok((head, Ok(streamed)));
}
let mut body = Vec::new();
copy_capped(&mut response, &url, &mut body, MAX_RESPONSE_BYTES)?;
match self.retry_delay(&head, attempt)? {
Some(delay) => {
thread::sleep(delay);
attempt += 1;
}
None => return Ok((head, Err(body))),
}
}
}
fn send(
&self,
request: &Request<'_>,
authorization: Option<&str>,
) -> Result<ureq::http::Response<ureq::Body>, CliError> {
let url = self.url(request.path);
let connect = format!(
"http://{}:{}{}",
self.target.connect().connect_host(),
self.target.connect().port(),
request.path
);
let builder = ureq::http::Request::builder()
.method(request.method)
.uri(&connect)
.header("Host", self.target.origin().authority())
.header("Accept", request.accept);
let builder = match authorization {
Some(value) => builder.header("Authorization", value),
None => builder,
};
let builder = match request.precondition {
Precondition::None => builder,
Precondition::IfMatch(etag) => builder.header("If-Match", etag),
Precondition::CreateOnly => builder.header("If-None-Match", "*"),
};
let result = if let Some((bytes, content_type)) = request.body {
let built = builder
.header("Content-Type", content_type)
.body(bytes)
.map_err(|err| CliError::Local(format!("building the request failed: {err}")))?;
self.agent.run(built)
} else {
let built = builder
.body(())
.map_err(|err| CliError::Local(format!("building the request failed: {err}")))?;
self.agent.run(built)
};
result.map_err(|err| transport_error(&url, &err))
}
}
fn head_of(response: &ureq::http::Response<ureq::Body>) -> Head {
let header = |name: &str| {
response
.headers()
.get(name)
.and_then(|value| value.to_str().ok())
.map(str::to_owned)
};
Head {
status: response.status().as_u16(),
content_type: header("content-type"),
etag: header("etag"),
retry_after: header("retry-after"),
}
}
fn copy_capped(
response: &mut ureq::http::Response<ureq::Body>,
url: &str,
sink: &mut dyn Write,
limit: u64,
) -> Result<Streamed, CliError> {
let mut reader = response.body_mut().with_config().limit(u64::MAX).reader();
let mut hasher = Sha256::new();
let mut size: u64 = 0;
let mut buffer = vec![0u8; 64 * 1024];
loop {
let read = match reader.read(&mut buffer) {
Ok(0) => break,
Ok(read) => read,
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
Err(err) => return Err(body_error(url, &err, limit)),
};
size = size.saturating_add(u64::try_from(read).unwrap_or(u64::MAX));
if size > limit {
return Err(CliError::Protocol(format!(
"response body is larger than {limit} bytes"
)));
}
let chunk = &buffer[..read];
hasher.update(chunk);
sink.write_all(chunk)
.map_err(|err| CliError::Local(format!("writing the response body failed: {err}")))?;
}
let digest: [u8; 32] = hasher.finalize().into();
Ok(Streamed {
size,
sha256: Sha256Digest::from_bytes(digest),
})
}
fn body_error(url: &str, err: &io::Error, limit: u64) -> CliError {
let text = err.to_string();
if text.contains("limit") {
return CliError::Protocol(format!("response body is larger than {limit} bytes"));
}
CliError::Unreachable {
url: url.to_owned(),
message: format!("reading the response failed: {}", err.kind()),
}
}
fn transport_error(url: &str, err: &ureq::Error) -> CliError {
let message = match err {
ureq::Error::Timeout(_) => "timed out".to_owned(),
ureq::Error::ConnectionFailed => "connection failed".to_owned(),
ureq::Error::HostNotFound => "host not found".to_owned(),
ureq::Error::Io(io) => io.kind().to_string(),
ureq::Error::Protocol(_) => "the connection closed without a valid response".to_owned(),
other => return CliError::Protocol(sanitize(&other.to_string())),
};
CliError::Unreachable {
url: url.to_owned(),
message,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bare_statuses_are_named_on_pod_routes_only() {
let head = Head {
status: 412,
..Head::default()
};
let err = error_from(&head, b"precondition failed", Route::Pod);
assert_eq!(err.code(), "precondition_failed");
let err = error_from(&head, b"precondition failed", Route::Admission);
assert_eq!(err.code(), "protocol");
let head = Head {
status: 503,
retry_after: Some("5".to_owned()),
..Head::default()
};
let err = error_from(
&head,
br#"{"error":{"code":"gate_unavailable","message":"paused"}}"#,
Route::Pod,
);
assert_eq!(err.code(), "gate_unavailable");
assert_eq!(err.to_string(), "gate_unavailable: paused (retry after 5)");
}
}