rustflexstack/security/pki_client/
transport.rs1use std::fmt;
13use std::sync::Arc;
14use std::time::Duration;
15
16use crate::security::pki_client::client::PkiClock;
17
18#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct PkiTransportError(pub String);
21
22impl fmt::Display for PkiTransportError {
23 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24 f.write_str(&self.0)
25 }
26}
27
28impl std::error::Error for PkiTransportError {}
29
30pub trait PkiTransport: Send + Sync {
32 fn post(
34 &self,
35 url: &str,
36 body: &[u8],
37 content_type: &str,
38 ) -> Result<Vec<u8>, PkiTransportError>;
39 fn get(&self, url: &str) -> Result<Vec<u8>, PkiTransportError>;
41}
42
43#[derive(Debug, Clone)]
45pub struct HttpTransport {
46 pub timeout: Duration,
47}
48
49impl HttpTransport {
50 pub fn new(timeout: Duration) -> Self {
51 Self { timeout }
52 }
53}
54
55impl Default for HttpTransport {
56 fn default() -> Self {
57 Self::new(Duration::from_secs(30))
58 }
59}
60
61fn read(
62 response: Result<ureq::Response, ureq::Error>,
63 what: &str,
64) -> Result<Vec<u8>, PkiTransportError> {
65 match response {
66 Ok(r) => {
67 let mut body = Vec::new();
68 std::io::Read::read_to_end(&mut r.into_reader(), &mut body)
69 .map_err(|e| PkiTransportError(format!("{what}: {e}")))?;
70 Ok(body)
71 }
72 Err(ureq::Error::Status(code, _)) => Err(PkiTransportError(format!("{what}: HTTP {code}"))),
73 Err(e) => Err(PkiTransportError(format!("{what}: {e}"))),
74 }
75}
76
77impl PkiTransport for HttpTransport {
78 fn post(
79 &self,
80 url: &str,
81 body: &[u8],
82 content_type: &str,
83 ) -> Result<Vec<u8>, PkiTransportError> {
84 read(
85 ureq::post(url)
86 .timeout(self.timeout)
87 .set("Content-Type", content_type)
88 .send_bytes(body),
89 &format!("POST {url}"),
90 )
91 }
92
93 fn get(&self, url: &str) -> Result<Vec<u8>, PkiTransportError> {
94 read(
95 ureq::get(url).timeout(self.timeout).call(),
96 &format!("GET {url}"),
97 )
98 }
99}
100
101pub type PkiSleep = Arc<dyn Fn(f64) + Send + Sync>;
103
104#[derive(Debug, Clone, Copy, PartialEq)]
110pub struct RetryPolicy {
111 pub th1: f64,
112 pub n1: u32,
113 pub th2: f64,
114}
115
116impl Default for RetryPolicy {
117 fn default() -> Self {
118 Self {
119 th1: 30.0,
120 n1: 3,
121 th2: 3600.0,
122 }
123 }
124}
125
126#[derive(Clone)]
128pub struct Retry {
129 pub policy: RetryPolicy,
130 pub clock: PkiClock,
131 pub sleep: PkiSleep,
132}
133
134pub fn post_with_retry(
139 transport: &dyn PkiTransport,
140 url: &str,
141 body: &[u8],
142 content_type: &str,
143 retry: Option<&Retry>,
144) -> Result<Vec<u8>, PkiTransportError> {
145 let Some(retry) = retry else {
146 return transport.post(url, body, content_type);
147 };
148 let policy = retry.policy;
149 let first = (retry.clock)();
150 for attempt in 1..=policy.n1 {
151 let sent = (retry.clock)();
152 if let Ok(response) = transport.post(url, body, content_type) {
153 return Ok(response);
154 }
155 let resend = sent + policy.th1;
156 if attempt == policy.n1 || resend >= first + policy.th2 {
157 return Err(PkiTransportError(format!(
158 "POST {url}: no response after {attempt} transmissions"
159 )));
160 }
161 (retry.sleep)((resend - (retry.clock)()).max(0.0));
162 }
163 Err(PkiTransportError(format!(
164 "POST {url}: no transmission allowed (n1 = {})",
165 policy.n1
166 )))
167}