Cancel outstanding orders when their trading key misses its heartbeat
This commit is contained in:
@@ -1,15 +1,41 @@
|
||||
use anyhow::Result;
|
||||
use exchange::Exchange;
|
||||
use serde_json::{json, Value};
|
||||
use std::io::{BufRead, Write};
|
||||
use std::{
|
||||
io::{BufRead, Write},
|
||||
sync::mpsc::{sync_channel, RecvTimeoutError},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
pub(crate) fn serve(
|
||||
engine: &mut Exchange,
|
||||
input: impl BufRead,
|
||||
input: impl BufRead + Send + 'static,
|
||||
mut output: impl Write,
|
||||
) -> Result<()> {
|
||||
for line in input.lines() {
|
||||
let line = line?;
|
||||
// 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);
|
||||
let mut next = Instant::now() + interval;
|
||||
loop {
|
||||
if Instant::now() >= next {
|
||||
engine.maintain()?;
|
||||
next = Instant::now() + interval;
|
||||
}
|
||||
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));
|
||||
|
||||
Reference in New Issue
Block a user