1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: AGPL-3.0-or-later
3 // There is NO WARRANTY.
5 use hippotat::prelude::*;
6 use hippotat_macros::into_crlfs;
8 type OutstandingRequest<'r> = Pin<Box<
9 dyn Future<Output=Option<Bytes>> + Send + 'r
12 impl<T> HCC for T where
13 T: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
14 trait HCC: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
16 struct ClientContext<'c,C> {
17 ic: &'c InstanceConfig,
18 hclient: &'c Arc<hyper::Client<C>>,
19 reporter: &'c parking_lot::Mutex<Reporter<'c>>,
23 fn submit_request<'r, 'c:'r, C:HCC>(
24 c: &'c ClientContext<C>,
25 reqs: &mut Vec<OutstandingRequest<'r>>,
28 let show_timeout = c.ic.http_timeout
29 .saturating_add(Duration::from_nanos(999_999_999))
32 let prefix = format!(into_crlfs!(
34 Content-Type: text/plain; charset="utf-8"
35 Content-Disposition: form-data; name="m"
42 "xxx token goes here",
43 c.ic.target_requests_outstanding,
47 let prefix2 = format!(into_crlfs!(
50 Content-Type: application/octet-stream
51 Content-Disposition: form-data; name="d"
55 let suffix = format!(into_crlfs!(
60 eprintln!(">{}[{}D]{}<", &prefix, &prefix2, &suffix);
62 let body = hyper::body::Body::wrap_stream(
63 futures::stream::iter(
64 Itertools::intersperse(
65 upbound.into_iter().map(|u| Bytes::from(u)),
71 let req = hyper::Request::post(&c.ic.url).body(body)
72 .context("construct request")?;
74 let resp = c.hclient.request(req);
75 let fut = Box::pin(async move {
76 let r = async { tokio::time::timeout( c.ic.http_timeout, async {
77 let resp = resp.await.context("make request")?;
78 if ! resp.status().is_success() {
79 throw!(anyhow!("HTTP error status {}", &resp.status()));
81 let resp = resp.into_body();
82 // xxx: some size limit to avoid mallocing the universe
83 let resp = hyper::body::to_bytes(resp).await
84 .context("HTTP error fetching response body")?;
89 let r = c.reporter.lock().report(r);
92 tokio::time::sleep(c.ic.http_retry).await;
99 #[allow(unused_variables)] // xxx
100 async fn run_client<C:HCC>(
102 hclient: Arc<hyper::Client<C>>
103 ) -> Result<Void, AE>
105 debug!("{}: config: {:?}", &ic, &ic);
107 let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
109 let c = ClientContext {
115 let mut ipif = tokio::process::Command::new("sh")
116 .args(&["-c", &ic.ipif])
117 .stdin (process::Stdio::piped())
118 .stdout(process::Stdio::piped())
119 .stderr(process::Stdio::piped())
121 .spawn().context("spawn ipif")?;
123 let stderr = ipif.stderr.take().unwrap();
124 let ic_name = ic.to_string();
125 let _ = task::spawn(async move {
126 let mut stderr = tokio::io::BufReader::new(stderr).lines();
127 while let Some(l) = stderr.next_line().await? {
128 error!("{}: ipif stderr: {}", &ic_name, l.trim_end());
130 Ok::<_,io::Error>(())
133 let tx_stream = ipif.stdout.take().unwrap();
134 let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_ESC);
135 let mut tx_defer = None;
137 let stream_for_rx = ipif.stdin .take().unwrap();
139 let mut reqs: Vec<OutstandingRequest>
140 = Vec::with_capacity(ic.max_requests_outstanding.sat());
142 // xxx check that ic settings are all honoured
148 // cancellation safety: if this future is polled, we might
149 // move out of tx_defer, but then we will be immediately
150 // ready and yield it inot packet
151 if let Some(y) = tx_defer.take() {
154 tx_stream.next_segment().await
157 if tx_defer.is_none() &&
158 reqs.len() < ic.max_requests_outstanding.sat() =>
160 let mut upbound = Frames::default();
161 let mut to_process: Option<Result<Option<Vec<u8>>,_>>
163 while let Some(packet) = to_process.take() {
165 packet.context("read from ipif")?
166 .ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
167 if let Ok(()) = check_checkmtu_mimeswap
168 ::<true>(&ic, &mut packet)
170 match upbound.add(ic.max_batch_up, packet) {
172 tx_defer = Some(packet);
177 // we rely oin `next_segment` being cancellation-safe,
178 // which isn't documented as true but seems reasonably safe
179 pin!{ let next_segment = tx_stream.next_segment(); }
180 to_process = match poll!(next_segment) {
181 Poll::Ready(p) => Some(p),
182 Poll::Pending => None,
186 assert!( to_process.is_none() );
187 dbg!(&reqs.len(), &upbound);
189 //: impl futures::Stream<Cow<&[u8]>>
190 submit_request(&c, &mut reqs, upbound.into())?;
194 if reqs.len() < ic.target_requests_outstanding.sat() ||
195 (tx_defer.is_some() &&
196 reqs.len() < ic.max_requests_outstanding.sat()) =>
198 let upbound = tx_defer.take().into_iter().collect_vec();
199 submit_request(&c, &mut reqs, upbound)?;
202 (got, goti, _) = async { future::select_all(&mut reqs).await },
203 if ! reqs.is_empty() =>
205 reqs.swap_remove(goti);
206 if let Some(got) = got {
207 dbg!(&got.remaining()); // xxx
216 async fn main() -> Result<(), AE> {
217 let ics = config::read(LinkEnd::Client)?;
218 if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
222 let https = HttpsConnector::new();
223 let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
224 let hclient = Arc::new(hclient);
227 let () = future::select_all(
228 ics.into_iter().map(|ic| Box::pin(async {
229 let assocname = ic.to_string();
230 info!("{} starting", &assocname);
231 let hclient = hclient.clone();
232 let join = task::spawn(async {
233 run_client(ic, hclient).await.void_unwrap_err()
237 error!("{} failed: {:?}", &assocname, e);
240 error!("{} panicked!", &assocname);
241 panic::resume_unwind(je.into_panic());
247 error!("quitting because one of your client connections crashed");