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
+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!([]));
}