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 prefix1 = 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!(
61 let body = hyper::body::Body::wrap_stream(
62 futures::stream::iter(itertools::chain![
63 array::IntoIter::new([
64 Ok::<Bytes,Void>( prefix1.into() ),
65 Ok::<Bytes,Void>( prefix2.into() ),
67 if upbound.is_empty() { 1 } else { 2 }
69 Itertools::intersperse(
70 upbound.into_iter().map(|u| Bytes::from(u)),
72 ).map(Ok::<Bytes,Void>),
73 [ Ok::<Bytes,Void>( suffix.into() ) ],
77 let req = hyper::Request::post(&c.ic.url).body(body)
78 .context("construct request")?;
80 let resp = c.hclient.request(req);
81 let fut = Box::pin(async move {
82 let r = async { tokio::time::timeout( c.ic.http_timeout, async {
83 let resp = resp.await.context("make request")?;
84 if ! resp.status().is_success() {
85 throw!(anyhow!("HTTP error status {}", &resp.status()));
87 let resp = resp.into_body();
88 // xxx: some size limit to avoid mallocing the universe
89 let resp = hyper::body::to_bytes(resp).await
90 .context("HTTP error fetching response body")?;
95 let r = c.reporter.lock().report(r);
98 tokio::time::sleep(c.ic.http_retry).await;
105 #[allow(unused_variables)] // xxx
106 async fn run_client<C:HCC>(
108 hclient: Arc<hyper::Client<C>>
109 ) -> Result<Void, AE>
111 debug!("{}: config: {:?}", &ic, &ic);
113 let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
115 let c = ClientContext {
121 let mut ipif = tokio::process::Command::new("sh")
122 .args(&["-c", &ic.ipif])
123 .stdin (process::Stdio::piped())
124 .stdout(process::Stdio::piped())
125 .stderr(process::Stdio::piped())
127 .spawn().context("spawn ipif")?;
129 let stderr = ipif.stderr.take().unwrap();
130 let ic_name = ic.to_string();
131 let _ = task::spawn(async move {
132 let mut stderr = tokio::io::BufReader::new(stderr).lines();
133 while let Some(l) = stderr.next_line().await? {
134 error!("{}: ipif stderr: {}", &ic_name, l.trim_end());
136 Ok::<_,io::Error>(())
139 let tx_stream = ipif.stdout.take().unwrap();
140 let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_ESC);
141 let mut tx_defer = None;
143 let stream_for_rx = ipif.stdin .take().unwrap();
145 let mut reqs: Vec<OutstandingRequest>
146 = Vec::with_capacity(ic.max_requests_outstanding.sat());
148 // xxx check that ic settings are all honoured
154 // cancellation safety: if this future is polled, we might
155 // move out of tx_defer, but then we will be immediately
156 // ready and yield it inot packet
157 if let Some(y) = tx_defer.take() {
160 tx_stream.next_segment().await
163 if tx_defer.is_none() &&
164 reqs.len() < ic.max_requests_outstanding.sat() =>
166 let mut upbound = Frames::default();
167 let mut to_process: Option<Result<Option<Vec<u8>>,_>>
169 while let Some(packet) = to_process.take() {
171 packet.context("read from ipif")?
172 .ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
173 if let Ok(()) = check_checkmtu_mimeswap
174 ::<true>(&ic, &mut packet)
176 match upbound.add(ic.max_batch_up, packet) {
178 tx_defer = Some(packet);
183 // we rely oin `next_segment` being cancellation-safe,
184 // which isn't documented as true but seems reasonably safe
185 pin!{ let next_segment = tx_stream.next_segment(); }
186 to_process = match poll!(next_segment) {
187 Poll::Ready(p) => Some(p),
188 Poll::Pending => None,
192 assert!( to_process.is_none() );
193 dbg!(&reqs.len(), &upbound);
195 //: impl futures::Stream<Cow<&[u8]>>
196 submit_request(&c, &mut reqs, upbound.into())?;
200 if reqs.len() < ic.target_requests_outstanding.sat() ||
201 (tx_defer.is_some() &&
202 reqs.len() < ic.max_requests_outstanding.sat()) =>
204 let upbound = tx_defer.take().into_iter().collect_vec();
205 submit_request(&c, &mut reqs, upbound)?;
208 (got, goti, _) = async { future::select_all(&mut reqs).await },
209 if ! reqs.is_empty() =>
211 reqs.swap_remove(goti);
212 if let Some(got) = got {
213 dbg!(&got.remaining()); // xxx
222 async fn main() -> Result<(), AE> {
223 let ics = config::read(LinkEnd::Client)?;
224 if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
228 let https = HttpsConnector::new();
229 let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
230 let hclient = Arc::new(hclient);
233 let () = future::select_all(
234 ics.into_iter().map(|ic| Box::pin(async {
235 let assocname = ic.to_string();
236 info!("{} starting", &assocname);
237 let hclient = hclient.clone();
238 let join = task::spawn(async {
239 run_client(ic, hclient).await.void_unwrap_err()
243 error!("{} failed: {:?}", &assocname, e);
246 error!("{} panicked!", &assocname);
247 panic::resume_unwind(je.into_panic());
253 error!("quitting because one of your client connections crashed");