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
+22
View File
@@ -100,3 +100,25 @@ sequenceDiagram
E-->>H: 一个数据库快照中的盘口列表
H-->>C: 单盘 JSON 对象或批量 JSON 数组
```
同一个 HTTP 监听器提供 `GET /v2/prices-history`。客户端按资产查询历史,接续页可以只发同一资产和上一页的游标。[请求样例](../../docs/examples/clob-http.http)
```mermaid
flowchart LR
main["main.rs"] --> http["market_http.rs"]
http --> history["exchange::HistoryQuery"]
```
```mermaid
sequenceDiagram
participant C as 图表客户端
participant H as market_http
participant E as Exchange
C->>H: GET /v2/prices-history 含资产与窗口
H->>E: 查询历史点与分页状态
E-->>H: data 与 pagination
H-->>C: JSON 中的 next_cursor
C->>H: 同一 token_id 和 cursor
H->>E: 读取该窗口下一页
E-->>C: 后续点及是否还有数据
```
+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),
];
+1
View File
@@ -9,6 +9,7 @@ anyhow.workspace = true
serde.workspace = true
serde_json = { workspace = true, features = ["arbitrary_precision"] }
rusqlite.workspace = true
data-encoding = "2"
sha1 = "0.10"
[dev-dependencies]
+25
View File
@@ -980,3 +980,28 @@ sequenceDiagram
end
E-->>H: 结束读事务并返回数组
```
### 图表客户端读取历史
```mermaid
flowchart LR
http["cli/market_http.rs"] --> wire["prices_history/http.rs"]
wire --> ids["assets.rs"]
wire --> history["prices_history.rs"]
history --> sql["prices_history.sql"]
```
```mermaid
sequenceDiagram
participant H as HTTP 服务
participant W as prices_history/http.rs
participant R as prices_history.rs
participant D as SQLite
H->>W: token_id、窗口或游标
W->>W: 校验资产、恢复首次查询的窗口与页大小
W->>R: 查询一页或 as_of 时点
R->>D: 按窗口、成交与裁决序号上限读取
D-->>R: 升序价格点及精度
R-->>W: 数据与内部继续位置
W-->>H: 公开点字段、偏移和 URL 安全的继续游标
```
+1
View File
@@ -45,6 +45,7 @@ use std::{path::Path, time::Duration};
pub use assets::parse_id as parse_asset_id;
pub use depth_feed::MarketPage;
pub use prices_history::http::{HistoryError, HistoryQuery};
pub struct Exchange {
db: Connection,
+3
View File
@@ -1,3 +1,4 @@
pub(crate) mod http;
use anyhow::{bail, ensure, Result};
use rusqlite::{params, Connection, Row};
use serde::{Deserialize, Serialize};
@@ -124,6 +125,8 @@ impl Request {
&& self.interval.is_none()
&& self.bucket_seconds.is_none()
&& self.limit.is_none()
&& cursor.fill_cap >= 0
&& cursor.settlement_cap >= 0
&& cursor.market == self.market
&& cursor.outcome == self.outcome
&& cursor.start >= 0
+142
View File
@@ -0,0 +1,142 @@
use super::{Cursor, Request};
use crate::{assets, Exchange};
use anyhow::{ensure, Context, Result};
use data_encoding::BASE64URL_NOPAD;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
#[derive(Deserialize)]
pub struct HistoryQuery {
#[serde(alias = "tokenId")]
token_id: String,
start: Option<i64>,
end: Option<i64>,
interval: Option<String>,
#[serde(alias = "bucketSeconds")]
bucket_seconds: Option<i64>,
#[serde(alias = "asOf")]
as_of: Option<i64>,
limit: Option<u32>,
cursor: Option<String>,
}
#[derive(Deserialize, Serialize)]
struct Continuation {
page: Cursor,
offset: u64,
// Clients may resend the original window with their cursor.
start: Option<i64>,
end: Option<i64>,
interval: Option<String>,
bucket_seconds: Option<i64>,
}
#[derive(Debug)]
pub enum HistoryError {
Invalid(String),
Unavailable,
}
impl Exchange {
pub fn public_price_history(&self, query: HistoryQuery) -> Result<Value, HistoryError> {
let tx = self
.db
.unchecked_transaction()
.map_err(|_| HistoryError::Unavailable)?;
let response = query.read(&tx).map_err(|err| {
if err.downcast_ref::<rusqlite::Error>().is_some() {
HistoryError::Unavailable
} else {
HistoryError::Invalid(err.to_string())
}
})?;
tx.commit().map_err(|_| HistoryError::Unavailable)?;
Ok(response)
}
}
impl HistoryQuery {
fn read(mut self, db: &rusqlite::Connection) -> Result<Value> {
let (outcome, market) = assets::parse_id(&self.token_id)?;
let mut offset: u64 = 0;
let mut page_size = self.limit.unwrap_or(10000);
let mut request = Request {
market: market.to_owned(),
outcome: outcome.to_owned(),
start: self.start,
end: self.end,
interval: self.interval.clone(),
bucket_seconds: self.bucket_seconds,
as_of: self.as_of,
limit: self.limit,
cursor: None,
};
if let Some(encoded) = self.cursor {
let unpack = || -> Option<Continuation> {
serde_json::from_slice(&BASE64URL_NOPAD.decode(encoded.as_bytes()).ok()?).ok()
};
let prior = unpack().context("invalid cursor")?;
ensure!(
self.as_of.is_none()
&& self.start.is_none_or(|n| Some(n) == prior.start)
&& self.end.is_none_or(|n| Some(n) == prior.end)
&& self
.interval
.as_ref()
.is_none_or(|s| Some(s) == prior.interval.as_ref())
&& self
.bucket_seconds
.is_none_or(|n| Some(n) == prior.bucket_seconds),
"window differs from cursor"
);
offset = prior.offset;
page_size = prior.page.limit;
self.start = prior.start;
self.end = prior.end;
self.interval = prior.interval;
self.bucket_seconds = prior.bucket_seconds;
request.start = None;
request.end = None;
request.interval = None;
request.bucket_seconds = None;
request.limit = None;
request.cursor = Some(prior.page);
} else if page_size == 0 {
// A zero-sized first page cannot advance a cursor. Validate the window first.
request.limit = if self.as_of.is_some() { None } else { Some(1) };
} else if self.as_of.is_some() {
ensure!(page_size <= 10000, "invalid limit");
request.limit = None;
}
let mut result = request.read(db)?;
let data = result["data"]
.as_array_mut()
.context("invalid history page")?;
for point in data.iter_mut() {
if let Some(fields) = point.as_object_mut() {
fields.remove("source");
}
}
if page_size == 0 {
data.clear();
}
let count = data.len() as u64;
let next = &result["pagination"]["next_cursor"];
let cursor = if next.is_null() || page_size == 0 {
None
} else {
let carry = Continuation {
page: serde_json::from_value(next.clone())?,
offset: offset.checked_add(count).context("invalid cursor offset")?,
start: self.start,
end: self.end,
interval: self.interval,
bucket_seconds: self.bucket_seconds,
};
Some(BASE64URL_NOPAD.encode(&serde_json::to_vec(&carry)?))
};
Ok(json!({"data":result["data"].take(),"pagination":{
"has_more":cursor.is_some(),"next_cursor":cursor,"limit":page_size,"offset":offset
}}))
}
}
+49
View File
@@ -1529,6 +1529,26 @@ fn prices_history_keeps_the_terminal_tick_and_pins_pages_before_settlement() {
point(245, 0.55, 0, "trade")
])
);
let wire = |engine: &Exchange, params: Value| {
engine.public_price_history(serde_json::from_value(params).unwrap())
};
let first_wire = wire(
&e,
json!({"tokenId":"eb:YES:e","start":120,"end":290,"bucketSeconds":60,"limit":1}),
)
.unwrap();
assert_eq!(
first_wire["data"],
json!([{"timestamp":120,"price":0.47,"resolution_seconds":60}])
);
let saved = first_wire["pagination"]["next_cursor"].as_str().unwrap();
assert!(wire(&e, json!({"token_id":"eb:NO:e","cursor":saved})).is_err());
assert!(wire(
&e,
json!({"token_id":"eb:YES:e","start":121,"cursor":saved})
)
.is_err());
assert!(wire(&e, json!({"token_id":"eb:YES:e","cursor":"broken!"})).is_err());
let mut first = query.clone();
first["limit"] = json!(1);
let page = e.execute(first).unwrap();
@@ -1543,6 +1563,35 @@ fn prices_history_keeps_the_terminal_tick_and_pins_pages_before_settlement() {
.unwrap();
drop(e);
let mut e = Exchange::open(&path).unwrap();
let second_wire = wire(
&e,
json!({"token_id":"eb:YES:e","start":120,"end":290,"cursor":saved,"limit":99}),
)
.unwrap();
assert_eq!(second_wire["pagination"]["limit"], 1);
assert_eq!(second_wire["pagination"]["offset"], 1);
assert_eq!(
second_wire["data"],
json!([{"timestamp":240,"price":0.55,"resolution_seconds":60}])
);
let final_wire = wire(
&e,
json!({"token_id":"eb:YES:e","cursor":second_wire["pagination"]["next_cursor"]}),
)
.unwrap();
assert_eq!(
final_wire["data"],
json!([{"timestamp":245,"price":0.55,"resolution_seconds":0}])
);
assert_eq!(
final_wire["pagination"],
json!({"limit":1,"offset":2,"has_more":false,"next_cursor":null})
);
let at_resolution = wire(&e, json!({"token_id":"eb:YES:e","asOf":273})).unwrap();
assert_eq!(
at_resolution["data"],
json!([{"timestamp":273,"price":0.5,"resolution_seconds":0}])
);
let mut seen = page["data"].as_array().unwrap().clone();
let mut cursor = page["pagination"]["next_cursor"].clone();
while !cursor.is_null() {