// Copyright 2021 Ian Jackson and contributors to Hippotat
-// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-License-Identifier: GPL-3.0-or-later
// There is NO WARRANTY.
use hippotat::prelude::*;
use hippotat_macros::into_crlfs;
+#[derive(StructOpt,Debug)]
+pub struct Opts {
+ /// Increase debug level
+ #[structopt(long, short="D", parse(from_occurrences))]
+ debug: usize,
+
+ #[structopt(flatten)]
+ config: config::Opts,
+}
+
type OutstandingRequest<'r> = Pin<Box<
dyn Future<Output=Option<Bytes>> + Send + 'r
>>;
struct ClientContext<'c,C> {
ic: &'c InstanceConfig,
+ effective_http_timeout: Duration,
hclient: &'c Arc<hyper::Client<C>>,
reporter: &'c parking_lot::Mutex<Reporter<'c>>,
}
{}
{}
{}
+ {}
{}"#),
&c.ic.link.client,
token,
c.ic.target_requests_outstanding,
show_timeout,
+ c.ic.max_batch_down,
);
let prefix2 = format!(into_crlfs!(
let resp = c.hclient.request(req);
let fut = Box::pin(async move {
- let r = async { tokio::time::timeout( c.ic.http_timeout, async {
+ let r = async { tokio::time::timeout( c.effective_http_timeout, async {
let resp = resp.await.context("make request")?;
let status = resp.status();
let resp = resp.into_body();
.context("HTTP error fetching response body")?;
if ! status.is_success() {
- // xxx get body and log it
throw!(anyhow!("HTTP error status={} body={:?}",
&status, String::from_utf8_lossy(&resp)));
}
Ok::<_,AE>(resp)
}).await? }.await;
- let r = c.reporter.lock().report(req_num, r);
+ let r = c.reporter.lock().filter(Some(req_num), r);
if r.is_none() {
tokio::time::sleep(c.ic.http_retry).await;
reqs.push(fut);
}
-#[allow(unused_variables)] // xxx
-#[allow(unused_mut)] // xxx
-#[allow(dead_code)] // xxx
async fn run_client<C:HCC>(
ic: InstanceConfig,
hclient: Arc<hyper::Client<C>>
reporter: &reporter,
hclient: &hclient,
ic: &ic,
+ effective_http_timeout: ic.http_timeout.checked_add(ic.http_timeout_grace)
+ .ok_or_else(|| anyhow!("calculate effective http timeout ({:?} + {:?})",
+ ic.http_timeout, ic.http_timeout_grace))?,
};
let mut ipif = tokio::process::Command::new("sh")
let mut req_num: ReqNum = 0;
let tx_stream = ipif.stdout.take().unwrap();
- let rx_stream = ipif.stdin .take().unwrap();
+ let mut rx_stream = ipif.stdin .take().unwrap();
let mut tx_stream = tokio::io::BufReader::new(tx_stream).split(SLIP_END);
let mut packets: VecDeque<Box<[u8]>> = default();
let mut reqs: Vec<OutstandingRequest>
= Vec::with_capacity(ic.max_requests_outstanding.sat());
- let mut rx_queue: VecDeque<Box<[u8]>> = default();
- #[derive(Debug)]
- enum RxState {
- Frame(Cursor<Box<u8>>),
- End,
- }
- let mut rx_current: Option<RxState> = None;
+ let mut rx_queue: FrameQueue = default();
// xxx check that ic settings are all honoured
async {
loop {
select! {
+ y = rx_stream.write_all_buf(&mut rx_queue),
+ if ! rx_queue.is_empty() =>
+ {
+ let () = y.context("write rx data to ipif")?;
+ },
+
data = tx_stream.next_segment(),
if packets.is_empty() =>
{
.ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
//eprintln!("data={:?}", DumpHex(&data));
- check
- ::<_,_,_,Slip2Mime>(ic.mtu, &data, &mut packets, |header| {
- let addr = ip_packet_addr::<false>(header)?;
- if addr != ic.link.client.0 { throw!(PE::Src(addr)) }
- Ok(())
- }, |e| match e {
- PE::Empty => { },
- e@ PE::Src(_) => debug!("{}: tx discarding: {}", &ic, e),
- e => error!("{}: tx discarding: {}", &ic, e),
- });
+ match check1(Slip2Mime, ic.mtu, &data, |header| {
+ let addr = ip_packet_addr::<false>(header)?;
+ if addr != ic.link.client.0 { throw!(PE::Src(addr)) }
+ Ok(())
+ }) {
+ Ok(packet) => packets.push_back(packet),
+ Err(PE::Empty) => { },
+ Err(e@ PE::Src(_)) => debug!("{}: tx discarding: {}", &ic, e),
+ Err(e) => error!("{}: tx discarding: {}", &ic, e),
+ };
},
_ = async { },
},
_ = async { },
- if reqs.len() < ic.target_requests_outstanding.sat() ||
+ if reporter.lock().filter(None, {
+ if rx_queue.remaining() < ic.max_batch_down.sat() * 3 /* xxx */ {
+ // xxx make this separate option ? docs say server only
+ Ok(())
+ } else {
+ Err(anyhow!("rx queue full"))
+ }
+ }).is_some() &&
+ (reqs.len() < ic.target_requests_outstanding.sat() ||
(reqs.len() < ic.max_requests_outstanding.sat() &&
- ! upbound.is_empty())
- // xxx backpressure, if too much in rx_queue
+ ! upbound.is_empty()))
=>
{
submit_request(&c, &mut req_num, &mut reqs,
reqs.swap_remove(goti);
if let Some(got) = got {
+ reporter.lock().success();
//eprintln!("got={:?}", DumpHex(&got));
- check
- ::<_,_,_,SlipNoConv>(ic.mtu, &got, &mut rx_queue, |header| {
- let addr = ip_packet_addr::<true>(header)?;
- if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
- Ok(())
- }, |e| error!("{} #{}: rx discarding: {}", &ic, req_num, e));
+ checkn(SlipNoConv,ic.mtu, &got, &mut rx_queue, |header| {
+ let addr = ip_packet_addr::<true>(header)?;
+ if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
+ Ok(())
+ }, |e| error!("{} #{}: rx discarding: {}", &ic, req_num, e));
- dbg!(&rx_queue.len());
- rx_queue = default(); // xxx
}
}
}
#[tokio::main]
async fn main() -> Result<(), AE> {
- let ics = config::read(LinkEnd::Client)?;
+ let opts = Opts::from_args();
+
+ let ics = config::read(&opts.config, LinkEnd::Client)?;
if ics.is_empty() { throw!(anyhow!("no associations with server(s)")); }
- env_logger::init();
+ {
+ let env = env_logger::Env::new()
+ .filter("HIPPOTAT_LOG")
+ .write_style("HIPPOTAT_LOG_STYLE");
+
+ let mut logb = env_logger::Builder::new();
+ logb.filter(Some("hippotat"),
+ *[ log::LevelFilter::Info,
+ log::LevelFilter::Debug ]
+ .get(opts.debug)
+ .unwrap_or(
+ &log::LevelFilter::Trace
+ ));
+ logb.parse_env(env);
+ logb.init();
+ }
let https = HttpsConnector::new();
let hclient = hyper::Client::builder().build::<_, hyper::Body>(https);