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