Files
eventbook-exchange/crates/cli/src/market_http.rs
T

318 lines
12 KiB
Rust

use anyhow::Result;
use exchange::{Exchange, HistoryError, HistoryQuery};
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,
if single {
"Invalid token id"
} else {
"Invalid payload"
},
));
}
let tokens = params.into_iter().map(|p| p.token_id).collect::<Vec<_>>();
let mut books = engine
.lock()
.map_err(|_| (500, "error getting the orderbook"))?
.public_books(&tokens)
.map_err(|_| (500, "error getting the orderbook"))?;
if single {
books.pop().ok_or((404, MISSING))
} else {
Ok(Value::Array(books))
}
}
fn batch_params(req: &mut Request) -> std::result::Result<Vec<BookParam>, (u16, &'static str)> {
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 payload"))?;
if data.len() as u64 > MAX_BODY {
return Err((413, "Request body too large"));
}
serde_json::from_slice(&data).map_err(|_| (400, "Invalid payload"))
}
#[derive(Deserialize)]
struct TokenList {
token_ids: String,
}
fn last_prices(engine: &Mutex<Exchange>, tokens: Vec<String>, single: bool) -> Reply {
let mut rows = engine
.lock()
.map_err(|_| (500, "Internal server error"))?
.last_trade_prices(&tokens)
.map_err(|e| match e {
exchange::MarketDataError::Invalid(_) if single => (400, "Invalid token id"),
exchange::MarketDataError::Invalid(_) => (400, "Invalid payload"),
exchange::MarketDataError::Unavailable => (500, "Internal server error"),
})?;
if single {
let row = rows.pop().ok_or((500, "Internal server error"))?;
Ok(json!({"price":row["price"],"side":row["side"]}))
} else {
Ok(Value::Array(rows))
}
}
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;
if req.method() == &Method::Get && path == "/v2/prices-history" {
let (status, body) = history(params, engine);
return send(req, status, body, 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_params(&mut req).and_then(|p| query(engine, p, false)),
(&Method::Get, "/last-trade-price") => serde_urlencoded::from_str::<BookParam>(params)
.map_err(|_| (400, "Invalid token id"))
.and_then(|p| last_prices(engine, vec![p.token_id], true)),
(&Method::Get, "/last-trades-prices") => serde_urlencoded::from_str::<TokenList>(params)
.map_err(|_| (400, "Invalid payload"))
.and_then(|p| {
last_prices(
engine,
p.token_ids.split(',').map(str::to_owned).collect(),
false,
)
}),
(&Method::Post, "/last-trades-prices") => batch_params(&mut req).and_then(|p| {
last_prices(
engine,
p.into_iter().map(|item| item.token_id).collect(),
false,
)
}),
(_, "/last-trades-prices") => {
allow = Some("GET, POST");
Err((405, "Method not allowed"))
}
(_, "/book" | "/last-trade-price" | "/v2/prices-history") => {
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})),
};
send(req, status, body, allow)
}
fn history(params: &str, engine: &Mutex<Exchange>) -> (u16, Value) {
let page = serde_urlencoded::from_str::<HistoryQuery>(params)
.map_err(|_| HistoryError::Invalid("invalid query parameters".to_owned()))
.and_then(|query| {
engine
.lock()
.map_err(|_| HistoryError::Unavailable)?
.public_price_history(query)
});
match page {
Ok(data) => (200, data),
Err(HistoryError::Invalid(message)) => (
400,
json!({"code":"invalid_request","error":message,"retryable":false}),
),
Err(HistoryError::Unavailable) => (
500,
json!({"code":"internal_error","error":"history unavailable","retryable":true}),
),
}
}
fn send(req: Request, status: u16, body: Value, allow: Option<&str>) -> std::io::Result<()> {
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 no_fills = json!({"price":"0.5","side":""});
let batch_no_fills = json!([{"token_id":yes,"price":"0.5","side":""},
{"token_id":no,"price":"0.5","side":""}]);
let csv = serde_urlencoded::to_string([("token_ids", format!("{yes},{no}"))]).unwrap();
let last_batch = format!("/last-trades-prices?{csv}");
let last_single = encoded.replacen("/book?", "/last-trade-price?", 1);
let cases = [
("GET",last_single.as_str(),String::new(),200,Some(no_fills)),
("GET",last_batch.as_str(),String::new(),200,Some(batch_no_fills.clone())),
("POST","/last-trades-prices",json!([{"token_id":yes,"side":"SELL"},{"token_id":no}]).to_string(),200,Some(batch_no_fills)),
("GET","/last-trade-price?token_id=",String::new(),400,Some(json!({"error":"Invalid token id"}))),
("POST","/last-trades-prices",json!(too_many).to_string(),400,Some(json!({"error":"Invalid payload"}))),
("DELETE","/last-trades-prices",String::new(),405,None),
(
"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,
Some(json!({"error":"Invalid payload"})),
),
(
"POST",
"/books",
r#"[{"token_id":"7","side":"INVALID"}]"#.into(),
400,
None,
),
("GET", "/v2/prices-history?tokenId=eb%3AYES%3Amap+2%3A%E8%83%9C%E8%80%85&interval=1h&bucketSeconds=60", String::new(), 200,
Some(json!({"data":[],"pagination":{"has_more":false,"next_cursor":null,"offset":0,"limit":10000}}))),
("GET","/v2/prices-history?token_id=7&interval=1h",String::new(),400,None),
("POST","/v2/prices-history",String::new(),405,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();
}
}