1use std::future::Future;
8use std::pin::pin;
9use std::sync::Mutex;
10
11use futures_util::future::{select, Either};
12use futures_util::stream::{FuturesUnordered, StreamExt};
13use web_time::{Duration, Instant};
14
15pub(crate) const LOCALHOST_GATEWAY: &str = "http://127.0.0.1:8080/";
16pub(crate) const DEFAULT_PUBLIC_GATEWAYS: [&str; 2] =
17 ["https://dweb.link/", "https://4everland.io/"];
18
19const DEFAULT_BASE_COOLDOWN: Duration = Duration::from_secs(5);
22const MAX_COOLDOWN: Duration = Duration::from_mins(5);
24const MAX_FIBONACCI_STEPS: u32 = 12;
26const HEDGE_DELAY: Duration = Duration::from_secs(2);
29const TOTAL_DEADLINE: Duration = Duration::from_secs(12);
31const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(6);
33
34#[derive(Default)]
36struct GatewayHealth {
37 consecutive_failures: u32,
38 blocked_until: Option<Instant>,
39}
40
41struct AttemptError {
44 detail: String,
45 penalise: bool,
46}
47
48impl AttemptError {
49 fn gateway(detail: String) -> Self {
50 Self {
51 detail,
52 penalise: true,
53 }
54 }
55
56 fn content(detail: String) -> Self {
57 Self {
58 detail,
59 penalise: false,
60 }
61 }
62}
63
64enum RaceStep<T> {
65 Completed(usize, Result<T, AttemptError>),
66 StartNext,
67}
68
69pub struct GatewayPool {
75 gateways: Vec<String>,
76 client: reqwest::Client,
77 base_cooldown: Duration,
78 request_timeout: Mutex<Option<Duration>>,
80 health: Mutex<Vec<GatewayHealth>>,
82}
83
84impl Default for GatewayPool {
85 fn default() -> Self {
87 let mut gateways = Vec::new();
88 push_gateway(&mut gateways, LOCALHOST_GATEWAY);
89 push_default_public_gateways(&mut gateways);
90 Self::from_gateway_list(gateways)
91 }
92}
93
94impl GatewayPool {
95 pub fn from_gateways<I, S>(gateways: I) -> crate::error::Result<Self>
101 where
102 I: IntoIterator<Item = S>,
103 S: AsRef<str>,
104 {
105 let mut list = Vec::new();
106 for gateway in gateways {
107 let gateway = gateway.as_ref();
108 if !gateway.trim().is_empty() {
109 push_gateway(&mut list, gateway);
110 }
111 }
112 if list.is_empty() {
113 return Err(crate::error::Error::InvalidTransport(
114 "gateway list must not be empty".to_string(),
115 ));
116 }
117 Ok(Self::from_gateway_list(list))
118 }
119
120 #[must_use]
122 pub fn public_default() -> Self {
123 let mut gateways = Vec::new();
124 push_default_public_gateways(&mut gateways);
125 Self::from_gateway_list(gateways)
126 }
127
128 #[must_use]
132 pub fn new(gateway_url: impl Into<String>) -> Self {
133 let mut gateways = Vec::new();
134 push_gateway(&mut gateways, &gateway_url.into());
135 push_default_public_gateways(&mut gateways);
136 Self::from_gateway_list(gateways)
137 }
138
139 #[must_use]
142 pub fn local_first(gateway_url: impl Into<String>) -> Self {
143 let mut gateways = Vec::new();
144 push_gateway(&mut gateways, LOCALHOST_GATEWAY);
145 push_gateway(&mut gateways, &gateway_url.into());
146 push_default_public_gateways(&mut gateways);
147 Self::from_gateway_list(gateways)
148 }
149
150 fn from_gateway_list(gateways: Vec<String>) -> Self {
151 #[cfg(not(target_arch = "wasm32"))]
152 let client = reqwest::Client::builder()
153 .connect_timeout(Duration::from_secs(2))
154 .redirect(reqwest::redirect::Policy::limited(10))
155 .build()
156 .unwrap_or_else(|_| reqwest::Client::new());
157
158 #[cfg(target_arch = "wasm32")]
159 let client = reqwest::Client::builder()
163 .build()
164 .unwrap_or_else(|_| reqwest::Client::new());
165
166 let health = gateways.iter().map(|_| GatewayHealth::default()).collect();
167 Self {
168 gateways,
169 client,
170 base_cooldown: DEFAULT_BASE_COOLDOWN,
171 request_timeout: Mutex::new(None),
172 health: Mutex::new(health),
173 }
174 }
175
176 #[must_use]
178 pub fn gateways(&self) -> &[String] {
179 &self.gateways
180 }
181
182 #[must_use]
186 pub fn with_base_cooldown(mut self, cooldown: Duration) -> Self {
187 self.base_cooldown = cooldown;
188 self
189 }
190
191 #[must_use]
195 pub fn with_request_timeout(self, timeout: Duration) -> Self {
196 self.set_request_timeout(Some(timeout));
197 self
198 }
199
200 pub fn set_request_timeout(&self, timeout: Option<Duration>) {
203 if let Ok(mut t) = self.request_timeout.lock() {
204 *t = timeout;
205 }
206 }
207
208 pub async fn fetch<T>(
217 &self,
218 path: &str,
219 accept: Option<&str>,
220 parse: impl Fn(&[u8]) -> std::result::Result<T, String>,
221 ) -> std::result::Result<T, String> {
222 let deadline = Instant::now() + TOTAL_DEADLINE;
223 let parse = &parse;
224 self.race_gateways(move |index| self.attempt_fetch(index, path, accept, parse, deadline))
225 .await
226 .map_err(|detail| format!("all gateways failed: {detail}"))
227 }
228
229 pub async fn fetch_bytes(
231 &self,
232 path: &str,
233 accept: Option<&str>,
234 ) -> std::result::Result<Vec<u8>, String> {
235 self.fetch(path, accept, |body| Ok(body.to_vec())).await
236 }
237
238 pub async fn resolve_ipns_path(&self, path: &str) -> crate::error::Result<String> {
245 if !path.starts_with("/ipns/") || path.len() <= "/ipns/".len() {
246 return Err(crate::error::Error::IpnsResolution {
247 path: path.to_string(),
248 detail: "expected a non-empty /ipns/<name> path".to_string(),
249 });
250 }
251
252 let deadline = Instant::now() + TOTAL_DEADLINE;
253 self.race_gateways(move |index| self.attempt_resolve(index, path, deadline))
254 .await
255 .map_err(|detail| crate::error::Error::IpnsResolution {
256 path: path.to_string(),
257 detail,
258 })
259 }
260
261 async fn race_gateways<T, F, Fut>(&self, attempt: F) -> std::result::Result<T, String>
266 where
267 F: Fn(usize) -> Fut,
268 Fut: Future<Output = (usize, std::result::Result<T, AttemptError>)>,
269 {
270 let mut errors = Vec::new();
271 let order = self.gateway_order(Instant::now(), &mut errors);
272
273 let mut in_flight = FuturesUnordered::new();
274 let mut candidates = order.into_iter();
275 let mut next_candidate = candidates.next();
276
277 loop {
278 if in_flight.is_empty() {
279 match next_candidate.take() {
280 Some(index) => {
281 in_flight.push(attempt(index));
282 next_candidate = candidates.next();
283 continue;
284 }
285 None => break,
286 }
287 }
288
289 let step = if next_candidate.is_some() {
290 let completion = in_flight.next();
291 match select(pin!(completion), pin!(hedge_sleep(HEDGE_DELAY))).await {
292 Either::Left((Some((index, result)), _)) => RaceStep::Completed(index, result),
293 Either::Left((None, _)) | Either::Right(_) => RaceStep::StartNext,
294 }
295 } else {
296 match in_flight.next().await {
297 Some((index, result)) => RaceStep::Completed(index, result),
298 None => break,
299 }
300 };
301
302 match step {
303 RaceStep::Completed(index, Ok(value)) => {
304 self.record_success(index);
305 return Ok(value);
306 }
307 RaceStep::Completed(index, Err(error)) => {
308 if error.penalise {
309 self.record_failure(index);
310 }
311 errors.push(error.detail);
312 if let Some(index) = next_candidate.take() {
313 in_flight.push(attempt(index));
314 next_candidate = candidates.next();
315 }
316 }
317 RaceStep::StartNext => {
318 if let Some(index) = next_candidate.take() {
319 in_flight.push(attempt(index));
320 next_candidate = candidates.next();
321 }
322 }
323 }
324 }
325
326 Err(format!(
327 "all {} gateways failed: {}",
328 errors.len(),
329 errors.join("; ")
330 ))
331 }
332
333 async fn attempt_fetch<T, P>(
334 &self,
335 index: usize,
336 path: &str,
337 accept: Option<&str>,
338 parse: &P,
339 deadline: Instant,
340 ) -> (usize, std::result::Result<T, AttemptError>)
341 where
342 P: Fn(&[u8]) -> std::result::Result<T, String>,
343 {
344 let url = gateway_url_for_path(&self.gateways[index], path);
345 let Some(timeout) = self.remaining_timeout(deadline) else {
346 return (
347 index,
348 Err(AttemptError::content(format!(
349 "{url} -> skipped (deadline exceeded)"
350 ))),
351 );
352 };
353
354 let mut request = self.client.get(&url).timeout(timeout);
355 if let Some(accept) = accept {
356 request = request.header(reqwest::header::ACCEPT, accept);
357 }
358
359 let response = match request.send().await {
360 Ok(response) if response.status().is_success() => response,
361 Ok(response) => {
362 return (
363 index,
364 Err(AttemptError::gateway(format!(
365 "{url} -> HTTP {}",
366 response.status()
367 ))),
368 );
369 }
370 Err(error) => {
371 return (
372 index,
373 Err(AttemptError::gateway(format!("{url} -> {error}"))),
374 );
375 }
376 };
377
378 let body = match response.bytes().await {
379 Ok(body) => body,
380 Err(error) => {
381 return (
382 index,
383 Err(AttemptError::gateway(format!("{url} -> {error}"))),
384 );
385 }
386 };
387
388 match parse(&body) {
389 Ok(value) => (index, Ok(value)),
390 Err(detail) => (
391 index,
392 Err(AttemptError::content(format!("{url} -> {detail}"))),
393 ),
394 }
395 }
396
397 async fn attempt_resolve(
398 &self,
399 index: usize,
400 path: &str,
401 deadline: Instant,
402 ) -> (usize, std::result::Result<String, AttemptError>) {
403 let url = gateway_url_for_path(&self.gateways[index], path);
404 let Some(timeout) = self.remaining_timeout(deadline) else {
405 return (
406 index,
407 Err(AttemptError::content(format!(
408 "{url} -> skipped (deadline exceeded)"
409 ))),
410 );
411 };
412
413 let response = match self.client.get(&url).timeout(timeout).send().await {
414 Ok(response) if response.status().is_success() => response,
415 Ok(response) => {
416 return (
417 index,
418 Err(AttemptError::gateway(format!(
419 "{url} -> HTTP {}",
420 response.status()
421 ))),
422 );
423 }
424 Err(error) => {
425 return (
426 index,
427 Err(AttemptError::gateway(format!("{url} -> {error}"))),
428 );
429 }
430 };
431
432 let header_path = response
433 .headers()
434 .get("x-ipfs-path")
435 .and_then(|value| value.to_str().ok());
436 if let Some(resolved) = resolved_ipfs_path(header_path, response.url().path()) {
437 return (index, Ok(resolved));
438 }
439
440 (
441 index,
442 Err(AttemptError::content(format!(
443 "{url} -> gateway did not expose a resolved /ipfs path"
444 ))),
445 )
446 }
447
448 fn remaining_timeout(&self, deadline: Instant) -> Option<Duration> {
451 let remaining = deadline.saturating_duration_since(Instant::now());
452 if remaining.is_zero() {
453 return None;
454 }
455 let configured = self
456 .request_timeout
457 .lock()
458 .ok()
459 .and_then(|guard| *guard)
460 .unwrap_or(DEFAULT_REQUEST_TIMEOUT);
461 Some(configured.min(remaining))
462 }
463
464 fn gateway_order(&self, now: Instant, errors: &mut Vec<String>) -> Vec<usize> {
467 let Ok(health) = self.health.lock() else {
468 return (0..self.gateways.len()).collect();
469 };
470 let mut available = Vec::new();
471 let mut skipped = Vec::new();
472 for (index, entry) in health.iter().enumerate() {
473 if entry.blocked_until.is_none_or(|until| until <= now) {
474 available.push(index);
475 } else {
476 skipped.push(index);
477 }
478 }
479 if available.is_empty() {
480 return (0..self.gateways.len()).collect();
481 }
482 for index in skipped {
483 errors.push(format!("{} -> skipped (cooldown)", self.gateways[index]));
484 }
485 available
486 }
487
488 fn record_success(&self, index: usize) {
489 if let Ok(mut health) = self.health.lock() {
490 if let Some(entry) = health.get_mut(index) {
491 *entry = GatewayHealth::default();
492 }
493 }
494 }
495
496 fn record_failure(&self, index: usize) {
497 if let Ok(mut health) = self.health.lock() {
498 if let Some(entry) = health.get_mut(index) {
499 entry.consecutive_failures = entry.consecutive_failures.saturating_add(1);
500 let cooldown = fibonacci_cooldown(self.base_cooldown, entry.consecutive_failures);
501 entry.blocked_until = Some(Instant::now() + cooldown);
502 }
503 }
504 }
505}
506
507fn fibonacci_cooldown(base: Duration, consecutive_failures: u32) -> Duration {
509 let steps = consecutive_failures.clamp(1, MAX_FIBONACCI_STEPS);
510 let (mut previous, mut current) = (0u32, 1u32);
511 for _ in 1..steps {
512 let next = previous + current;
513 previous = current;
514 current = next;
515 }
516 base.saturating_mul(current).min(MAX_COOLDOWN)
517}
518
519async fn hedge_sleep(duration: Duration) {
521 #[cfg(not(target_arch = "wasm32"))]
522 tokio::time::sleep(duration).await;
523 #[cfg(target_arch = "wasm32")]
524 gloo_timers::future::TimeoutFuture::new(
525 u32::try_from(duration.as_millis()).unwrap_or(u32::MAX),
526 )
527 .await;
528}
529
530fn normalize_gateway_url(input: &str) -> String {
531 let mut url = input.trim().to_string();
532 if !url.ends_with('/') {
533 url.push('/');
534 }
535 url
536}
537
538fn push_gateway(gateways: &mut Vec<String>, candidate: &str) {
539 let normalized = normalize_gateway_url(candidate);
540 if !gateways.iter().any(|g| g.eq_ignore_ascii_case(&normalized)) {
541 gateways.push(normalized);
542 }
543}
544
545fn push_default_public_gateways(gateways: &mut Vec<String>) {
546 for fallback in DEFAULT_PUBLIC_GATEWAYS {
547 push_gateway(gateways, fallback);
548 }
549}
550
551fn gateway_url_for_path(gateway: &str, path: &str) -> String {
556 let normalised_path = path.trim_start_matches('/');
557 if let (Some(parsed), Some((namespace, root, suffix))) = (
558 reqwest::Url::parse(gateway).ok(),
559 subdomain_gateway_parts(normalised_path),
560 ) {
561 if let Some(host) = domain_gateway_host(&parsed) {
562 return format!("{}://{root}.{namespace}.{host}{suffix}", parsed.scheme());
563 }
564 }
565 format!("{}{}", gateway, normalised_path)
566}
567
568fn domain_gateway_host(gateway: &reqwest::Url) -> Option<&str> {
569 let host = gateway.host_str()?;
570 (host != "localhost" && host.parse::<std::net::IpAddr>().is_err()).then_some(host)
571}
572
573fn subdomain_gateway_parts(path: &str) -> Option<(&str, &str, String)> {
574 let (namespace, rest) = path
575 .strip_prefix("ipfs/")
576 .map(|rest| ("ipfs", rest))
577 .or_else(|| path.strip_prefix("ipns/").map(|rest| ("ipns", rest)))?;
578 let split_at = rest
579 .find(|character| ['/', '?'].contains(&character))
580 .unwrap_or(rest.len());
581 let root = &rest[..split_at];
582 if root.is_empty() {
583 return None;
584 }
585 let remainder = &rest[split_at..];
586 let suffix = if remainder.is_empty() {
587 "/".to_string()
588 } else if remainder.starts_with('/') {
589 remainder.to_string()
590 } else {
591 format!("/{remainder}")
592 };
593 Some((namespace, root, suffix))
594}
595
596fn resolved_ipfs_path(header_path: Option<&str>, final_path: &str) -> Option<String> {
597 header_path
598 .into_iter()
599 .chain(std::iter::once(final_path))
600 .find_map(|path| {
601 path.strip_prefix("/ipfs/")
602 .map(|cid| format!("/ipfs/{cid}"))
603 })
604}
605
606#[cfg(test)]
607mod tests {
608 use super::{
609 fibonacci_cooldown, gateway_url_for_path, normalize_gateway_url, push_gateway,
610 resolved_ipfs_path, GatewayPool, MAX_COOLDOWN,
611 };
612 use web_time::{Duration, Instant};
613
614 #[test]
615 fn resolved_ipfs_path_prefers_gateway_header() {
616 assert_eq!(
617 resolved_ipfs_path(Some("/ipfs/bafyheader"), "/ipfs/bafyredirect"),
618 Some("/ipfs/bafyheader".to_string())
619 );
620 assert_eq!(
621 resolved_ipfs_path(None, "/ipfs/bafyredirect"),
622 Some("/ipfs/bafyredirect".to_string())
623 );
624 assert_eq!(resolved_ipfs_path(None, "/ipns/k51name"), None);
625 }
626
627 #[test]
628 fn gateway_url_for_path_uses_subdomain_for_domain_gateways() {
629 assert_eq!(
630 gateway_url_for_path("https://dweb.link/", "/ipns/k51abc"),
631 "https://k51abc.ipns.dweb.link/"
632 );
633 assert_eq!(
634 gateway_url_for_path("https://4everland.io/", "/ipns/k51abc"),
635 "https://k51abc.ipns.4everland.io/"
636 );
637 assert_eq!(
639 gateway_url_for_path("http://127.0.0.1:8080/", "/ipns/k51abc"),
640 "http://127.0.0.1:8080/ipns/k51abc"
641 );
642 assert_eq!(
644 gateway_url_for_path("http://localhost:8080/", "/ipns/k51abc"),
645 "http://localhost:8080/ipns/k51abc"
646 );
647 assert_eq!(
648 gateway_url_for_path("https://dweb.link/", "/ipfs/bafycid"),
649 "https://bafycid.ipfs.dweb.link/"
650 );
651 assert_eq!(
652 gateway_url_for_path("https://dweb.link/", "ipfs/bafycid?format=raw"),
653 "https://bafycid.ipfs.dweb.link/?format=raw"
654 );
655 assert_eq!(
656 gateway_url_for_path("https://dweb.link/", "/ipfs/bafycid/child"),
657 "https://bafycid.ipfs.dweb.link/child"
658 );
659 }
660
661 #[test]
662 fn normalize_gateway_url_adds_missing_trailing_slash() {
663 assert_eq!(
664 normalize_gateway_url("https://dweb.link"),
665 "https://dweb.link/"
666 );
667 assert_eq!(
668 normalize_gateway_url("https://dweb.link/"),
669 "https://dweb.link/"
670 );
671 assert_eq!(
672 normalize_gateway_url(" https://dweb.link "),
673 "https://dweb.link/"
674 );
675 }
676
677 #[test]
678 fn push_gateway_deduplicates_case_insensitively() {
679 let mut gateways = Vec::new();
680 push_gateway(&mut gateways, "https://dweb.link/");
681 push_gateway(&mut gateways, "https://dweb.link/"); push_gateway(&mut gateways, "https://dweb.link"); assert_eq!(gateways.len(), 1, "duplicates must not be added");
684 }
685
686 #[test]
687 fn default_is_local_first() {
688 let pool = GatewayPool::default();
689 assert_eq!(
690 pool.gateways(),
691 [
692 "http://127.0.0.1:8080/".to_string(),
693 "https://dweb.link/".to_string(),
694 "https://4everland.io/".to_string(),
695 ]
696 );
697 }
698
699 #[test]
700 fn public_default_never_includes_localhost() {
701 let pool = GatewayPool::public_default();
702 assert_eq!(
703 pool.gateways(),
704 [
705 "https://dweb.link/".to_string(),
706 "https://4everland.io/".to_string(),
707 ]
708 );
709 }
710
711 #[test]
712 fn new_uses_primary_then_public_fallbacks_without_hidden_localhost() {
713 let pool = GatewayPool::new("https://example.test/ipfs");
714 assert_eq!(
715 pool.gateways(),
716 [
717 "https://example.test/ipfs/".to_string(),
718 "https://dweb.link/".to_string(),
719 "https://4everland.io/".to_string(),
720 ]
721 );
722 }
723
724 #[test]
725 fn local_first_puts_localhost_before_primary() {
726 let pool = GatewayPool::local_first("https://example.test/");
727 assert_eq!(
728 pool.gateways(),
729 [
730 "http://127.0.0.1:8080/".to_string(),
731 "https://example.test/".to_string(),
732 "https://dweb.link/".to_string(),
733 "https://4everland.io/".to_string(),
734 ]
735 );
736 }
737
738 #[test]
739 fn from_gateways_uses_exact_deduplicated_list() {
740 let pool = GatewayPool::from_gateways([
741 "https://example.test/ipfs",
742 "",
743 "https://example.test/ipfs/",
744 "http://localhost:8881/",
745 ])
746 .expect("gateway list");
747 assert_eq!(
748 pool.gateways(),
749 [
750 "https://example.test/ipfs/".to_string(),
751 "http://localhost:8881/".to_string(),
752 ]
753 );
754 }
755
756 #[test]
757 fn from_gateways_rejects_empty_lists() {
758 let result = GatewayPool::from_gateways(["", " "]);
759 assert!(result
760 .err()
761 .is_some_and(|err| err.to_string().contains("gateway list must not be empty")));
762 }
763
764 #[test]
765 fn fibonacci_cooldown_escalates_and_caps() {
766 let base = Duration::from_secs(5);
767 assert_eq!(fibonacci_cooldown(base, 1), Duration::from_secs(5));
768 assert_eq!(fibonacci_cooldown(base, 2), Duration::from_secs(5));
769 assert_eq!(fibonacci_cooldown(base, 3), Duration::from_secs(10));
770 assert_eq!(fibonacci_cooldown(base, 4), Duration::from_secs(15));
771 assert_eq!(fibonacci_cooldown(base, 5), Duration::from_secs(25));
772 assert_eq!(fibonacci_cooldown(base, 6), Duration::from_secs(40));
773 assert_eq!(fibonacci_cooldown(base, 100), MAX_COOLDOWN);
774 assert_eq!(fibonacci_cooldown(Duration::ZERO, 7), Duration::ZERO);
775 }
776
777 #[test]
778 fn record_failure_blocks_gateway_and_success_clears_it() {
779 let pool = GatewayPool::default();
780 let mut errors = Vec::new();
781
782 assert_eq!(
783 pool.gateway_order(Instant::now(), &mut errors),
784 vec![0, 1, 2],
785 "all gateways available initially"
786 );
787
788 pool.record_failure(0);
789 errors.clear();
790 assert_eq!(
791 pool.gateway_order(Instant::now(), &mut errors),
792 vec![1, 2],
793 "failed gateway must be skipped during cooldown"
794 );
795 assert_eq!(errors.len(), 1);
796 assert!(errors[0].contains("skipped (cooldown)"));
797
798 pool.record_success(0);
799 errors.clear();
800 assert_eq!(
801 pool.gateway_order(Instant::now(), &mut errors),
802 vec![0, 1, 2],
803 "success must clear the cooldown"
804 );
805 assert!(errors.is_empty());
806 }
807
808 #[test]
809 fn gateway_order_falls_back_to_all_when_everything_is_blocked() {
810 let pool = GatewayPool::default();
811 for index in 0..pool.gateways().len() {
812 pool.record_failure(index);
813 }
814 let mut errors = Vec::new();
815 assert_eq!(
816 pool.gateway_order(Instant::now(), &mut errors),
817 vec![0, 1, 2],
818 "a fetch must never dead-end on cooldowns alone"
819 );
820 assert!(errors.is_empty());
821 }
822
823 #[test]
824 fn zero_base_cooldown_disables_blocking() {
825 let pool = GatewayPool::default().with_base_cooldown(Duration::ZERO);
826 pool.record_failure(0);
827 let mut errors = Vec::new();
828 assert_eq!(
829 pool.gateway_order(Instant::now(), &mut errors),
830 vec![0, 1, 2],
831 "zero base cooldown must never block a gateway"
832 );
833 }
834}