Serve single and batch CLOB order books over HTTP

This commit is contained in:
2026-12-03 07:52:06 +08:00
parent 5892772671
commit 5dde2cd28e
11 changed files with 452 additions and 11 deletions
+2
View File
@@ -9,3 +9,5 @@ serde_json.workspace = true
anyhow.workspace = true
serde.workspace = true
tungstenite = "0.28"
tiny_http = "0.12"
serde_urlencoded = "0.7"
+21
View File
@@ -79,3 +79,24 @@ sequenceDiagram
```
[订阅报文样例](../../docs/examples/market-ws.txt)逐行发送为文本帧。客户端可每 10 秒发送一次 `PING`。本地按 100 毫秒间隔检查新批次,单页最多 64 个批次,每个进程最多接纳 128 个同时连接的会话。这些是本地实现参数。慢连接的网络写入在释放 Exchange 锁后进行。
## 盘口 HTTP
`cli DATABASE --market-http 127.0.0.1:9002` 启动公开盘口读取服务。可与写入会话和 WebSocket 服务共用数据库文件。[HTTP 请求样例](../../docs/examples/clob-http.http)
```mermaid
flowchart LR
main["main.rs"] --> http["market_http.rs"]
http --> api["exchange::Exchange::public_books"]
```
```mermaid
sequenceDiagram
participant C as SDK
participant H as market_http
participant E as Exchange
C->>H: GET /book?token_id=... 或 POST /books
H->>E: 提交本次请求的资产 ID
E-->>H: 一个数据库快照中的盘口列表
H-->>C: 单盘 JSON 对象或批量 JSON 数组
```
+10 -3
View File
@@ -1,3 +1,4 @@
mod market_http;
mod market_ws;
mod stream;
mod subscriptions;
@@ -11,17 +12,23 @@ use std::{
fn main() -> Result<()> {
let mut args = env::args_os().skip(1);
let usage = "usage: cli DATABASE [--market-ws HOST:PORT]";
let usage = "usage: cli DATABASE [--market-ws HOST:PORT | --market-http HOST:PORT]";
let path = args.next().context(usage)?;
if let Some(mode) = args.next() {
ensure!(mode == "--market-ws", usage);
ensure!(mode == "--market-ws" || mode == "--market-http", usage);
let addr: SocketAddr = args
.next()
.and_then(|s| s.into_string().ok())
.context(usage)?
.parse()?;
ensure!(args.next().is_none(), usage);
return market_ws::serve(Exchange::open(path)?, TcpListener::bind(addr)?);
let engine = Exchange::open(path)?;
let listener = TcpListener::bind(addr)?;
return if mode == "--market-http" {
market_http::serve(engine, listener)
} else {
market_ws::serve(engine, listener)
};
}
let mut exchange = Exchange::open(path)?;
stream::serve(
+213
View File
@@ -0,0 +1,213 @@
use anyhow::Result;
use exchange::Exchange;
use serde::Deserialize;
use serde_json::{json, Value};
use std::{io::Read, net::TcpListener, sync::Mutex, thread};
use tiny_http::{Header, Method, Request, Response, Server};
const MAX_BOOKS: usize = 500;
const MAX_BODY: u64 = 1_048_576;
const MISSING: &str = "No orderbook exists for the requested token id";
#[derive(Deserialize)]
struct BookParam {
token_id: String,
// The official SDK can include a side on a BookParams item. The book contains both.
#[serde(rename = "side")]
_side: Option<Side>,
}
#[derive(Deserialize)]
#[serde(rename_all = "UPPERCASE")]
enum Side {
Buy,
Sell,
}
type Reply = std::result::Result<Value, (u16, &'static str)>;
fn query(engine: &Mutex<Exchange>, params: Vec<BookParam>, single: bool) -> Reply {
if params.len() > MAX_BOOKS || params.iter().any(|p| p.token_id.trim().is_empty()) {
return Err((400, "Invalid book request"));
}
let tokens = params.into_iter().map(|p| p.token_id).collect::<Vec<_>>();
let mut books = engine
.lock()
.map_err(|_| (500, "Order book unavailable"))?
.public_books(&tokens)
.map_err(|_| (500, "Order book unavailable"))?;
if single {
books.pop().ok_or((404, MISSING))
} else {
Ok(Value::Array(books))
}
}
fn batch(req: &mut Request, engine: &Mutex<Exchange>) -> Reply {
if req.body_length().is_some_and(|n| n as u64 > MAX_BODY) {
return Err((413, "Request body too large"));
}
let mut data = Vec::new();
req.as_reader()
.take(MAX_BODY + 1)
.read_to_end(&mut data)
.map_err(|_| (400, "Invalid request body"))?;
if data.len() as u64 > MAX_BODY {
return Err((413, "Request body too large"));
}
let params = serde_json::from_slice(&data).map_err(|_| (400, "Invalid book request"))?;
query(engine, params, false)
}
fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
let (path, params) = req.url().split_once('?').unwrap_or((req.url(), ""));
let mut allow = None;
let reply = match (req.method(), path) {
(&Method::Get, "/book") => serde_urlencoded::from_str::<BookParam>(params)
.map_err(|_| (400, "Invalid token id"))
.and_then(|p| query(engine, vec![p], true)),
(&Method::Post, "/books") => batch(&mut req, engine),
(_, "/book") => {
allow = Some("GET");
Err((405, "Method not allowed"))
}
(_, "/books") => {
allow = Some("POST");
Err((405, "Method not allowed"))
}
_ => Err((404, "Not found")),
};
let (status, body) = match reply {
Ok(v) => (200, v),
Err((status, msg)) => (status, json!({"error":msg})),
};
let mut response = Response::from_data(body.to_string().into_bytes())
.with_status_code(status)
.with_header(Header::from_bytes("Content-Type", "application/json").unwrap());
if let Some(method) = allow {
response.add_header(Header::from_bytes("Allow", method).unwrap());
}
req.respond(response)
}
pub(crate) fn serve(engine: Exchange, listener: TcpListener) -> Result<()> {
let server = Server::from_listener(listener, None).map_err(anyhow::Error::from_boxed)?;
let engine = Mutex::new(engine);
thread::scope(|scope| {
for _ in 0..4 {
scope.spawn(|| {
for req in server.incoming_requests() {
if let Err(err) = respond(req, &engine) {
eprintln!("market HTTP response: {err}");
}
}
});
}
});
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::{io::Write, net::TcpStream, time::Duration};
#[test]
fn socket_serves_single_and_batch_books_and_rejects_invalid_requests() {
let mut db = Exchange::open(":memory:").unwrap();
let market = "map 2:胜者";
db.execute(
json!({"op":"list","id":"list","market":market,"rules":"simulated","tick_size":"0.01"}),
)
.unwrap();
let yes = format!("eb:YES:{market}");
let no = format!("eb:NO:{market}");
let expected_yes = db
.execute(json!({"op":"clob_book","token_id":yes}))
.unwrap();
let expected_no = db.execute(json!({"op":"clob_book","token_id":no})).unwrap();
let max_batch = vec![json!({"token_id":yes}); MAX_BOOKS];
let too_many = vec![json!({"token_id":yes}); MAX_BOOKS + 1];
let addr = TcpListener::bind("127.0.0.1:0").unwrap();
let port = addr.local_addr().unwrap();
let server = Server::from_listener(addr, None).unwrap();
let encoded = "/book?token_id=eb%3AYES%3Amap+2%3A%E8%83%9C%E8%80%85";
let mixed = json!([
{"token_id":no}, {"token_id":"7"}, {"token_id":yes,"side":"BUY"}, {"token_id":no}
]);
let cases = [
(
"GET",
encoded,
String::new(),
200,
Some(expected_yes.clone()),
),
(
"POST",
"/books",
mixed.to_string(),
200,
Some(json!([expected_no, expected_yes, expected_no])),
),
(
"GET",
"/book?token_id=7",
String::new(),
404,
Some(json!({"error": MISSING})),
),
("GET", "/book", String::new(), 400, None),
("POST", "/books", "[]".into(), 200, Some(json!([]))),
("POST", "/books", json!(max_batch).to_string(), 200, None),
("POST", "/books", json!(too_many).to_string(), 400, None),
("POST", "/books", "{}".into(), 400, None),
(
"POST",
"/books",
r#"[{"token_id":"7","side":"INVALID"}]"#.into(),
400,
None,
),
("GET", "/books", String::new(), 405, None),
("POST", "/order", "{}".into(), 404, None),
];
let count = cases.len();
let worker = thread::spawn(move || {
let db = Mutex::new(db);
for _ in 0..count {
let req = server
.recv_timeout(Duration::from_secs(5))
.unwrap()
.unwrap();
respond(req, &db).unwrap();
}
});
for (method, path, body, status, expected) in cases {
let mut socket = TcpStream::connect(port).unwrap();
socket
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
write!(socket,"{method} {path} HTTP/1.0\r\nHost: {port}\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",body.len()).unwrap();
let mut message = String::new();
socket.read_to_string(&mut message).unwrap();
let (headers, body) = message.split_once("\r\n\r\n").unwrap();
assert_eq!(
headers.split_whitespace().nth(1).unwrap(),
status.to_string()
);
assert!(headers
.to_ascii_lowercase()
.contains("content-type: application/json"));
let actual: Value = serde_json::from_str(body).unwrap();
if let Some(expected) = expected {
assert_eq!(actual, expected);
} else if status == 200 {
assert_eq!(actual.as_array().unwrap().len(), MAX_BOOKS);
} else {
assert!(actual["error"].is_string());
}
}
worker.join().unwrap();
}
}
+25
View File
@@ -955,3 +955,28 @@ sequenceDiagram
S->>S: 将每个资产的订阅起点与帧批次比较
S-->>S: 输出符合订阅条件的帧,游标留在服务端
```
### 一致的批量盘口
```mermaid
flowchart LR
http["cli/market_http.rs"] --> engine["lib.rs"]
engine --> snapshots["book_snapshot.rs"]
snapshots --> resident["resident.rs"]
```
```mermaid
sequenceDiagram
participant H as HTTP 服务
participant E as Exchange
participant D as SQLite
participant B as 常驻盘口
H->>E: public_books 请求多个资产
E->>D: 开启读事务,确定快照
E->>B: 应用到该快照的已提交订单变更
loop 每个请求的资产
E->>D: 读取同一版本的市场规格和最近成交
E->>B: 汇总该资产的买卖档位并计算快照哈希
end
E-->>H: 结束读事务并返回数组
```
+42 -8
View File
@@ -7,9 +7,9 @@ use crate::{
resident::Books,
tick_size::{TickSize, PAR},
};
use anyhow::Result;
use anyhow::{Context, Result};
use matching::Side;
use rusqlite::Transaction;
use rusqlite::{OptionalExtension, Transaction};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sha1::{Digest, Sha1};
@@ -45,12 +45,28 @@ impl Snapshot {
fn build(tx: &Transaction, books: &Books, token: &str) -> Result<Snapshot> {
let (outcome, market) = assets::parse_id(token)?;
let (at_ms, neg_risk): (i64, bool) = tx.query_row(
"SELECT at_ms,EXISTS(SELECT 1 FROM neg_risk_members WHERE market=?1)
find(tx, books, token, outcome, market)?
.context("No orderbook exists for the requested token id")
}
fn find(
tx: &Transaction,
books: &Books,
token: &str,
outcome: &str,
market: &str,
) -> Result<Option<Snapshot>> {
let row: Option<(i64, bool)> = tx
.query_row(
"SELECT at_ms,EXISTS(SELECT 1 FROM neg_risk_members WHERE market=?1)
FROM book_snapshot_times WHERE market=?1",
[market],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
[market],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
let Some((at_ms, neg_risk)) = row else {
return Ok(None);
};
let book = books.get(market, outcome);
let levels = |taker| {
let mut result = Vec::new();
@@ -85,7 +101,25 @@ fn build(tx: &Transaction, books: &Books, token: &str) -> Result<Snapshot> {
.unwrap_or_default(),
};
snapshot.set_hash()?;
Ok(snapshot)
Ok(Some(snapshot))
}
pub(crate) fn read_many(
tx: &Transaction,
books: &mut Books,
tokens: &[String],
) -> Result<Vec<Value>> {
let changes = books.changes(tx)?;
books.apply(changes);
let mut result = Vec::with_capacity(tokens.len());
for token in tokens {
if let Ok((outcome, market)) = assets::parse_id(token) {
if let Some(book) = find(tx, books, token, outcome, market)? {
result.push(serde_json::to_value(book)?);
}
}
}
Ok(result)
}
pub(crate) fn read(tx: &Transaction, books: &mut Books, token: &str) -> Result<Value> {
+8
View File
@@ -119,6 +119,14 @@ impl Exchange {
Ok(())
}
/// Read requested outcome books in one consistent database and resident-book snapshot.
pub fn public_books(&mut self, tokens: &[String]) -> Result<Vec<Value>> {
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
let books = book_snapshot::read_many(&tx, &mut self.books, tokens)?;
tx.commit()?;
Ok(books)
}
pub fn market_stream_page(&mut self, market: &str, after: Option<i64>) -> Result<MarketPage> {
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
let page = market_stream::page(&tx, &mut self.books, market, after)?;
+49
View File
@@ -2916,3 +2916,52 @@ fn market_stream_preserves_trades_and_empty_book_tick_across_restart() {
page.cursor
);
}
#[test]
fn batch_book_reads_keep_complementary_depth_on_one_revision() {
let dir = tempdir().unwrap();
let path = dir.path().join("batch.db");
let mut writer = Exchange::open(&path).unwrap();
let mut reader = Exchange::open(&path).unwrap();
for cmd in [
json!({"op":"list","id":"list","market":"demo","rules":"Local binary outcome","tick_size":"0.01"}),
json!({"op":"fund","id":"fund","account":"maker","cents":3000}),
json!({"op":"open","id":"open","market":"demo"}),
] {
writer.execute(cmd).unwrap();
}
let tokens = ["eb:YES:demo", "eb:NO:demo", "eb:YES:demo"].map(String::from);
let start = std::sync::Barrier::new(2);
std::thread::scope(|scope| {
scope.spawn(|| {
start.wait();
for index in 0..24 {
let order = writer
.execute(json!({"op":"order","id":format!("bid-{index}"),
"account":"maker","asset_id":"eb:YES:demo","side":"buy","price":30,"qty":1}))
.unwrap();
writer
.execute(json!({"op":"cancel","id":format!("cancel-{index}"),
"account":"maker","order":order["order"]}))
.unwrap();
}
});
start.wait();
for _ in 0..48 {
let books = reader.public_books(&tokens).unwrap();
assert_eq!(books.len(), 3);
assert_eq!(books[0], books[2]);
assert_eq!(books[0]["timestamp"], books[1]["timestamp"]);
let bids = books[0]["bids"].as_array().unwrap();
let asks = books[1]["asks"].as_array().unwrap();
assert_eq!(bids.len(), asks.len());
if !bids.is_empty() {
assert_eq!(bids, &[json!({"price":"0.3","size":"1"})]);
assert_eq!(asks, &[json!({"price":"0.7","size":"1"})]);
}
}
});
let books = reader.public_books(&tokens).unwrap();
assert_eq!(books[0]["bids"], json!([]));
assert_eq!(books[1]["asks"], json!([]));
}