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

704 lines
31 KiB
Rust

use anyhow::Result;
use exchange::{Exchange, HistoryError, HistoryQuery};
use percent_encoding::percent_decode_str;
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<exchange::PriceSide>,
}
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))
}
}
#[derive(Clone, Copy)]
enum QuoteField {
Spread,
Midpoint,
}
fn quote_response(
engine: &Mutex<Exchange>,
tokens: Vec<String>,
field: QuoteField,
single: bool,
) -> Reply {
let internal_error = match field {
QuoteField::Spread => (500, "error getting the spread"),
QuoteField::Midpoint => (500, "error getting the midpoint"),
};
let exchange = engine.lock().map_err(|_| internal_error)?;
let rows = match field {
QuoteField::Spread => exchange.spreads(&tokens),
QuoteField::Midpoint => exchange.midpoints(&tokens),
}
.map_err(|error| match error {
exchange::MarketDataError::Invalid(_) if single => (400, "Invalid token id"),
exchange::MarketDataError::Invalid(_) => (400, "Invalid payload"),
exchange::MarketDataError::Unavailable => internal_error,
})?;
if single {
let value = rows
.into_values()
.next()
.ok_or((404, MISSING))?
.ok_or((422, "Two-sided quote unavailable"))?;
return Ok(match field {
QuoteField::Spread => json!({"spread":value}),
QuoteField::Midpoint => json!({"mid":value}),
});
}
let result = rows
.into_iter()
.filter_map(|(id, value)| value.map(|s| (id, Value::String(s))))
.collect();
Ok(Value::Object(result))
}
#[derive(Deserialize)]
struct WirePrice {
token_id: String,
side: Option<String>,
}
impl WirePrice {
fn into_request(self) -> std::result::Result<exchange::PriceRequest, (u16, &'static str)> {
let side = match self.side.as_deref() {
Some("BUY") => exchange::PriceSide::Buy,
Some("SELL") => exchange::PriceSide::Sell,
_ => return Err((400, "Invalid side")),
};
Ok(exchange::PriceRequest {
token_id: self.token_id,
side,
})
}
}
#[derive(Deserialize)]
struct PriceList {
token_ids: String,
sides: String,
}
impl PriceList {
fn into_rows(self) -> std::result::Result<Vec<WirePrice>, (u16, &'static str)> {
let tokens = self.token_ids.split(',');
let sides = self.sides.split(',');
let count = tokens.clone().count();
if count > MAX_BOOKS || count != sides.clone().count() {
return Err((400, "Invalid payload"));
}
Ok(tokens
.zip(sides)
.map(|(token, side)| WirePrice {
token_id: token.to_owned(),
side: Some(side.to_owned()),
})
.collect())
}
}
fn execution_prices(engine: &Mutex<Exchange>, rows: Vec<WirePrice>, single: bool) -> Reply {
if rows.is_empty() || rows.len() > MAX_BOOKS {
return Err((400, "Invalid payload"));
}
let requests = rows
.into_iter()
.map(WirePrice::into_request)
.collect::<std::result::Result<Vec<_>, _>>()?;
let exchange = engine.lock().map_err(|_| (500, "Internal server error"))?;
let value = if single {
exchange.execution_price(&requests[0])
} else {
exchange.execution_prices(&requests)
}
.map_err(
|error| match error.downcast_ref::<exchange::PriceQueryError>() {
Some(exchange::PriceQueryError::InvalidToken) if single => (400, "Invalid token id"),
Some(exchange::PriceQueryError::MissingBook) => (404, MISSING),
Some(_) => (400, "Invalid payload"),
None => (500, "Internal server error"),
},
)?;
if single && value["price"].is_null() {
return Err((422, "No price available for requested side"));
}
Ok(value)
}
fn batch_params<T: serde::de::DeserializeOwned>(
req: &mut Request,
) -> std::result::Result<Vec<T>, (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 {
Ok(match rows.pop() {
Some(row) => json!({"price":row["price"],"side":row["side"]}),
None => json!({"price":"0.5","side":""}),
})
} else {
Ok(Value::Array(rows))
}
}
#[derive(Deserialize)]
struct TokenQuery {
token_id: String,
}
fn tick_size(engine: &Mutex<Exchange>, params: &str, segment: Option<&str>) -> Reply {
let invalid = (400, "Invalid token id");
let token = match segment {
Some(raw) => percent_decode_str(raw).decode_utf8().map_err(|_| invalid)?,
None => serde_urlencoded::from_str::<TokenQuery>(params)
.map_err(|_| invalid)?
.token_id
.into(),
};
let size = engine
.lock()
.map_err(|_| (500, "Internal server error"))?
.minimum_tick_size(&token)
.map_err(|e| match e {
exchange::MarketDataError::Invalid(_) => invalid,
exchange::MarketDataError::Unavailable => (500, "Internal server error"),
})?
.ok_or((404, "market not found"))?;
Ok(json!({"minimum_tick_size":size}))
}
fn market_lookup(engine: &Mutex<Exchange>, prefix: &str, raw: &str) -> Reply {
let is_token = prefix == "markets-by-token";
let invalid = if is_token {
"Invalid token id"
} else {
"Invalid condition id"
};
let id = percent_decode_str(raw)
.decode_utf8()
.map_err(|_| (400, invalid))?;
let exchange = engine.lock().map_err(|_| (500, "Internal server error"))?;
let info = if is_token {
exchange.market_by_token(&id)
} else {
exchange.clob_market_info(&id)
};
info.map_err(|e| match e {
exchange::MarketDataError::Invalid(_) => (400, invalid),
exchange::MarketDataError::Unavailable => (500, "Internal server error"),
})?
.ok_or((if is_token { 404 } else { 400 }, "market not found"))
}
fn clarifications(engine: &Mutex<Exchange>, query: &str) -> Reply {
let invalid = (400, "Invalid clarification query");
let fields: Vec<(String, String)> = serde_urlencoded::from_str(query).map_err(|_| invalid)?;
let mut ids = Vec::new();
let mut events = Vec::new();
let mut limit = 20;
let mut offset = 0;
let mut ascending = false;
for (key, value) in fields {
match key.as_str() {
"event_id" => events.push(value.parse().map_err(|_| invalid)?),
"market_id" => ids.push(value.parse().map_err(|_| invalid)?),
"limit" => limit = value.parse().map_err(|_| invalid)?,
"offset" => offset = value.parse().map_err(|_| invalid)?,
"ascending" => ascending = value.parse().map_err(|_| invalid)?,
"order" if value == "id" => {}
_ => return Err(invalid),
}
}
let rows = engine
.lock()
.map_err(|_| (500, "Internal server error"))?
.filtered_market_clarifications(&ids, &events, limit, offset, ascending)
.map_err(|e| match e {
exchange::MarketDataError::Invalid(_) => invalid,
exchange::MarketDataError::Unavailable => (500, "Internal server error"),
})?;
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 tick_segment = path
.strip_prefix("/tick-size/")
.filter(|s| !s.contains('/'));
let is_tick_route = path == "/tick-size" || tick_segment.is_some();
let lookup = path
.strip_prefix('/')
.and_then(|p| p.split_once('/'))
.filter(|(prefix, id)| {
matches!(*prefix, "markets-by-token" | "clob-markets") && !id.contains('/')
});
if let Some((prefix, id)) = lookup {
if req.method() != &Method::Get {
return send(req, 405, json!({"error":"Method not allowed"}), Some("GET"));
}
let (status, body) = match market_lookup(engine, prefix, id) {
Ok(value) => (200, value),
Err((status, msg)) => (status, json!({"error":msg})),
};
return send(req, status, body, None);
}
let reply = match (req.method(), path) {
(&Method::Get, _) if is_tick_route => tick_size(engine, params, tick_segment),
(_, _) if is_tick_route => {
allow = Some("GET");
Err((405, "Method not allowed"))
}
(&Method::Get, "/market-clarifications") => clarifications(engine, params),
(&Method::Get, "/prices-history") => {
let result = serde_urlencoded::from_str::<exchange::ClobHistoryQuery>(params)
.map_err(|_| HistoryError::Invalid("invalid query parameters".into()))
.and_then(|query| {
engine
.lock()
.map_err(|_| HistoryError::Unavailable)?
.clob_price_history(query)
});
match result {
Ok(history) => Ok(history),
Err(HistoryError::Invalid(message)) => {
return send(req, 400, json!({"error":message}), None)
}
Err(HistoryError::Unavailable) => Err((500, "Internal server error")),
}
}
(&Method::Get, "/price") => serde_urlencoded::from_str::<WirePrice>(params)
.map_err(|_| (400, "Invalid token id"))
.and_then(|p| execution_prices(engine, vec![p], true)),
(&Method::Post, "/prices") => batch_params::<WirePrice>(&mut req)
.and_then(|rows| execution_prices(engine, rows, false)),
(&Method::Get, "/prices") => serde_urlencoded::from_str::<PriceList>(params)
.map_err(|_| (400, "Invalid payload"))
.and_then(PriceList::into_rows)
.and_then(|rows| execution_prices(engine, rows, false)),
(&Method::Get, "/spread" | "/midpoint") => {
let field = if path == "/spread" {
QuoteField::Spread
} else {
QuoteField::Midpoint
};
serde_urlencoded::from_str::<BookParam>(params)
.map_err(|_| (400, "Invalid token id"))
.and_then(|p| quote_response(engine, vec![p.token_id], field, true))
}
(&Method::Post, "/spreads" | "/midpoints") => {
let field = if path == "/spreads" {
QuoteField::Spread
} else {
QuoteField::Midpoint
};
batch_params::<BookParam>(&mut req).and_then(|p| {
quote_response(
engine,
p.into_iter().map(|b| b.token_id).collect(),
field,
false,
)
})
}
(&Method::Get, "/midpoints") => serde_urlencoded::from_str::<TokenList>(params)
.map_err(|_| (400, "Invalid payload"))
.and_then(|p| {
quote_response(
engine,
p.token_ids.split(',').map(str::to_owned).collect(),
QuoteField::Midpoint,
false,
)
}),
(&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::<BookParam>(&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::<BookParam>(&mut req).and_then(|p| {
last_prices(
engine,
p.into_iter().map(|item| item.token_id).collect(),
false,
)
})
}
(_, "/prices" | "/last-trades-prices" | "/midpoints") => {
allow = Some("GET, POST");
Err((405, "Method not allowed"))
}
(
_,
"/price"
| "/midpoint"
| "/spread"
| "/book"
| "/last-trade-price"
| "/prices-history"
| "/market-clarifications"
| "/v2/prices-history",
) => {
allow = Some("GET");
Err((405, "Method not allowed"))
}
(_, "/books" | "/spreads") => {
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();
db.execute(json!({"op":"list","id":"path-market","market":"map+2/1","rules":"simulation","tick_size":"0.0025"})).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!([]);
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 tick_query = encoded.replacen("/book?", "/tick-size?", 1);
let lookup_pair = json!({"condition_id":"map+2/1","primary_token_id":"eb:YES:map+2/1","secondary_token_id":"eb:NO:map+2/1"});
let lookup_info = json!({"gst":null,"nr":false,"rfqe":false,"ibce":false,"oas":0,"mos":0.01,"mts":0.0025,
"t":[{"o":"YES","t":"eb:YES:map+2/1"},{"o":"NO","t":"eb:NO:map+2/1"}]});
for command in [
json!({"op":"list","id":"s-list","market":"s","rules":"spread fixture"}),
json!({"op":"open","id":"s-open","market":"s"}),
json!({"op":"fund","id":"s-f1","account":"a","cents":100}),
json!({"op":"fund","id":"s-f2","account":"b","cents":100}),
json!({"op":"order","id":"s-bid","asset_id":"eb:YES:s","account":"a","side":"buy","price":39,"qty":1}),
json!({"op":"list","id":"one-list","market":"one","rules":"one-sided fixture"}),
json!({"op":"open","id":"one-open","market":"one"}),
json!({"op":"order","id":"one-bid","asset_id":"eb:YES:one","account":"b","side":"buy","price":20,"qty":1}),
json!({"op":"order","id":"s-comp","asset_id":"eb:NO:s","account":"b","side":"buy","price":59,"qty":1}),
] {
db.execute(command).unwrap();
}
for line in include_str!("../../../docs/examples/midpoint.jsonl").lines() {
db.execute(serde_json::from_str(line).unwrap()).unwrap();
}
let sample = json!({"eb:YES:mid-example":"0.085","eb:NO:mid-example":"0.915"});
let pair = json!({"eb:YES:s":"0.4","eb:NO:s":"0.6"});
let price_batch =
json!({"eb:YES:mid-example":{"BUY":0.09,"SELL":0.08},"eb:NO:mid-example":{"BUY":0.92}});
db.execute(json!({"op":"publish_clarification","id":"note","market":market,"content":"Map one includes overtime.","clear_book":false})).unwrap();
let note = db
.execute(json!({"op":"resolution","market":market}))
.unwrap()["clarifications"]
.clone();
let note_id = note[0]["marketId"].as_i64().unwrap();
let note_query = format!(
"/market-clarifications?market_id=9999&market_id={note_id}&order=id&ascending=true"
);
let cases = [
("GET","/market-clarifications?event_id=1&event_id=2",String::new(),200,Some(json!([]))),
("GET","/market-clarifications?event_id=0",String::new(),400,None),
("GET",note_query.as_str(),String::new(),200,Some(note)),
("GET","/market-clarifications?limit=0",String::new(),200,Some(json!([]))),
("GET","/market-clarifications?offset=1",String::new(),200,Some(json!([]))),
("GET","/market-clarifications?limit=101",String::new(),400,None),
("POST","/market-clarifications","{}".into(),405,None),
("GET","/prices-history?market=eb:YES:s&interval=1h&fidelity=10",String::new(),200,Some(json!({"history":[]}))),
("GET","/prices-history?market=eb:NO:s&startTs=1000&endTs=2000",String::new(),200,Some(json!({"history":[]}))),
("GET","/prices-history?market=eb:YES:s&startTs=1000",String::new(),400,None),
("GET","/prices-history?market=eb:YES:s&interval=1d&fidelity=0",String::new(),400,None),
("GET","/prices-history?market=eb:YES:s&startTs=1&endTs=2&interval=max",String::new(),400,None),
("POST","/prices-history","{}".into(),405,None),
("GET","/price?token_id=eb:YES:mid-example&side=BUY",String::new(),200,Some(json!({"price":"0.09"}))),
("GET","/price?token_id=eb:YES:mid-example&side=SELL",String::new(),200,Some(json!({"price":"0.08"}))),
("GET","/price?token_id=eb:YES:one&side=SELL",String::new(),200,Some(json!({"price":"0.20"}))),
("GET","/price?token_id=eb:YES:one&side=BUY",String::new(),422,None),
("GET","/price?token_id=eb:YES:missing&side=BUY",String::new(),404,Some(json!({"error":MISSING}))),
("GET","/price?token_id=eb:YES:s&side=HOLD",String::new(),400,Some(json!({"error":"Invalid side"}))),
("GET","/price?token_id=broken&side=BUY",String::new(),400,Some(json!({"error":"Invalid token id"}))),
("GET","/prices?token_ids=eb:YES:mid-example,eb:YES:mid-example,eb:NO:mid-example&sides=BUY,SELL,BUY",String::new(),200,Some(price_batch.clone())),
("POST","/prices",json!([{"token_id":"eb:YES:mid-example","side":"BUY"},{"token_id":"eb:NO:mid-example","side":"BUY"},{"token_id":"eb:YES:mid-example","side":"SELL"},{"token_id":"eb:YES:one","side":"BUY"},{"token_id":"eb:YES:mid-example","side":"BUY"}]).to_string(),200,Some(price_batch)),
("GET","/prices?token_ids=eb:YES:s,eb:NO:s&sides=BUY",String::new(),400,Some(json!({"error":"Invalid payload"}))),
("POST","/prices",json!([{"token_id":"eb:YES:s","side":"BUY"},{"token_id":"eb:NO:missing","side":"SELL"}]).to_string(),404,Some(json!({"error":MISSING}))),
("POST","/prices",json!([{"token_id":"eb:YES:s"}]).to_string(),400,Some(json!({"error":"Invalid side"}))),
("POST","/prices",json!(vec![json!({"token_id":"eb:YES:s","side":"BUY"}); MAX_BOOKS+1]).to_string(),400,None),
("DELETE","/prices",String::new(),405,None),
("GET","/midpoint?token_id=eb:YES:mid-example",String::new(),200,Some(json!({"mid":"0.085"}))),
("POST","/midpoints",json!([{"token_id":"eb:YES:mid-example"},{"token_id":"eb:NO:mid-example"}]).to_string(),200,Some(sample)),
("GET","/midpoint?token_id=eb:YES:s",String::new(),200,Some(json!({"mid":"0.4"}))),
("GET","/midpoints?token_ids=eb:YES:s%2Ceb:NO:s",String::new(),200,Some(pair.clone())),
("POST","/midpoints",json!([{"token_id":"eb:NO:s","side":"BUY"},{"token_id":"eb:YES:one"},{"token_id":"eb:YES:s"},{"token_id":"eb:YES:s"}]).to_string(),200,Some(pair)),
("GET","/midpoint?token_id=eb:NO:one",String::new(),422,None),
("GET","/midpoint?token_id=eb:YES:missing",String::new(),404,None),
("GET","/midpoint",String::new(),400,None),
("POST","/midpoints",json!(too_many).to_string(),400,None),
("DELETE","/midpoints",String::new(),405,None),
("GET","/spread?token_id=eb:YES:s",String::new(),200,Some(json!({"spread":"0.02"}))),
("POST","/spreads",json!([{"token_id":"eb:YES:s"},{"token_id":"eb:NO:s","side":"SELL"},{"token_id":"eb:YES:s"},{"token_id":yes}]).to_string(),200,Some(json!({"eb:YES:s":"0.02","eb:NO:s":"0.02"}))),
("GET","/spread?token_id=eb:NO:one",String::new(),422,Some(json!({"error":"Two-sided quote unavailable"}))),
("GET","/spread?token_id=eb:YES:missing",String::new(),404,Some(json!({"error":MISSING}))),
("GET","/spread?token_id=eb:YES:map%2B2%2F1",String::new(),422,Some(json!({"error":"Two-sided quote unavailable"}))),
("POST","/spreads",json!(too_many).to_string(),400,None),
("GET","/spreads",String::new(),405,None),
("GET","/markets-by-token/eb:NO:map+2%2F1",String::new(),200,Some(lookup_pair)),
("GET","/clob-markets/map+2%2F1",String::new(),200,Some(lookup_info)),
("GET","/markets-by-token/eb:YES:missing",String::new(),404,None),
("GET","/markets-by-token/garbage",String::new(),400,None),
("GET","/clob-markets/missing",String::new(),400,None),
("POST","/clob-markets/map+2%2F1","{}".into(),405,None),
("GET",tick_query.as_str(),String::new(),200,Some(json!({"minimum_tick_size":0.01}))),
("GET","/tick-size/eb%3ANO%3Amap%202%3A%E8%83%9C%E8%80%85",String::new(),200,Some(json!({"minimum_tick_size":0.01}))),
("GET","/tick-size/eb:YES:map+2%2F1",String::new(),200,Some(json!({"minimum_tick_size":0.0025}))),
("GET","/tick-size?token_id=eb%3AYES%3Amap%2B2%2F1",String::new(),200,Some(json!({"minimum_tick_size":0.0025}))),
("GET","/tick-size/eb:YES:missing",String::new(),404,Some(json!({"error":"market not found"}))),
("GET","/tick-size/",String::new(),400,Some(json!({"error":"Invalid token id"}))),
("GET","/tick-size/eb:YES:%FF",String::new(),400,Some(json!({"error":"Invalid token id"}))),
("GET","/tick-size",String::new(),400,Some(json!({"error":"Invalid token id"}))),
("POST","/tick-size/eb:YES:e",String::new(),405,None),
("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();
}
}