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::*;
7 type OutstandingRequest<'r> = Pin<Box<
8 dyn Future<Output=Option<Bytes>> + Send + 'r
11 impl<T> HCC for T where
12 T: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
13 trait HCC: hyper::client::connect::Connect + Clone + Send + Sync + 'static { }
15 struct ClientContext<'c,C> {
16 ic: &'c InstanceConfig,
17 hclient: &'c Arc<hyper::Client<C>>,
18 reporter: &'c parking_lot::Mutex<Reporter<'c>>,
22 fn submit_request<'r, 'c:'r, C:HCC>(
23 c: &'c ClientContext<C>,
24 reqs: &mut Vec<OutstandingRequest<'r>>,
27 let body = hyper::body::Body::wrap_stream(
28 futures::stream::iter(
29 Itertools::intersperse(
30 upbound.into_iter().map(|u| Bytes::from(u)),
31 slip::SLIP_END_SLICE.into()
36 let req = hyper::Request::post(&c.ic.url).body(body)
37 .context("construct request")?;
39 let resp = c.hclient.request(req);
40 let fut = Box::pin(async move {
41 let r = async { tokio::time::timeout( c.ic.http_timeout, async {
42 let resp = resp.await.context("make request")?;
43 if ! resp.status().is_success() {
44 throw!(anyhow!("HTTP error status {}", &resp.status()));
46 let resp = resp.into_body();
47 // xxx: some size limit to avoid mallocing the universe
48 let resp = hyper::body::to_bytes(resp).await
49 .context("HTTP error fetching response body")?;
54 let r = c.reporter.lock().report(r);
57 tokio::time::sleep(c.ic.http_retry).await;
64 #[allow(unused_variables)] // xxx
65 async fn run_client<C:HCC>(
67 hclient: Arc<hyper::Client<C>>
70 debug!("{}: config: {:?}", &ic, &ic);
72 let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
74 let c = ClientContext {
80 let mut ipif = tokio::process::Command::new("sh")
81 .args(&["-c", &ic.ipif])
82 .stdin (process::Stdio::piped())
83 .stdout(process::Stdio::piped())
84 .stderr(process::Stdio::piped())
86 .spawn().context("spawn ipif")?;
88 let stderr = ipif.stderr.take().unwrap();
89 let ic_name = ic.to_string();
90 let _ = task::spawn(async move {
91 let mut stderr = tokio::io::BufReader::new(stderr).lines();
92 while let Some(l) = stderr.next_line().await? {
93 error!("{}: ipif stderr: {}", &ic_name, l.trim_end());
98 let tx_stream = ipif.stdout.take().unwrap();
99 let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_ESC);
100 let mut tx_defer = None;
102 let stream_for_rx = ipif.stdin .take().unwrap();
104 let mut reqs: Vec<OutstandingRequest>
105 = Vec::with_capacity(ic.max_requests_outstanding.sat());
107 // xxx check that ic settings are all honoured
113 // cancellation safety: if this future is polled, we might
114 // move out of tx_defer, but then we will be immediately
115 // ready and yield it inot packet
116 if let Some(y) = tx_defer.take() {
119 tx_stream.next_segment().await
122 if tx_defer.is_none() &&
123 reqs.len() < ic.max_requests_outstanding.sat() =>
125 let mut upbound_total = 0;
126 let mut upbound: Vec<Vec<u8>> = vec![];
127 let mut to_process: Option<Result<Option<Vec<u8>>,_>>
129 while let Some(packet) = to_process.take() {
131 packet.context("read from ipif")?
132 .ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
133 if let Ok(()) = slip::check_checkmtu_mimeswap
134 ::<true>(&ic, &mut packet)
136 let new_upbound_total = packet.len() + upbound_total + 1;
137 if new_upbound_total > ic.max_batch_up.sat() {
138 tx_defer = Some(packet);
141 upbound_total = new_upbound_total;
142 upbound.push(packet);
143 // we rely oin `next_segment` being cancellation-safe,
144 // which isn't documented as true but seems reasonably safe
145 pin!{ let next_segment = tx_stream.next_segment(); }
146 to_process = match poll!(next_segment) {
147 Poll::Ready(p) => Some(p),
148 Poll::Pending => None,
152 assert!( to_process.is_none() );
153 dbg!(&reqs.len(), &upbound_total, &upbound.len());
155 //: impl futures::Stream<Cow<&[u8]>>
156 submit_request(&c, &mut reqs, upbound)?;
160 if reqs.len() < ic.target_requests_outstanding.sat() ||
161 (tx_defer.is_some() &&
162 reqs.len() < ic.max_requests_outstanding.sat()) =>
164 let upbound = tx_defer.take().into_iter().collect_vec();
165 submit_request(&c, &mut reqs, upbound)?;
168 (got, goti, _) = async { future::select_all(&mut reqs).await },
169 if ! reqs.is_empty() =>
171 reqs.swap_remove(goti);
172 if let Some(got) = got {
173 dbg!(&got.remaining()); // xxx
182 async fn main() -> Result<(), AE> {
183 let ics = config::read(LinkEnd::Client)?;
184 if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
188 let https = HttpsConnector::new();
189 let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
190 let hclient = Arc::new(hclient);
193 let () = future::select_all(
194 ics.into_iter().map(|ic| Box::pin(async {
195 let assocname = ic.to_string();
196 info!("{} starting", &assocname);
197 let hclient = hclient.clone();
198 let join = task::spawn(async {
199 run_client(ic, hclient).await.void_unwrap_err()
203 error!("{} failed: {:?}", &assocname, e);
206 error!("{} panicked!", &assocname);
207 panic::resume_unwind(je.into_panic());
213 error!("quitting because one of your client connections crashed");