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
+18 -3
View File
@@ -1,13 +1,28 @@
mod market_ws;
mod stream;
mod subscriptions;
use anyhow::{ensure, Context, Result};
use exchange::Exchange;
use std::{env, io};
use std::{
env, io,
net::{SocketAddr, TcpListener},
};
fn main() -> Result<()> {
let mut args = env::args_os().skip(1);
let path = args.next().context("usage: cli DATABASE")?;
ensure!(args.next().is_none(), "usage: cli DATABASE");
let usage = "usage: cli DATABASE [--market-ws HOST:PORT]";
let path = args.next().context(usage)?;
if let Some(mode) = args.next() {
ensure!(mode == "--market-ws", 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 mut exchange = Exchange::open(path)?;
stream::serve(
&mut exchange,
+163
View File
@@ -0,0 +1,163 @@
use crate::subscriptions::Session;
use anyhow::{Context, Result};
use exchange::Exchange;
use std::{
io::ErrorKind,
net::{TcpListener, TcpStream},
sync::{Arc, Mutex},
thread,
time::{Duration, Instant},
};
use tungstenite::{
accept_hdr_with_config,
handshake::server::{ErrorResponse, Request, Response},
protocol::WebSocketConfig,
Error, Message, WebSocket,
};
const POLL: Duration = Duration::from_millis(100);
pub(crate) fn serve(engine: Exchange, listener: TcpListener) -> Result<()> {
let engine = Arc::new(Mutex::new(engine));
for stream in listener.incoming() {
let stream = stream?;
// Each accepted session owns exactly one engine reference and one OS thread.
if Arc::strong_count(&engine) > 128 {
continue;
}
let engine = Arc::clone(&engine);
thread::Builder::new()
.name("market-ws".into())
.spawn(move || {
if let Err(err) = connection(stream, &engine) {
eprintln!("market WebSocket: {err}");
}
})?;
}
Ok(())
}
fn send(socket: &mut WebSocket<TcpStream>, frame: serde_json::Value) -> Result<()> {
socket.send(Message::text(serde_json::to_string(&frame)?))?;
Ok(())
}
pub(crate) fn connection(stream: TcpStream, engine: &Mutex<Exchange>) -> Result<()> {
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
stream.set_write_timeout(Some(Duration::from_secs(5)))?;
let config = WebSocketConfig::default()
.max_message_size(Some(65536))
.max_frame_size(Some(65536));
let mut socket = accept_hdr_with_config(
stream,
|req: &Request, resp: Response| {
if req.uri().path() == "/ws/market" {
Ok(resp)
} else {
let mut err = ErrorResponse::new(Some("unknown WebSocket path".into()));
*err.status_mut() = tungstenite::http::StatusCode::NOT_FOUND;
Err(err)
}
},
Some(config),
)
.map_err(|e| anyhow::anyhow!("market WebSocket handshake: {e}"))?;
socket.get_mut().set_read_timeout(Some(POLL))?;
let mut session = Session::default();
let mut next = Instant::now();
loop {
match socket.read() {
Ok(Message::Text(s)) if s.as_str() == "PING" => socket.send(Message::text("PONG"))?,
Ok(Message::Text(s)) => {
let reply = {
let mut engine = engine
.lock()
.map_err(|_| anyhow::anyhow!("exchange unavailable"))?;
session.control(&mut engine, s.as_str())
};
match reply {
Ok(snapshots) if !snapshots.is_empty() => send(&mut socket, snapshots.into())?,
Ok(_) => {}
Err(_) => socket.send(Message::text("INVALID OPERATION"))?,
}
}
Ok(Message::Close(_)) => {
let _ = socket.flush();
break;
}
Ok(Message::Ping(_)) => socket.flush()?,
Ok(_) => {}
Err(Error::Io(err))
if matches!(err.kind(), ErrorKind::TimedOut | ErrorKind::WouldBlock) => {}
Err(Error::ConnectionClosed | Error::AlreadyClosed) => break,
Err(err) => return Err(err).context("read market WebSocket"),
}
if Instant::now() >= next {
let frames = {
let mut engine = engine
.lock()
.map_err(|_| anyhow::anyhow!("exchange unavailable"))?;
session.poll(&mut engine)?
};
for frame in frames {
send(&mut socket, frame)?;
}
next = Instant::now() + POLL;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{json, Value};
#[test]
fn market_socket_sends_snapshots_deltas_and_application_pongs() {
let mut engine = Exchange::open(":memory:").unwrap();
for cmd in [
json!({"op":"list","id":"list","market":"demo","rules":"r","tick_size":"0.01"}),
json!({"op":"fund","id":"fund","account":"maker","cents":500}),
json!({"op":"open","id":"open","market":"demo"}),
] {
engine.execute(cmd).unwrap();
}
let engine = Arc::new(Mutex::new(engine));
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let db = Arc::clone(&engine);
let worker = thread::spawn(move || connection(listener.accept().unwrap().0, &db));
let tcp = TcpStream::connect(addr).unwrap();
tcp.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
let (mut client, _) = tungstenite::client(format!("ws://{addr}/ws/market"), tcp).unwrap();
let controls: Vec<&str> = include_str!("../../../docs/examples/market-ws.txt")
.lines()
.collect();
client.send(Message::text(controls[0])).unwrap();
client.send(Message::text("PING")).unwrap();
assert_eq!(client.read().unwrap().into_text().unwrap(), "PONG"); // initial_dump=false
client.send(Message::text(controls[1])).unwrap();
let frames: Value =
serde_json::from_str(client.read().unwrap().to_text().unwrap()).unwrap();
assert_eq!(frames.as_array().unwrap().len(), 1);
assert_eq!(frames[0]["asset_id"], "eb:NO:demo");
assert_eq!(frames[0]["event_type"], "book");
client.send(Message::text(controls[2])).unwrap();
client.send(Message::text("PING")).unwrap();
assert_eq!(client.read().unwrap().into_text().unwrap(), "PONG"); // unsubscribe processed
engine.lock().unwrap().execute(json!({"op":"order","id":"bid","account":"maker","asset_id":"eb:YES:demo","side":"buy","price":30,"qty":1})).unwrap();
let delta: Value = serde_json::from_str(client.read().unwrap().to_text().unwrap()).unwrap();
assert_eq!(delta["event_type"], "price_change");
assert!(delta["timestamp"].as_str().unwrap().parse::<i64>().is_ok());
assert_eq!(delta["price_changes"].as_array().unwrap().len(), 1);
assert_eq!(delta["price_changes"][0]["asset_id"], "eb:NO:demo");
assert_eq!(delta["price_changes"][0]["price"], "0.7");
let quote: Value = serde_json::from_str(client.read().unwrap().to_text().unwrap()).unwrap();
assert_eq!(quote["event_type"], "best_bid_ask");
assert_eq!(quote["best_ask"], "0.7");
assert!(quote["best_bid"].is_null());
client.close(None).unwrap();
worker.join().unwrap().unwrap();
}
}
+215
View File
@@ -0,0 +1,215 @@
use anyhow::{ensure, Context, Result};
use exchange::{parse_asset_id, Exchange, MarketPage};
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::{BTreeMap, BTreeSet};
#[derive(Deserialize)]
struct Control {
#[serde(rename = "type")]
channel: Option<String>,
operation: Option<String>,
assets_ids: Vec<String>,
initial_dump: Option<bool>,
custom_feature_enabled: Option<bool>,
}
#[derive(Clone)]
struct Asset {
since: i64,
bid: Option<String>,
ask: Option<String>,
}
#[derive(Default, Clone)]
struct Market {
cursor: i64,
assets: BTreeMap<String, Asset>,
}
#[derive(Default, Clone)]
pub(crate) struct Session {
opened: bool,
custom: bool,
markets: BTreeMap<String, Market>,
}
impl Session {
pub fn control(&mut self, engine: &mut Exchange, text: &str) -> Result<Vec<Value>> {
let c: Control = serde_json::from_str(text)?;
let opening = !self.opened;
let subscribe = match (opening, c.channel.as_deref(), c.operation.as_deref()) {
(true, Some("market"), None) | (false, None, Some("subscribe")) => true,
(false, None, Some("unsubscribe")) => false,
_ => anyhow::bail!("invalid market subscription operation"),
};
ensure!(!c.assets_ids.is_empty(), "assets_ids required");
let mut groups = BTreeMap::<String, BTreeSet<String>>::new();
for token in c.assets_ids {
let (_, market) = parse_asset_id(&token)?;
groups.entry(market.into()).or_default().insert(token);
}
// Validate all assets before replacing a live subscription.
let mut next = self.clone();
if opening {
next.opened = true;
next.custom = c.custom_feature_enabled.unwrap_or(false);
}
let mut snapshots = Vec::new();
for (market, mut tokens) in groups {
if !subscribe {
if let Some(watch) = next.markets.get_mut(&market) {
watch.assets.retain(|id, _| !tokens.contains(id));
if watch.assets.is_empty() {
next.markets.remove(&market);
}
}
continue;
}
if let Some(watch) = next.markets.get(&market) {
tokens.retain(|id| !watch.assets.contains_key(id));
}
if tokens.is_empty() {
continue;
}
let page = engine.market_stream_page(&market, None)?;
let watch = next.markets.entry(market).or_insert_with(|| Market {
cursor: page.cursor,
assets: BTreeMap::new(),
});
for (_, snapshot) in page.frames {
let id = snapshot["asset_id"]
.as_str()
.context("snapshot asset missing")?;
if !tokens.contains(id) {
continue;
}
let best = |field: &str| {
snapshot[field].as_array()?.last()?["price"]
.as_str()
.map(str::to_owned)
};
watch.assets.insert(
id.into(),
Asset {
since: page.cursor,
bid: best("bids"),
ask: best("asks"),
},
);
if !opening || c.initial_dump.unwrap_or(true) {
snapshots.push(snapshot);
}
}
}
*self = next;
Ok(snapshots)
}
pub fn poll(&mut self, engine: &mut Exchange) -> Result<Vec<Value>> {
let mut frames = Vec::new();
for (market, watch) in &mut self.markets {
let page = engine.market_stream_page(market, Some(watch.cursor))?;
watch.project(market, page, self.custom, &mut frames)?;
}
Ok(frames)
}
}
impl Market {
fn project(
&mut self,
market: &str,
page: MarketPage,
custom: bool,
frames: &mut Vec<Value>,
) -> Result<()> {
for (seq, mut event) in page.frames {
let changes = event["price_changes"]
.as_array_mut()
.context("missing price changes")?;
changes.retain(|c| {
c["asset_id"]
.as_str()
.and_then(|id| self.assets.get(id))
.is_some_and(|asset| seq > asset.since)
});
if changes.is_empty() {
continue;
}
let mut top = Vec::new();
if custom {
for c in changes.iter() {
let token = c["asset_id"].as_str().context("missing changed asset")?;
let asset = self
.assets
.get_mut(token)
.context("unknown changed asset")?;
let bid = c["best_bid"].as_str();
let ask = c["best_ask"].as_str();
if (asset.bid.as_deref(), asset.ask.as_deref()) == (bid, ask) {
continue;
}
asset.bid = bid.map(str::to_owned);
asset.ask = ask.map(str::to_owned);
let spread = bid.zip(ask).map(|(b, a)| spread(a, b)).transpose()?;
top.push(
json!({"event_type":"best_bid_ask","market":market,"asset_id":token,
"best_bid":bid,"best_ask":ask,"spread":spread}),
);
}
}
for quote in &mut top {
quote["timestamp"] = event["timestamp"].clone();
}
frames.push(event);
frames.extend(top);
}
self.cursor = page.cursor;
Ok(())
}
}
fn spread(ask: &str, bid: &str) -> Result<String> {
fn units(s: &str) -> Result<i64> {
let (w, f) = s.split_once('.').unwrap_or((s, ""));
ensure!(f.len() <= 4, "invalid book price precision");
Ok(w.parse::<i64>()? * 10000 + format!("{f:0<4}").parse::<i64>()?)
}
let n = units(ask)? - units(bid)?;
let sign = if n < 0 { "-" } else { "" };
let n = n.abs();
Ok(format!("{sign}{}.{:04}", n / 10000, n % 10000)
.trim_end_matches('0')
.trim_end_matches('.')
.to_owned())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adding_an_asset_does_not_skip_backlog_or_replay_before_its_snapshot() {
let mut db = Exchange::open(":memory:").unwrap();
for cmd in [
json!({"op":"list","id":"l","market":"demo","rules":"r"}),
json!({"op":"fund","id":"f","account":"maker","cents":200}),
json!({"op":"open","id":"o","market":"demo"}),
] {
db.execute(cmd).unwrap();
}
let mut session = Session::default();
let opening = r#"{"type":"market","assets_ids":["eb:YES:demo"]}"#;
assert_eq!(session.control(&mut db, opening).unwrap().len(), 1);
db.execute(json!({"op":"order","id":"a","account":"maker","asset_id":"eb:YES:demo","side":"buy","price":20,"qty":1})).unwrap();
let subscribe = r#"{"operation":"subscribe","assets_ids":["eb:NO:demo"]}"#;
let snap = session.control(&mut db, subscribe).unwrap();
assert_eq!(snap[0]["asks"][0]["price"], "0.8");
assert!(session.control(&mut db, subscribe).unwrap().is_empty());
let frames = session.poll(&mut db).unwrap();
assert_eq!(frames.len(), 1);
assert_eq!(frames[0]["price_changes"].as_array().unwrap().len(), 1);
assert_eq!(frames[0]["price_changes"][0]["asset_id"], "eb:YES:demo");
assert!(session.poll(&mut db).unwrap().is_empty());
}
}