use std::pin::Pin;
use futures_util::{Stream, StreamExt};
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
use serde::{Deserialize, Serialize};
use tokio_util::sync::CancellationToken;
use crate::{ErpcError, Result, rest::RestTransport, rpc::decode_json};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PriceEncoding {
Base64,
Hex,
}
impl PriceEncoding {
const fn as_str(self) -> &'static str {
match self {
Self::Base64 => "base64",
Self::Hex => "hex",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PriceAssetType {
Crypto,
Equity,
Fx,
Metal,
Rates,
}
impl PriceAssetType {
const fn as_str(self) -> &'static str {
match self {
Self::Crypto => "crypto",
Self::Equity => "equity",
Self::Fx => "fx",
Self::Metal => "metal",
Self::Rates => "rates",
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct PriceFeedMetadata {
pub attributes: Option<std::collections::HashMap<String, String>>,
pub id: String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct PricePoint {
pub conf: String,
pub expo: i32,
pub price: String,
pub publish_time: i64,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ParsedPriceMetadata {
pub prev_publish_time: Option<i64>,
pub proof_available_time: Option<i64>,
pub slot: Option<u64>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ParsedPriceUpdate {
pub ema_price: PricePoint,
pub id: String,
pub metadata: Option<ParsedPriceMetadata>,
pub price: PricePoint,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct BinaryUpdate {
pub data: Vec<String>,
pub encoding: String,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct PriceUpdateResponse {
pub binary: BinaryUpdate,
pub parsed: Option<Vec<ParsedPriceUpdate>>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct PriceUpdateOptions {
pub encoding: Option<PriceEncoding>,
pub ids: Vec<String>,
pub ignore_invalid_price_ids: Option<bool>,
pub parsed: Option<bool>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct PriceStreamOptions {
pub update: PriceUpdateOptions,
pub allow_unordered: Option<bool>,
pub benchmarks_only: Option<bool>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct PublisherStakeCap {
pub cap: f64,
pub publisher: String,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ParsedPublisherStakeCaps {
pub publisher_stake_caps: Vec<PublisherStakeCap>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct PublisherStakeCapsResponse {
pub binary: BinaryUpdate,
pub parsed: Option<Vec<ParsedPublisherStakeCaps>>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct PriceStreamEvent {
pub data: PriceUpdateResponse,
pub event: Option<String>,
pub id: Option<String>,
}
pub type PriceStream = Pin<Box<dyn Stream<Item = Result<PriceStreamEvent>> + Send>>;
#[derive(Clone)]
pub struct PriceClient {
transport: RestTransport,
}
impl PriceClient {
pub(crate) const fn new(transport: RestTransport) -> Self {
Self { transport }
}
pub async fn get_price_feeds(
&self,
query_text: Option<&str>,
asset_type: Option<PriceAssetType>,
) -> Result<Vec<PriceFeedMetadata>> {
self.get_price_feeds_with(query_text, asset_type, None)
.await
}
pub async fn get_price_feeds_with(
&self,
query_text: Option<&str>,
asset_type: Option<PriceAssetType>,
cancellation: Option<&CancellationToken>,
) -> Result<Vec<PriceFeedMetadata>> {
let mut query = Vec::new();
if let Some(value) = query_text {
query.push(("query".to_owned(), value.to_owned()));
}
if let Some(value) = asset_type {
query.push(("asset_type".to_owned(), value.as_str().to_owned()));
}
self.transport
.get("/v2/price_feeds", query, cancellation)
.await
}
pub async fn get_latest_price_updates(
&self,
options: &PriceUpdateOptions,
) -> Result<PriceUpdateResponse> {
self.get_latest_price_updates_with(options, None).await
}
pub async fn get_latest_price_updates_with(
&self,
options: &PriceUpdateOptions,
cancellation: Option<&CancellationToken>,
) -> Result<PriceUpdateResponse> {
self.transport
.get(
"/v2/updates/price/latest",
update_query(options),
cancellation,
)
.await
}
pub async fn get_price_updates_at_timestamp(
&self,
publish_time: impl std::fmt::Display,
options: &PriceUpdateOptions,
) -> Result<PriceUpdateResponse> {
self.get_price_updates_at_timestamp_with(publish_time, options, None)
.await
}
pub async fn get_price_updates_at_timestamp_with(
&self,
publish_time: impl std::fmt::Display,
options: &PriceUpdateOptions,
cancellation: Option<&CancellationToken>,
) -> Result<PriceUpdateResponse> {
let publish_time = publish_time.to_string();
let segment = utf8_percent_encode(&publish_time, NON_ALPHANUMERIC);
let path = format!("/v2/updates/price/{segment}");
self.transport
.get(&path, update_query(options), cancellation)
.await
}
pub async fn get_latest_publisher_stake_caps(
&self,
encoding: Option<PriceEncoding>,
parsed: Option<bool>,
) -> Result<PublisherStakeCapsResponse> {
self.get_latest_publisher_stake_caps_with(encoding, parsed, None)
.await
}
pub async fn get_latest_publisher_stake_caps_with(
&self,
encoding: Option<PriceEncoding>,
parsed: Option<bool>,
cancellation: Option<&CancellationToken>,
) -> Result<PublisherStakeCapsResponse> {
let mut query = Vec::new();
if let Some(value) = encoding {
query.push(("encoding".to_owned(), value.as_str().to_owned()));
}
if let Some(value) = parsed {
query.push(("parsed".to_owned(), value.to_string()));
}
self.transport
.get(
"/v2/updates/publisher_stake_caps/latest",
query,
cancellation,
)
.await
}
pub async fn stream_price_updates(
&self,
options: &PriceStreamOptions,
cancellation: Option<CancellationToken>,
) -> Result<PriceStream> {
let mut query = update_query(&options.update);
if let Some(value) = options.allow_unordered {
query.push(("allow_unordered".to_owned(), value.to_string()));
}
if let Some(value) = options.benchmarks_only {
query.push(("benchmarks_only".to_owned(), value.to_string()));
}
let response = self
.transport
.get_response("/v2/updates/price/stream", query, cancellation.as_ref())
.await?;
let mut bytes = response.bytes_stream();
let output = async_stream::stream! {
let mut buffer = String::new();
loop {
let next = if let Some(token) = &cancellation {
tokio::select! {
() = token.cancelled() => {
yield Err(ErpcError::Aborted);
break;
}
next = bytes.next() => next,
}
} else {
bytes.next().await
};
let Some(chunk) = next else { break };
if let Ok(chunk) = chunk {
buffer.push_str(&String::from_utf8_lossy(&chunk));
} else {
yield Err(ErpcError::Transport("Unable to read ERPC stream".to_owned()));
break;
}
while let Some((boundary, separator_length)) = sse_boundary(&buffer) {
let block = buffer[..boundary].to_owned();
buffer.drain(..boundary + separator_length);
match parse_sse_block(&block) {
Ok(Some(event)) => yield Ok(event),
Ok(None) => {}
Err(error) => {
yield Err(error);
return;
}
}
}
}
if !buffer.is_empty() {
match parse_sse_block(&buffer) {
Ok(Some(event)) => yield Ok(event),
Ok(None) => {}
Err(error) => yield Err(error),
}
}
};
Ok(Box::pin(output))
}
}
fn update_query(options: &PriceUpdateOptions) -> Vec<(String, String)> {
let mut query: Vec<_> = options
.ids
.iter()
.map(|id| ("ids[]".to_owned(), id.clone()))
.collect();
if let Some(value) = options.encoding {
query.push(("encoding".to_owned(), value.as_str().to_owned()));
}
if let Some(value) = options.parsed {
query.push(("parsed".to_owned(), value.to_string()));
}
if let Some(value) = options.ignore_invalid_price_ids {
query.push(("ignore_invalid_price_ids".to_owned(), value.to_string()));
}
query
}
fn sse_boundary(buffer: &str) -> Option<(usize, usize)> {
match (buffer.find("\n\n"), buffer.find("\r\n\r\n")) {
(Some(left), Some(right)) if left <= right => Some((left, 2)),
(Some(_) | None, Some(right)) => Some((right, 4)),
(Some(left), None) => Some((left, 2)),
(None, None) => None,
}
}
fn parse_sse_block(block: &str) -> Result<Option<PriceStreamEvent>> {
let mut data = Vec::new();
let mut event = None;
let mut id = None;
for line in block.lines() {
if line.is_empty() || line.starts_with(':') {
continue;
}
let (field, raw) = line.split_once(':').unwrap_or((line, ""));
let value = raw.strip_prefix(' ').unwrap_or(raw);
match field {
"data" => data.push(value),
"event" => event = Some(value.to_owned()),
"id" => id = Some(value.to_owned()),
_ => {}
}
}
if data.is_empty() {
return Ok(None);
}
let response = decode_json(&data.join("\n")).map_err(|_| {
ErpcError::InvalidResponse("ERPC returned malformed stream data".to_owned())
})?;
Ok(Some(PriceStreamEvent {
data: response,
event,
id,
}))
}