Serve subscribed order book updates over a market WebSocket

This commit is contained in:
2026-12-03 07:35:08 +08:00
parent 6b50266300
commit e80e52275c
13 changed files with 675 additions and 20 deletions
+21
View File
@@ -930,3 +930,24 @@ sequenceDiagram
E-->>C: price_change 批次和新 cursor
C->>C: 按资产、方向、价格覆盖数量,零份移除该档
```
### 将盘口变动交给 WebSocket 会话
```mermaid
flowchart LR
ws["cli/subscriptions.rs"] --> api["lib.rs / market_stream_page"]
api --> page["depth_feed.rs / MarketPage"]
page --> snap["book_snapshot.rs"]
```
```mermaid
sequenceDiagram
participant S as 单个连接的订阅
participant E as Exchange
participant D as SQLite
S->>E: market_stream_page(market, after)
E->>D: 同一个读事务读取批次及最终档量
E-->>S: 原始协议帧、各帧所属批次及下一游标
S->>S: 将每个资产的订阅起点与帧批次比较
S-->>S: 输出符合订阅条件的帧,游标留在服务端
```
+1 -1
View File
@@ -9,7 +9,7 @@ pub(crate) fn id(market: &str, outcome: &str) -> String {
format!("eb:{outcome}:{market}")
}
pub(crate) fn parse_id(asset: &str) -> Result<(&str, &str)> {
pub fn parse_id(asset: &str) -> Result<(&str, &str)> {
let (outcome, market) = asset
.strip_prefix("eb:")
.and_then(|s| s.split_once(':'))
+6 -1
View File
@@ -94,8 +94,13 @@ pub(crate) fn read(tx: &Transaction, books: &mut Books, token: &str) -> Result<V
Ok(serde_json::to_value(build(tx, books, token)?)?)
}
pub(crate) fn event(tx: &Transaction, books: &Books, token: &str) -> Result<Value> {
pub(crate) fn event(tx: &Transaction, books: &Books, token: &str, raw: bool) -> Result<Value> {
let s = build(tx, books, token)?;
if raw {
let mut frame = serde_json::to_value(s)?;
frame["event_type"] = json!("book");
return Ok(frame);
}
let stamp: String = tx.query_row(
"SELECT strftime('%Y-%m-%dT%H:%M:%f000Z',?1/1000.0,'unixepoch')",
[&s.timestamp],
+42 -12
View File
@@ -25,8 +25,29 @@ pub(crate) struct Request {
limit: Option<u32>,
}
/// Batch numbers are local delivery cursors; they are never placed on the wire.
pub struct MarketPage {
pub cursor: i64,
pub frames: Vec<(i64, Value)>,
pub has_more: bool,
}
impl Request {
pub fn read(self, tx: &Transaction, books: &mut Books) -> Result<Value> {
let page = self.page(tx, books, false)?;
let events: Vec<_> = page.frames.into_iter().map(|(_, event)| event).collect();
Ok(json!({"cursor":page.cursor,"events":events,"has_more":page.has_more}))
}
pub(crate) fn wire(market: &str, after: Option<i64>) -> Self {
Self {
market: market.into(),
after,
limit: Some(64),
}
}
pub(crate) fn page(self, tx: &Transaction, books: &mut Books, raw: bool) -> Result<MarketPage> {
let limit = self.limit.unwrap_or(100);
ensure!((1..=500).contains(&limit), "invalid book_feed batch limit");
let latest: i64 = tx.query_row(
@@ -37,19 +58,21 @@ impl Request {
books.apply(changes);
let mut events = Vec::new();
for outcome in ["YES", "NO"] {
events.push(book_snapshot::event(
tx,
books,
&assets::id(&self.market, outcome),
)?);
let asset = assets::id(&self.market, outcome);
let frame = book_snapshot::event(tx, books, &asset, raw)?;
events.push((latest, frame));
}
return Ok(json!({"cursor":latest,"events":events,"has_more":false}));
return Ok(MarketPage {
cursor: latest,
frames: events,
has_more: false,
});
};
ensure!((0..=latest).contains(&cursor), "invalid book_feed cursor");
let mut batches = tx.prepare_cached(
"SELECT seq,strftime('%Y-%m-%dT%H:%M:%f000Z',at_ms/1000.0,'unixepoch'),best_bid,best_ask
"SELECT seq,CASE WHEN ?4 THEN CAST(at_ms AS TEXT) ELSE strftime('%Y-%m-%dT%H:%M:%f000Z',at_ms/1000.0,'unixepoch') END,best_bid,best_ask
FROM depth_batches WHERE market=?1 AND seq>?2 ORDER BY seq LIMIT ?3")?;
let mut rows = batches.query(params![self.market, cursor, limit])?;
let mut rows = batches.query(params![self.market, cursor, limit, raw])?;
let mut updates = tx.prepare_cached(
"SELECT side,price,size FROM depth_updates WHERE batch=? ORDER BY side,price",
)?;
@@ -80,11 +103,18 @@ impl Request {
"best_bid":bid.map(price),"best_ask":ask.map(price),"hash":null}));
}
}
events.push(
let frame = if raw {
json!({"event_type":"price_change","market":self.market,"price_changes":changes,"timestamp":stamp})
} else {
json!({"topic":"market","type":"price_change","payload":{"condition_id":self.market,
"price_changes":changes,"timestamp":stamp}}),
);
"price_changes":changes,"timestamp":stamp}})
};
events.push((cursor, frame));
}
Ok(json!({"cursor":cursor,"events":events,"has_more":cursor<latest}))
Ok(MarketPage {
cursor,
frames: events,
has_more: cursor < latest,
})
}
}
+10
View File
@@ -42,6 +42,9 @@ use rusqlite::{params, types::ValueRef, Connection, OptionalExtension, Transacti
use serde_json::{json, Map, Value};
use std::{path::Path, time::Duration};
pub use assets::parse_id as parse_asset_id;
pub use depth_feed::MarketPage;
pub struct Exchange {
db: Connection,
books: Books,
@@ -107,6 +110,13 @@ impl Exchange {
Ok(())
}
pub fn market_stream_page(&mut self, market: &str, after: Option<i64>) -> Result<MarketPage> {
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
let page = depth_feed::Request::wire(market, after).page(&tx, &mut self.books, true)?;
tx.commit()?;
Ok(page)
}
pub fn execute(&mut self, mut payload: Value) -> Result<Value> {
if payload["op"].as_str() == Some("heartbeat") {
payload