use reqwest::header::{HeaderMap, HeaderValue};
use url::Url;
use crate::IndexerError;
pub const PROJECT_ID: &str = "project_id";
pub const DEFAULT_GRAPHQL_PATH: &str = "/api/v4/graphql";
#[derive(Clone)]
pub struct IndexerEndpoint {
pub url: Url,
pub project_id: Option<String>,
}
impl std::fmt::Debug for IndexerEndpoint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("IndexerEndpoint")
.field("url", &self.url.as_str())
.field(
"project_id",
&self.project_id.as_ref().map(|_| "<redacted>"),
)
.finish()
}
}
impl IndexerEndpoint {
pub fn parse(raw: &str) -> Result<Self, IndexerError> {
let mut url = Url::parse(raw)?;
if url.path().is_empty() || url.path() == "/" {
url.set_path(DEFAULT_GRAPHQL_PATH);
}
let mut project_id = None;
let rest: Vec<(String, String)> = url
.query_pairs()
.filter_map(|(k, v)| {
if k == PROJECT_ID {
project_id = Some(v.into_owned());
None
} else {
Some((k.into_owned(), v.into_owned()))
}
})
.collect();
if rest.is_empty() {
url.set_query(None);
} else {
url.query_pairs_mut().clear().extend_pairs(rest);
}
Ok(Self { url, project_id })
}
pub fn http_client(&self) -> Result<reqwest::Client, IndexerError> {
let mut headers = HeaderMap::new();
if let Some(id) = &self.project_id {
let mut value = HeaderValue::from_str(id).map_err(|e| {
IndexerError::InvalidResponse(format!(
"project id is not a valid header value: {e}"
))
})?;
value.set_sensitive(true);
headers.insert(PROJECT_ID, value);
}
let builder = reqwest::Client::builder().default_headers(headers);
#[cfg(not(target_arch = "wasm32"))]
let builder = builder.tcp_nodelay(true).pool_max_idle_per_host(8);
Ok(builder.build()?)
}
#[must_use]
pub fn url_with_project_id(&self) -> Url {
let mut url = self.url.clone();
if let Some(id) = &self.project_id {
url.query_pairs_mut().append_pair(PROJECT_ID, id);
}
url
}
}
#[must_use]
pub fn redact_project_id(url: &str) -> String {
let Ok(mut parsed) = Url::parse(url) else {
return url.to_owned();
};
if !parsed.query_pairs().any(|(k, _)| k == PROJECT_ID) {
return url.to_owned();
}
let pairs: Vec<(String, String)> = parsed
.query_pairs()
.map(|(k, v)| {
let v = if k == PROJECT_ID {
"<redacted>".to_owned()
} else {
v.into_owned()
};
(k.into_owned(), v)
})
.collect();
parsed.query_pairs_mut().clear().extend_pairs(pairs);
parsed.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_bare_host_gets_the_self_hosted_path() {
let ep = IndexerEndpoint::parse("http://127.0.0.1:8088").unwrap();
assert_eq!(ep.url.as_str(), "http://127.0.0.1:8088/api/v4/graphql");
assert!(ep.project_id.is_none());
}
#[test]
fn the_project_id_moves_out_of_the_url() {
let ep = IndexerEndpoint::parse(
"https://midnight-preprod.blockfrost.io/api/v0?project_id=nightpreprodX",
)
.unwrap();
assert_eq!(
ep.url.as_str(),
"https://midnight-preprod.blockfrost.io/api/v0"
);
assert_eq!(ep.project_id.as_deref(), Some("nightpreprodX"));
assert_eq!(
ep.url_with_project_id().as_str(),
"https://midnight-preprod.blockfrost.io/api/v0?project_id=nightpreprodX"
);
assert!(!format!("{ep:?}").contains("nightpreprodX"));
}
#[test]
fn redaction_hides_only_the_project_id() {
assert_eq!(
redact_project_id("wss://rpc.midnight-mainnet.blockfrost.io/?project_id=secret&x=1"),
"wss://rpc.midnight-mainnet.blockfrost.io/?project_id=%3Credacted%3E&x=1"
);
assert_eq!(
redact_project_id("ws://127.0.0.1:9944"),
"ws://127.0.0.1:9944"
);
}
}