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
Generated
+65
View File
@@ -21,6 +21,12 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "ascii"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"
[[package]]
name = "bitflags"
version = "2.13.2"
@@ -64,6 +70,12 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "chunked_transfer"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901"
[[package]]
name = "cli"
version = "0.1.0"
@@ -72,6 +84,8 @@ dependencies = [
"exchange",
"serde",
"serde_json",
"serde_urlencoded",
"tiny_http",
"tungstenite",
]
@@ -157,6 +171,15 @@ version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8"
[[package]]
name = "form_urlencoded"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
dependencies = [
"percent-encoding",
]
[[package]]
name = "generic-array"
version = "0.14.7"
@@ -226,6 +249,12 @@ version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "httpdate"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "itoa"
version = "1.0.19"
@@ -287,6 +316,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pkg-config"
version = "0.3.34"
@@ -394,6 +429,12 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "ryu"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "serde"
version = "1.0.229"
@@ -437,6 +478,18 @@ dependencies = [
"zmij",
]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
dependencies = [
"form_urlencoded",
"itoa",
"ryu",
"serde",
]
[[package]]
name = "sha1"
version = "0.10.7"
@@ -515,6 +568,18 @@ dependencies = [
"syn 3.0.10",
]
[[package]]
name = "tiny_http"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82"
dependencies = [
"ascii",
"chunked_transfer",
"httpdate",
"log",
]
[[package]]
name = "tungstenite"
version = "0.28.0"
+2
View File
@@ -9,3 +9,5 @@ serde_json.workspace = true
anyhow.workspace = true
serde.workspace = true
tungstenite = "0.28"
tiny_http = "0.12"
serde_urlencoded = "0.7"
+21
View File
@@ -79,3 +79,24 @@ sequenceDiagram
```
[订阅报文样例](../../docs/examples/market-ws.txt)逐行发送为文本帧。客户端可每 10 秒发送一次 `PING`。本地按 100 毫秒间隔检查新批次,单页最多 64 个批次,每个进程最多接纳 128 个同时连接的会话。这些是本地实现参数。慢连接的网络写入在释放 Exchange 锁后进行。
## 盘口 HTTP
`cli DATABASE --market-http 127.0.0.1:9002` 启动公开盘口读取服务。可与写入会话和 WebSocket 服务共用数据库文件。[HTTP 请求样例](../../docs/examples/clob-http.http)
```mermaid
flowchart LR
main["main.rs"] --> http["market_http.rs"]
http --> api["exchange::Exchange::public_books"]
```
```mermaid
sequenceDiagram
participant C as SDK
participant H as market_http
participant E as Exchange
C->>H: GET /book?token_id=... 或 POST /books
H->>E: 提交本次请求的资产 ID
E-->>H: 一个数据库快照中的盘口列表
H-->>C: 单盘 JSON 对象或批量 JSON 数组
```
+10 -3
View File
@@ -1,3 +1,4 @@
mod market_http;
mod market_ws;
mod stream;
mod subscriptions;
@@ -11,17 +12,23 @@ use std::{
fn main() -> Result<()> {
let mut args = env::args_os().skip(1);
let usage = "usage: cli DATABASE [--market-ws HOST:PORT]";
let usage = "usage: cli DATABASE [--market-ws HOST:PORT | --market-http HOST:PORT]";
let path = args.next().context(usage)?;
if let Some(mode) = args.next() {
ensure!(mode == "--market-ws", usage);
ensure!(mode == "--market-ws" || mode == "--market-http", 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 engine = Exchange::open(path)?;
let listener = TcpListener::bind(addr)?;
return if mode == "--market-http" {
market_http::serve(engine, listener)
} else {
market_ws::serve(engine, listener)
};
}
let mut exchange = Exchange::open(path)?;
stream::serve(
+213
View File
@@ -0,0 +1,213 @@
use anyhow::Result;
use exchange::Exchange;
use serde::Deserialize;
use serde_json::{json, Value};
use std::{io::Read, net::TcpListener, sync::Mutex, thread};
use tiny_http::{Header, Method, Request, Response, Server};
const MAX_BOOKS: usize = 500;
const MAX_BODY: u64 = 1_048_576;
const MISSING: &str = "No orderbook exists for the requested token id";
#[derive(Deserialize)]
struct BookParam {
token_id: String,
// The official SDK can include a side on a BookParams item. The book contains both.
#[serde(rename = "side")]
_side: Option<Side>,
}
#[derive(Deserialize)]
#[serde(rename_all = "UPPERCASE")]
enum Side {
Buy,
Sell,
}
type Reply = std::result::Result<Value, (u16, &'static str)>;
fn query(engine: &Mutex<Exchange>, params: Vec<BookParam>, single: bool) -> Reply {
if params.len() > MAX_BOOKS || params.iter().any(|p| p.token_id.trim().is_empty()) {
return Err((400, "Invalid book request"));
}
let tokens = params.into_iter().map(|p| p.token_id).collect::<Vec<_>>();
let mut books = engine
.lock()
.map_err(|_| (500, "Order book unavailable"))?
.public_books(&tokens)
.map_err(|_| (500, "Order book unavailable"))?;
if single {
books.pop().ok_or((404, MISSING))
} else {
Ok(Value::Array(books))
}
}
fn batch(req: &mut Request, engine: &Mutex<Exchange>) -> Reply {
if req.body_length().is_some_and(|n| n as u64 > MAX_BODY) {
return Err((413, "Request body too large"));
}
let mut data = Vec::new();
req.as_reader()
.take(MAX_BODY + 1)
.read_to_end(&mut data)
.map_err(|_| (400, "Invalid request body"))?;
if data.len() as u64 > MAX_BODY {
return Err((413, "Request body too large"));
}
let params = serde_json::from_slice(&data).map_err(|_| (400, "Invalid book request"))?;
query(engine, params, false)
}
fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
let (path, params) = req.url().split_once('?').unwrap_or((req.url(), ""));
let mut allow = None;
let reply = match (req.method(), path) {
(&Method::Get, "/book") => serde_urlencoded::from_str::<BookParam>(params)
.map_err(|_| (400, "Invalid token id"))
.and_then(|p| query(engine, vec![p], true)),
(&Method::Post, "/books") => batch(&mut req, engine),
(_, "/book") => {
allow = Some("GET");
Err((405, "Method not allowed"))
}
(_, "/books") => {
allow = Some("POST");
Err((405, "Method not allowed"))
}
_ => Err((404, "Not found")),
};
let (status, body) = match reply {
Ok(v) => (200, v),
Err((status, msg)) => (status, json!({"error":msg})),
};
let mut response = Response::from_data(body.to_string().into_bytes())
.with_status_code(status)
.with_header(Header::from_bytes("Content-Type", "application/json").unwrap());
if let Some(method) = allow {
response.add_header(Header::from_bytes("Allow", method).unwrap());
}
req.respond(response)
}
pub(crate) fn serve(engine: Exchange, listener: TcpListener) -> Result<()> {
let server = Server::from_listener(listener, None).map_err(anyhow::Error::from_boxed)?;
let engine = Mutex::new(engine);
thread::scope(|scope| {
for _ in 0..4 {
scope.spawn(|| {
for req in server.incoming_requests() {
if let Err(err) = respond(req, &engine) {
eprintln!("market HTTP response: {err}");
}
}
});
}
});
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::{io::Write, net::TcpStream, time::Duration};
#[test]
fn socket_serves_single_and_batch_books_and_rejects_invalid_requests() {
let mut db = Exchange::open(":memory:").unwrap();
let market = "map 2:胜者";
db.execute(
json!({"op":"list","id":"list","market":market,"rules":"simulated","tick_size":"0.01"}),
)
.unwrap();
let yes = format!("eb:YES:{market}");
let no = format!("eb:NO:{market}");
let expected_yes = db
.execute(json!({"op":"clob_book","token_id":yes}))
.unwrap();
let expected_no = db.execute(json!({"op":"clob_book","token_id":no})).unwrap();
let max_batch = vec![json!({"token_id":yes}); MAX_BOOKS];
let too_many = vec![json!({"token_id":yes}); MAX_BOOKS + 1];
let addr = TcpListener::bind("127.0.0.1:0").unwrap();
let port = addr.local_addr().unwrap();
let server = Server::from_listener(addr, None).unwrap();
let encoded = "/book?token_id=eb%3AYES%3Amap+2%3A%E8%83%9C%E8%80%85";
let mixed = json!([
{"token_id":no}, {"token_id":"7"}, {"token_id":yes,"side":"BUY"}, {"token_id":no}
]);
let cases = [
(
"GET",
encoded,
String::new(),
200,
Some(expected_yes.clone()),
),
(
"POST",
"/books",
mixed.to_string(),
200,
Some(json!([expected_no, expected_yes, expected_no])),
),
(
"GET",
"/book?token_id=7",
String::new(),
404,
Some(json!({"error": MISSING})),
),
("GET", "/book", String::new(), 400, None),
("POST", "/books", "[]".into(), 200, Some(json!([]))),
("POST", "/books", json!(max_batch).to_string(), 200, None),
("POST", "/books", json!(too_many).to_string(), 400, None),
("POST", "/books", "{}".into(), 400, None),
(
"POST",
"/books",
r#"[{"token_id":"7","side":"INVALID"}]"#.into(),
400,
None,
),
("GET", "/books", String::new(), 405, None),
("POST", "/order", "{}".into(), 404, None),
];
let count = cases.len();
let worker = thread::spawn(move || {
let db = Mutex::new(db);
for _ in 0..count {
let req = server
.recv_timeout(Duration::from_secs(5))
.unwrap()
.unwrap();
respond(req, &db).unwrap();
}
});
for (method, path, body, status, expected) in cases {
let mut socket = TcpStream::connect(port).unwrap();
socket
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
write!(socket,"{method} {path} HTTP/1.0\r\nHost: {port}\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",body.len()).unwrap();
let mut message = String::new();
socket.read_to_string(&mut message).unwrap();
let (headers, body) = message.split_once("\r\n\r\n").unwrap();
assert_eq!(
headers.split_whitespace().nth(1).unwrap(),
status.to_string()
);
assert!(headers
.to_ascii_lowercase()
.contains("content-type: application/json"));
let actual: Value = serde_json::from_str(body).unwrap();
if let Some(expected) = expected {
assert_eq!(actual, expected);
} else if status == 200 {
assert_eq!(actual.as_array().unwrap().len(), MAX_BOOKS);
} else {
assert!(actual["error"].is_string());
}
}
worker.join().unwrap();
}
}
+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!([]));
}
+11
View File
@@ -0,0 +1,11 @@
### Run against the demo database from clob-book.jsonl
GET http://127.0.0.1:9002/book?token_id=eb%3AYES%3Ademo
### Read both outcome books in one snapshot
POST http://127.0.0.1:9002/books
Content-Type: application/json
[{"token_id":"eb:NO:demo"},{"token_id":"eb:YES:demo","side":"BUY"}]
### Unknown token
GET http://127.0.0.1:9002/book?token_id=eb%3AYES%3Amissing
+6
View File
@@ -319,3 +319,9 @@ order、market_sell 和卖出 estimate 可用 size_micros 输入数量,也可
上架时记录当时的文本,重放保留原始公告。目录数字 ID 可通过 `assets` 查询,并与最终裁决报文对应。同一命令的幂等重试和事务回滚不会重复发布。市场 slug 可在 `list` 指定,默认采用市场 ID;无父事件的盘口也可直接指定 `question`。旧数据库升级时为既有市场补目录身份,不发布历史上架消息。
官方明确要求生命周期事件启用 `custom_feature_enabled`。本地约定为有活动订阅的扩展连接推送整个目录的新盘,最终裁决按已订阅的市场推送一次。恢复一个已清空的订阅集合时,从当前目录位置开始发现。生产端新盘的广播范围、作废报文和跨市场帧顺序仍待实测。
## CLOB 盘口 HTTP 查询
`GET /book?token_id=...` 返回一个盘口。未知标的的单盘查询返回 HTTP 404,错误对象的 `error` 是 `No orderbook exists for the requested token id`。`POST /books` 接收由 `token_id` 对象组成的数组,兼容 SDK 传入的可选 `side`,每个结果均含买卖两侧。两条路径复用常驻盘口的合约字段和哈希。[官方 Python 客户端(固定版本)](https://github.com/Polymarket/py-clob-client-v2/blob/9c7c9e89cbbc11528daae90dc66ef65c9380cbdf/py_clob_client_v2/client.py) · [官方 TypeScript 客户端错误示例](https://github.com/Polymarket/clob-client#error-handling)
本地批量上限 500 项、请求体上限 1 MiB。请求内按同一个读事务取数,同步常驻盘口一次。返回值保持请求顺序与重复项,略过未知标的,空数组返回空数组。生产端混合有效与未知标的、重复标的和已终结市场的行为仍待实测。[可重放 HTTP 请求](examples/clob-http.http)