Files
eventbook-exchange/crates/cli/src/stream.rs
T

78 lines
2.5 KiB
Rust

use anyhow::Result;
use exchange::Exchange;
use serde_json::{json, Value};
use std::{
io::{BufRead, Write},
sync::mpsc::{sync_channel, RecvTimeoutError},
thread,
time::{Duration, Instant},
};
pub(crate) fn serve(
engine: &mut Exchange,
input: impl BufRead + Send + 'static,
mut output: impl Write,
) -> Result<()> {
// The engine stays on one thread. A bounded input queue permits idle
// maintenance without buffering an unbounded command stream.
let (sender, reader) = sync_channel(1);
thread::spawn(move || {
for line in input.lines() {
let failed = line.is_err();
if sender.send(line).is_err() || failed {
break;
}
}
});
let interval = Duration::from_secs(5);
// New GTDs live at least two minutes, so rechecking within five seconds
// also catches orders added by another process before their cutoff.
let next_check = |exchange: &Exchange| -> Result<Instant> {
let start = Instant::now();
let wait = exchange
.next_gtd_expiry()?
.unwrap_or(interval)
.min(interval);
Ok(start + wait)
};
let mut next = next_check(engine)?;
loop {
if Instant::now() >= next {
engine.maintain()?;
next = next_check(engine)?;
}
let line = match reader.recv_timeout(next.saturating_duration_since(Instant::now())) {
Ok(line) => line?,
Err(RecvTimeoutError::Timeout) => continue,
Err(RecvTimeoutError::Disconnected) => break,
};
let result = serde_json::from_str::<Value>(&line)
.map_err(anyhow::Error::from)
.and_then(|v| engine.execute(v));
let reply = result.unwrap_or_else(|e| json!({"error":e.to_string()}));
serde_json::to_writer(&mut output, &reply)?;
writeln!(output)?;
output.flush()?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn invalid_line_does_not_discard_next_request() {
let mut e = Exchange::open(":memory:").unwrap();
let mut out = Vec::new();
serve(&mut e, &b"broken\n{\"op\":\"state\"}\n"[..], &mut out).unwrap();
let replies: Vec<Value> = std::str::from_utf8(&out)
.unwrap()
.lines()
.map(|line| serde_json::from_str(line).unwrap())
.collect();
assert_eq!(replies.len(), 2);
assert!(replies[0]["error"].is_string());
assert_eq!(replies[1]["orders"], json!([]));
}
}