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
+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,
})
}
}