Expose paginated token price history through the public HTTP service

This commit is contained in:
2026-12-03 08:12:01 +08:00
parent 2ef0784ddc
commit 9b25fdc424
11 changed files with 292 additions and 2 deletions
+36 -2
View File
@@ -1,5 +1,5 @@
use anyhow::Result;
use exchange::Exchange;
use exchange::{Exchange, HistoryError, HistoryQuery};
use serde::Deserialize;
use serde_json::{json, Value};
use std::{io::Read, net::TcpListener, sync::Mutex, thread};
@@ -69,12 +69,16 @@ fn batch(req: &mut Request, engine: &Mutex<Exchange>) -> Reply {
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(&mut req, engine),
(_, "/book") => {
(_, "/book" | "/v2/prices-history") => {
allow = Some("GET");
Err((405, "Method not allowed"))
}
@@ -88,6 +92,32 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
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());
@@ -182,6 +212,10 @@ mod tests {
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),
];