Cancel outstanding orders when their trading key misses its heartbeat

This commit is contained in:
2026-12-03 05:57:49 +08:00
parent d01ab8f15c
commit 2306c6fd96
14 changed files with 296 additions and 9 deletions
+4 -1
View File
@@ -1,6 +1,6 @@
# cli
可信操作员的 JSON 行命令入口。启动参数指定数据库文件,程序复用同一个 Exchange 连接。标准输入的每一行对应标准输出的一条 JSON 回执。输入结束时进程退出。
可信操作员的 JSON 行命令入口。启动参数指定数据库文件,程序复用同一个 Exchange 连接。标准输入的每一行对应标准输出的一条 JSON 回执。输入结束时进程退出。输入线程和交易线程之间使用有界队列,交易线程每五秒检查到期任务,空闲时仍可撤掉断线客户端的挂单。
## 文件依赖
@@ -24,6 +24,9 @@ sequenceDiagram
U->>C: 启动并指定数据库路径
C->>E: 打开数据库
C->>S: 传入连接和输入输出流
opt 输入空闲达到定时检查时刻
S->>E: maintain 检查到期注册、释放余单并同步盘口
end
loop 输入一行
U->>S: JSON 命令
alt JSON 有效
+5 -1
View File
@@ -9,5 +9,9 @@ fn main() -> Result<()> {
let path = args.next().context("usage: cli DATABASE")?;
ensure!(args.next().is_none(), "usage: cli DATABASE");
let mut exchange = Exchange::open(path)?;
stream::serve(&mut exchange, io::stdin().lock(), io::stdout().lock())
stream::serve(
&mut exchange,
io::BufReader::new(io::stdin()),
io::stdout().lock(),
)
}
+30 -4
View File
@@ -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));