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 prefix = 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 eprintln!(">{}[{}D]{}<", &prefix, &prefix2, &suffix);
61
62   let body = hyper::body::Body::wrap_stream(
63     futures::stream::iter(
64       Itertools::intersperse(
65         upbound.into_iter().map(|u| Bytes::from(u)),
66         SLIP_END_SLICE.into()
67       ).map(Ok::<_,Void>)
68     )
69   );
70
71   let req = hyper::Request::post(&c.ic.url).body(body)
72     .context("construct request")?;
73
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()));
80       }
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")?;
85
86       Ok::<_,AE>(resp)
87     }).await? }.await;
88
89     let r = c.reporter.lock().report(r);
90
91     if r.is_none() {
92       tokio::time::sleep(c.ic.http_retry).await;
93     }
94     r
95   });
96   reqs.push(fut);
97 }
98
99 #[allow(unused_variables)] // xxx
100 async fn run_client<C:HCC>(
101   ic: InstanceConfig,
102   hclient: Arc<hyper::Client<C>>
103 ) -> Result<Void, AE>
104 {
105   debug!("{}: config: {:?}", &ic, &ic);
106
107   let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
108
109   let c = ClientContext {
110     reporter: &reporter,
111     hclient: &hclient,
112     ic: &ic,
113   };
114
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())
120     .kill_on_drop(true)
121     .spawn().context("spawn ipif")?;
122   
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());
129     }
130     Ok::<_,io::Error>(())
131   });
132
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;
136
137   let stream_for_rx = ipif.stdin .take().unwrap();
138
139   let mut reqs: Vec<OutstandingRequest>
140     = Vec::with_capacity(ic.max_requests_outstanding.sat());
141
142   // xxx check that ic settings are all honoured
143
144   async {
145     loop {
146       select! {
147         packet = async {
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() {
152             Ok(Some(y))
153           } else {
154             tx_stream.next_segment().await
155           }
156         },
157         if tx_defer.is_none() &&
158            reqs.len() < ic.max_requests_outstanding.sat() =>
159         {
160           let mut upbound = Frames::default();
161           let mut to_process: Option<Result<Option<Vec<u8>>,_>>
162             = Some(packet);
163           while let Some(packet) = to_process.take() {
164             let mut packet =
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)
169             {
170               match upbound.add(ic.max_batch_up, packet) {
171                 Err(packet) => {
172                   tx_defer = Some(packet);
173                   break;
174                 }
175                 Ok(()) => { },
176               };
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,
183               };
184             }
185           }
186           assert!( to_process.is_none() );
187           dbg!(&reqs.len(), &upbound);
188
189           //: impl futures::Stream<Cow<&[u8]>>
190           submit_request(&c, &mut reqs, upbound.into())?;
191         }
192
193         () = async { },
194         if reqs.len() < ic.target_requests_outstanding.sat() ||
195            (tx_defer.is_some() &&
196             reqs.len() < ic.max_requests_outstanding.sat()) =>
197         {
198           let upbound = tx_defer.take().into_iter().collect_vec();
199           submit_request(&c, &mut reqs, upbound)?;
200         }
201
202         (got, goti, _) = async { future::select_all(&mut reqs).await },
203           if ! reqs.is_empty() =>
204         {
205           reqs.swap_remove(goti);
206           if let Some(got) = got {
207             dbg!(&got.remaining()); // xxx
208           }
209         }
210       }
211     }
212   }.await
213 }
214
215 #[tokio::main]
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)")); }
219
220   env_logger::init();
221
222   let https = HttpsConnector::new();
223   let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);
224   let hclient = Arc::new(hclient);
225
226   info!("starting");
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()
234       });
235       match join.await {
236         Ok(e) => {
237           error!("{} failed: {:?}", &assocname, e);
238         },
239         Err(je) => {
240           error!("{} panicked!", &assocname);
241           panic::resume_unwind(je.into_panic());
242         },
243       }
244     }))
245   ).await.0;
246
247   error!("quitting because one of your client connections crashed");
248   process::exit(16);
249 }