chiark / gitweb /
wip request mime
[hippotat.git] / src / bin / client.rs
1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: AGPL-3.0-or-later
3 // There is NO WARRANTY.
4
5 use hippotat::prelude::*;
6 use hippotat_macros::into_crlfs;
7
8 type OutstandingRequest<'r> = Pin<Box<
9     dyn Future<Output=Option<Bytes>> + Send + 'r
10     >>;
11
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 { }
15
16 struct ClientContext<'c,C> {
17   ic: &'c InstanceConfig,
18   hclient: &'c Arc<hyper::Client<C>>,
19   reporter: &'c parking_lot::Mutex<Reporter<'c>>,
20 }
21
22 #[throws(AE)]
23 fn submit_request<'r, 'c:'r, C:HCC>(
24   c: &'c ClientContext<C>,
25   reqs: &mut Vec<OutstandingRequest<'r>>,
26   upbound: FramesData,
27 ) {
28   let show_timeout = c.ic.http_timeout
29     .saturating_add(Duration::from_nanos(999_999_999))
30     .as_secs();
31
32   let prefix1 = format!(into_crlfs!(
33     r#"--
34        Content-Type: text/plain; charset="utf-8"
35        Content-Disposition: form-data; name="m"
36
37        {}
38        {}
39        {}
40        {}"#),
41                        &c.ic.link.client,
42                        "xxx token goes here",
43                        c.ic.target_requests_outstanding,
44                        show_timeout,
45   );
46
47   let prefix2 = format!(into_crlfs!(
48     r#"
49        --
50        Content-Type: application/octet-stream
51        Content-Disposition: form-data; name="d"
52
53        "#),
54   );
55   let suffix = format!(into_crlfs!(
56     r#"
57        --b--
58        "#),
59   );
60
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() ),
66       ]).take(
67         if upbound.is_empty() { 1 } else { 2 }
68       ),
69       Itertools::intersperse(
70         upbound.into_iter().map(|u| Bytes::from(u)),
71         SLIP_END_SLICE.into()
72       ).map(Ok::<Bytes,Void>),
73       [ Ok::<Bytes,Void>( suffix.into() ) ],
74     ])
75   );
76
77   let req = hyper::Request::post(&c.ic.url).body(body)
78     .context("construct request")?;
79
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()));
86       }
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")?;
91
92       Ok::<_,AE>(resp)
93     }).await? }.await;
94
95     let r = c.reporter.lock().report(r);
96
97     if r.is_none() {
98       tokio::time::sleep(c.ic.http_retry).await;
99     }
100     r
101   });
102   reqs.push(fut);
103 }
104
105 #[allow(unused_variables)] // xxx
106 async fn run_client<C:HCC>(
107   ic: InstanceConfig,
108   hclient: Arc<hyper::Client<C>>
109 ) -> Result<Void, AE>
110 {
111   debug!("{}: config: {:?}", &ic, &ic);
112
113   let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
114
115   let c = ClientContext {
116     reporter: &reporter,
117     hclient: &hclient,
118     ic: &ic,
119   };
120
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())
126     .kill_on_drop(true)
127     .spawn().context("spawn ipif")?;
128   
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());
135     }
136     Ok::<_,io::Error>(())
137   });
138
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;
142
143   let stream_for_rx = ipif.stdin .take().unwrap();
144
145   let mut reqs: Vec<OutstandingRequest>
146     = Vec::with_capacity(ic.max_requests_outstanding.sat());
147
148   // xxx check that ic settings are all honoured
149
150   async {
151     loop {
152       select! {
153         packet = async {
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() {
158             Ok(Some(y))
159           } else {
160             tx_stream.next_segment().await
161           }
162         },
163         if tx_defer.is_none() &&
164            reqs.len() < ic.max_requests_outstanding.sat() =>
165         {
166           let mut upbound = Frames::default();
167           let mut to_process: Option<Result<Option<Vec<u8>>,_>>
168             = Some(packet);
169           while let Some(packet) = to_process.take() {
170             let mut packet =
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)
175             {
176               match upbound.add(ic.max_batch_up, packet) {
177                 Err(packet) => {
178                   tx_defer = Some(packet);
179                   break;
180                 }
181                 Ok(()) => { },
182               };
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,
189               };
190             }
191           }
192           assert!( to_process.is_none() );
193           dbg!(&reqs.len(), &upbound);
194
195           //: impl futures::Stream<Cow<&[u8]>>
196           submit_request(&c, &mut reqs, upbound.into())?;
197         }
198
199         () = async { },
200         if reqs.len() < ic.target_requests_outstanding.sat() ||
201            (tx_defer.is_some() &&
202             reqs.len() < ic.max_requests_outstanding.sat()) =>
203         {
204           let upbound = tx_defer.take().into_iter().collect_vec();
205           submit_request(&c, &mut reqs, upbound)?;
206         }
207
208         (got, goti, _) = async { future::select_all(&mut reqs).await },
209           if ! reqs.is_empty() =>
210         {
211           reqs.swap_remove(goti);
212           if let Some(got) = got {
213             dbg!(&got.remaining()); // xxx
214           }
215         }
216       }
217     }
218   }.await
219 }
220
221 #[tokio::main]
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)")); }
225
226   env_logger::init();
227
228   let https = HttpsConnector::new();
229   let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
230   let hclient = Arc::new(hclient);
231
232   info!("starting");
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()
240       });
241       match join.await {
242         Ok(e) => {
243           error!("{} failed: {:?}", &assocname, e);
244         },
245         Err(je) => {
246           error!("{} panicked!", &assocname);
247           panic::resume_unwind(je.into_panic());
248         },
249       }
250     }))
251   ).await.0;
252
253   error!("quitting because one of your client connections crashed");
254   process::exit(16);
255 }