Deduplicate public book batches and validate item fields
This commit is contained in:
@@ -423,3 +423,5 @@ sequenceDiagram
|
||||
E-->>H: true
|
||||
H-->>C: 200,neg_risk 为真
|
||||
```
|
||||
|
||||
批量盘口 POST /books 的响应使用 asset_id 对应请求。重复资产只返回一份,单批最多 500 个不同标识。
|
||||
|
||||
@@ -3,7 +3,7 @@ use exchange::{Exchange, HistoryError};
|
||||
use percent_encoding::percent_decode_str;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::{io::Read, net::TcpListener, sync::Mutex, thread};
|
||||
use std::{collections::HashSet, io::Read, net::TcpListener, sync::Mutex, thread};
|
||||
use tiny_http::{Header, Method, Request, Response, Server};
|
||||
|
||||
const MAX_BOOKS: usize = 500;
|
||||
@@ -18,20 +18,15 @@ struct BookParam {
|
||||
_side: Option<exchange::PriceSide>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct BatchBookParam {
|
||||
token_id: Option<String>,
|
||||
side: Option<String>,
|
||||
}
|
||||
|
||||
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<_>>();
|
||||
fn book_response(engine: &Mutex<Exchange>, tokens: Vec<String>, single: bool) -> Reply {
|
||||
let mut books = engine
|
||||
.lock()
|
||||
.map_err(|_| (500, "error getting the orderbook"))?
|
||||
@@ -439,10 +434,36 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
(&Method::Get, "/midpoints") => Err((400, "Invalid payload")),
|
||||
(&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))
|
||||
}
|
||||
.and_then(|p| {
|
||||
if p.token_id.trim().is_empty() {
|
||||
return Err((400, "Invalid token id"));
|
||||
}
|
||||
book_response(engine, vec![p.token_id], true)
|
||||
}),
|
||||
(&Method::Post, "/books") => batch_params::<BatchBookParam>(&mut req).and_then(|rows| {
|
||||
let mut seen = HashSet::new();
|
||||
let mut tokens = Vec::new();
|
||||
for row in &rows {
|
||||
let Some(token) = row.token_id.as_deref().filter(|id| !id.trim().is_empty()) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(side) = row.side.as_deref() {
|
||||
if !side.is_empty()
|
||||
&& !side.eq_ignore_ascii_case("BUY")
|
||||
&& !side.eq_ignore_ascii_case("SELL")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if seen.insert(token) {
|
||||
if seen.len() > MAX_BOOKS {
|
||||
return Err((400, "Payload exceeds the limit"));
|
||||
}
|
||||
tokens.push(token.to_owned());
|
||||
}
|
||||
}
|
||||
book_response(engine, tokens, 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)),
|
||||
@@ -819,7 +840,7 @@ mod tests {
|
||||
"/books",
|
||||
mixed.to_string(),
|
||||
200,
|
||||
Some(json!([expected_no, expected_yes, expected_no])),
|
||||
Some(json!([expected_no, expected_yes])),
|
||||
),
|
||||
(
|
||||
"GET",
|
||||
@@ -830,8 +851,11 @@ mod tests {
|
||||
),
|
||||
("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", json!(max_batch).to_string(), 200, Some(json!([expected_yes]))),
|
||||
("POST", "/books", json!(too_many).to_string(), 200, Some(json!([expected_yes]))),
|
||||
("POST", "/books", json!((0..=MAX_BOOKS).map(|i| json!({"token_id": i.to_string()})).collect::<Vec<_>>()).to_string(), 400, Some(json!({"error":"Payload exceeds the limit"}))),
|
||||
("POST", "/books", json!([{"token_id":""},{"side":"BUY"},{"token_id":yes,"side":"invalid"},{"token_id":no,"side":"sell"}]).to_string(), 200, Some(json!([expected_no]))),
|
||||
("POST", "/books", json!([{"token_id":123}]).to_string(), 400, Some(json!({"error":"Invalid payload"}))),
|
||||
(
|
||||
"POST",
|
||||
"/books",
|
||||
@@ -843,8 +867,8 @@ mod tests {
|
||||
"POST",
|
||||
"/books",
|
||||
r#"[{"token_id":"7","side":"INVALID"}]"#.into(),
|
||||
400,
|
||||
None,
|
||||
200,
|
||||
Some(json!([])),
|
||||
),
|
||||
("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}}))),
|
||||
|
||||
Reference in New Issue
Block a user