diff --git a/Cargo.lock b/Cargo.lock index 53fdfdb..ec58f83 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9,7 +9,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519" dependencies = [ "cfg-if", - "getrandom", + "getrandom 0.4.3", "once_cell", "version_check", "zerocopy", @@ -42,6 +42,12 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + [[package]] name = "cc" version = "1.12.0" @@ -64,7 +70,9 @@ version = "0.1.0" dependencies = [ "anyhow", "exchange", + "serde", "serde_json", + "tungstenite", ] [[package]] @@ -86,6 +94,12 @@ dependencies = [ "typenum", ] +[[package]] +name = "data-encoding" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a2330da5de22e8a3cb63252ce2abb30116bf5265e89c0e01bc17015ce30a476" + [[package]] name = "digest" version = "0.10.7" @@ -153,6 +167,18 @@ dependencies = [ "version_check", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -162,7 +188,7 @@ dependencies = [ "cfg-if", "js-sys", "libc", - "r-efi", + "r-efi 6.0.0", "wasm-bindgen", ] @@ -184,6 +210,22 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "http" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a07dc2d082802d1782faa5b3c8ac252f3a4fc89f51e76c3f37dc2d1a5b857c05" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "itoa" version = "1.0.19" @@ -223,6 +265,12 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + [[package]] name = "matching" version = "0.1.0" @@ -245,6 +293,15 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -263,12 +320,47 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "r-efi" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "rusqlite" version = "0.32.1" @@ -397,12 +489,49 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom", + "getrandom 0.4.3", "once_cell", "rustix", "windows-sys", ] +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tungstenite" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand", + "sha1", + "thiserror", + "utf-8", +] + [[package]] name = "typenum" version = "1.20.1" @@ -415,6 +544,12 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + [[package]] name = "vcpkg" version = "0.2.15" @@ -427,6 +562,15 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm-bindgen" version = "0.2.129" @@ -487,6 +631,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + [[package]] name = "zerocopy" version = "0.8.66" diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 871207d..1eca50d 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -7,3 +7,5 @@ version.workspace = true exchange = { path = "../exchange" } serde_json.workspace = true anyhow.workspace = true +serde.workspace = true +tungstenite = "0.28" diff --git a/crates/cli/README.md b/crates/cli/README.md index 96f1baf..e2da6bb 100644 --- a/crates/cli/README.md +++ b/crates/cli/README.md @@ -38,3 +38,37 @@ sequenceDiagram S-->>U: 输出一行 JSON 并刷新 end ``` + +## 市场 WebSocket + +已有可执行文件可用 `cli DATABASE --market-ws 127.0.0.1:9001` 启动行情监听,客户端连接 `ws://127.0.0.1:9001/ws/market`。同一数据库可以由另一条 JSON 行命令会话写入。监听模式只接收市场订阅与心跳。每个连接独立维护订阅,所有连接共享一个 Exchange。当前服务提供明文 WebSocket,接入 TLS 需要相应的服务入口。 + +```mermaid +flowchart LR + main["main.rs"] --> ws["market_ws.rs"] + main --> stdin["stream.rs"] + ws --> subs["subscriptions.rs"] + subs --> api["exchange::Exchange / MarketPage"] + stdin --> api +``` + +```mermaid +sequenceDiagram + participant C as 客户端 + participant W as market_ws + participant S as 连接订阅 + participant E as Exchange + C->>W: Upgrade /ws/market + C->>S: type=market,订阅 YES + S->>E: 同一快照内读取 YES 盘口和批次号 + S-->>C: 初始 book 数组,可用 initial_dump=false 省略 + C->>S: operation=subscribe,增加 NO + S-->>C: 新增 NO 的 book 数组 + S->>E: 从该市场的已读批次号读取后续变化 + S-->>C: price_change,只含已订阅且晚于其起点的资产 + C->>S: operation=unsubscribe,移除 YES + C->>W: 文本 PING + W-->>C: 文本 PONG +``` + +[订阅报文样例](../../docs/examples/market-ws.txt)逐行发送为文本帧。客户端可每 10 秒发送一次 `PING`。本地按 100 毫秒间隔检查新批次,单页最多 64 个批次,每个进程最多接纳 128 个同时连接的会话。这些是本地实现参数。慢连接的网络写入在释放 Exchange 锁后进行。 diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index a197686..03930c3 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -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, diff --git a/crates/cli/src/market_ws.rs b/crates/cli/src/market_ws.rs new file mode 100644 index 0000000..fdf23c8 --- /dev/null +++ b/crates/cli/src/market_ws.rs @@ -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, frame: serde_json::Value) -> Result<()> { + socket.send(Message::text(serde_json::to_string(&frame)?))?; + Ok(()) +} + +pub(crate) fn connection(stream: TcpStream, engine: &Mutex) -> 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::().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(); + } +} diff --git a/crates/cli/src/subscriptions.rs b/crates/cli/src/subscriptions.rs new file mode 100644 index 0000000..83a53ba --- /dev/null +++ b/crates/cli/src/subscriptions.rs @@ -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, + operation: Option, + assets_ids: Vec, + initial_dump: Option, + custom_feature_enabled: Option, +} + +#[derive(Clone)] +struct Asset { + since: i64, + bid: Option, + ask: Option, +} + +#[derive(Default, Clone)] +struct Market { + cursor: i64, + assets: BTreeMap, +} + +#[derive(Default, Clone)] +pub(crate) struct Session { + opened: bool, + custom: bool, + markets: BTreeMap, +} + +impl Session { + pub fn control(&mut self, engine: &mut Exchange, text: &str) -> Result> { + 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::>::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> { + 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, + ) -> 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 { + fn units(s: &str) -> Result { + let (w, f) = s.split_once('.').unwrap_or((s, "")); + ensure!(f.len() <= 4, "invalid book price precision"); + Ok(w.parse::()? * 10000 + format!("{f:0<4}").parse::()?) + } + 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()); + } +} diff --git a/crates/exchange/README.md b/crates/exchange/README.md index 5fbdeb0..20871e5 100644 --- a/crates/exchange/README.md +++ b/crates/exchange/README.md @@ -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: 输出符合订阅条件的帧,游标留在服务端 +``` diff --git a/crates/exchange/src/assets.rs b/crates/exchange/src/assets.rs index 7781491..828c5b5 100644 --- a/crates/exchange/src/assets.rs +++ b/crates/exchange/src/assets.rs @@ -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(':')) diff --git a/crates/exchange/src/book_snapshot.rs b/crates/exchange/src/book_snapshot.rs index d857cef..1cfa0e6 100644 --- a/crates/exchange/src/book_snapshot.rs +++ b/crates/exchange/src/book_snapshot.rs @@ -94,8 +94,13 @@ pub(crate) fn read(tx: &Transaction, books: &mut Books, token: &str) -> Result Result { +pub(crate) fn event(tx: &Transaction, books: &Books, token: &str, raw: bool) -> Result { 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], diff --git a/crates/exchange/src/depth_feed.rs b/crates/exchange/src/depth_feed.rs index df70e48..aa90769 100644 --- a/crates/exchange/src/depth_feed.rs +++ b/crates/exchange/src/depth_feed.rs @@ -25,8 +25,29 @@ pub(crate) struct Request { limit: Option, } +/// 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 { + 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) -> Self { + Self { + market: market.into(), + after, + limit: Some(64), + } + } + + pub(crate) fn page(self, tx: &Transaction, books: &mut Books, raw: bool) -> Result { 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) -> Result { + 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 { if payload["op"].as_str() == Some("heartbeat") { payload diff --git a/docs/examples/market-ws.txt b/docs/examples/market-ws.txt new file mode 100644 index 0000000..978bd39 --- /dev/null +++ b/docs/examples/market-ws.txt @@ -0,0 +1,4 @@ +{"assets_ids":["eb:YES:demo"],"type":"market","initial_dump":false,"custom_feature_enabled":true} +{"assets_ids":["eb:NO:demo"],"operation":"subscribe","initial_dump":false} +{"assets_ids":["eb:YES:demo"],"operation":"unsubscribe"} +PING diff --git a/docs/prediction-parity.md b/docs/prediction-parity.md index 2b53fdb..4fa9ed1 100644 --- a/docs/prediction-parity.md +++ b/docs/prediction-parity.md @@ -299,3 +299,9 @@ order、market_sell 和卖出 estimate 可用 size_micros 输入数量,也可 `book_feed` 在同一个读事务里提供该市场的两个结果快照及本地游标。将游标作为下一次请求的 `after`,返回已提交的 `price_change` 批次。`limit` 以批次为单位,范围 1 到 500;`has_more` 指示在当前读事务中还有更多批次。客户端按同一市场保存游标,应用完整页后再推进。批次包含资产、方向、价格、最新聚合数量及当时的买一卖一。零数量删除该档,增量哈希使用协议允许的 null。外层游标与分页是本地读取接口;内部事件采用公开 SDK 的 market 事件格式。[官方市场数据事件](https://docs.polymarket.com/market-data/realtime-data.md) [回放样例](examples/depth-feed.jsonl)先在 YES 买一 0.30 美元挂两份。随后同价增加一份互补流动性、成交两份、撤掉最后一份;客户端看到该档从 2 份依次变为 3、1、0 份。每个事务只发布净变化,重复命令、已回滚命令及同事务内进入后全部成交的临时挂单不会产生额外档位。本地数据库首次升级时从现有挂单建立起点;升级前的深度变化没有回放记录。请在升级所有写入进程后启用。这里验证从快照重建买卖档位,最近成交、步长变化需使用相应行情事件;公网 WebSocket 的传播顺序和延迟仍待独立对照。 + +## 市场 WebSocket 的订阅与推送 + +`/ws/market` 使用原始行情协议的毫秒时间戳字符串和顶层 `event_type`。首次 `type: market` 订阅默认收到一组 `book`;可用 `initial_dump: false` 跳过。动态 `subscribe` 总是为新资产发送快照,重复订阅同一资产保持原进度。退订只影响当前连接。两侧同时订阅时,变化可合并在同一条 `price_change` 内;已有订阅的积压变化和新订阅的快照使用各自起点。启用 `custom_feature_enabled` 后额外发送最优档发生变化的 `best_bid_ask`,同价档量变化只发 `price_change`。协议样例采用 Eventbook 资产 ID。[官方原始帧示例](https://docs.polymarket.com/market-data/realtime-data.md) · [可重放的客户端文本帧](examples/market-ws.txt) + +本地覆盖盘口快照、档位变化、最优报价和文本心跳。最近成交、步长调整与市场生命周期的 WebSocket 事件仍待接入。初始快照使用数组发送;生产端帧分组、延迟和断线时机尚待实测。Rust 回环测试入口为 `market_socket_sends_snapshots_deltas_and_application_pongs`。