Serve single and batch CLOB order books over HTTP
This commit is contained in:
+10
-3
@@ -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(
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user