use super::{FetchError, FetchRequest, Fetched, Fetcher, HttpFetcher, ProgressFn};
use crate::types::Address;
use async_trait::async_trait;
pub const DEFAULT_IPFS_GATEWAY: &str = "https://ipfs.io";
const IPFS_SCHEME: &str = "ipfs";
pub struct IpfsGatewayFetcher {
gateway: String,
http: HttpFetcher,
schemes: Vec<String>,
}
impl IpfsGatewayFetcher {
pub fn new(gateway: impl Into<String>) -> Self {
Self {
gateway: gateway.into().trim_end_matches('/').to_owned(),
http: HttpFetcher::new(),
schemes: vec![IPFS_SCHEME.to_owned()],
}
}
pub fn with_default_gateway() -> Self {
Self::new(DEFAULT_IPFS_GATEWAY)
}
pub fn with_http_fetcher(mut self, http: HttpFetcher) -> Self {
self.http = http;
self
}
pub fn gateway(&self) -> &str {
&self.gateway
}
pub fn resolve(&self, uri: &str) -> Result<String, FetchError> {
let rest = uri
.strip_prefix("ipfs://")
.ok_or_else(|| FetchError::InvalidAddress(format!("not an ipfs URI: `{uri}`")))?;
let rest = rest.trim_start_matches('/');
if rest.is_empty() {
return Err(FetchError::InvalidAddress(format!(
"ipfs URI has no content identifier: `{uri}`"
)));
}
Ok(format!("{}/ipfs/{rest}", self.gateway))
}
fn rewrite(&self, request: &FetchRequest) -> Result<FetchRequest, FetchError> {
Ok(FetchRequest {
address: Address::new("https", self.resolve(&request.address.uri)?),
destination: request.destination.clone(),
expected_sha256: request.expected_sha256.clone(),
})
}
}
#[async_trait]
impl Fetcher for IpfsGatewayFetcher {
fn name(&self) -> &str {
"ipfs-gateway"
}
fn schemes(&self) -> &[String] {
&self.schemes
}
async fn fetch(&self, request: &FetchRequest) -> Result<Fetched, FetchError> {
let mut fetched = self.http.fetch(&self.rewrite(request)?).await?;
fetched.address = request.address.clone();
Ok(fetched)
}
async fn fetch_with_progress(
&self,
request: &FetchRequest,
progress: &ProgressFn<'_>,
) -> Result<Fetched, FetchError> {
let mut fetched = self
.http
.fetch_with_progress(&self.rewrite(request)?, progress)
.await?;
fetched.address = request.address.clone();
Ok(fetched)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn resolves_cid_without_path() {
let fetcher = IpfsGatewayFetcher::new("https://ipfs.io");
assert_eq!(
fetcher.resolve("ipfs://bafyabc").expect("resolve"),
"https://ipfs.io/ipfs/bafyabc"
);
}
#[test]
fn resolves_cid_with_path_and_query() {
let fetcher = IpfsGatewayFetcher::new("https://ipfs.io");
assert_eq!(
fetcher
.resolve("ipfs://bafyabc/docs/report.pdf?filename=report.pdf")
.expect("resolve"),
"https://ipfs.io/ipfs/bafyabc/docs/report.pdf?filename=report.pdf"
);
}
#[test]
fn tolerates_trailing_gateway_slash_and_leading_cid_slash() {
let fetcher = IpfsGatewayFetcher::new("https://ipfs.io/");
assert_eq!(
fetcher.resolve("ipfs:///bafyabc").expect("resolve"),
"https://ipfs.io/ipfs/bafyabc"
);
assert_eq!(fetcher.gateway(), "https://ipfs.io");
}
#[test]
fn rejects_wrong_scheme_and_empty_cid() {
let fetcher = IpfsGatewayFetcher::new("https://ipfs.io");
assert!(matches!(
fetcher.resolve("https://example.org/file"),
Err(FetchError::InvalidAddress(_))
));
assert!(matches!(
fetcher.resolve("ipfs://"),
Err(FetchError::InvalidAddress(_))
));
assert!(matches!(
fetcher.resolve("ipfs:///"),
Err(FetchError::InvalidAddress(_))
));
}
}