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
+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() {