Skip to main content

hashtree_client/
store.rs

1use crate::ClientConfig;
2use anyhow::{bail, ensure, Context, Result};
3use async_trait::async_trait;
4use futures::{stream::FuturesUnordered, StreamExt};
5use hashtree_core::{Hash, Store, StoreError};
6use hashtree_fs::FsBlobStore;
7use sha2::{Digest, Sha256};
8use std::{error::Error, io::ErrorKind, path::Path, time::Duration};
9
10const MAX_BLOCK: usize = 4 * 1024 * 1024;
11
12pub struct BlobStore {
13    cache: FsBlobStore,
14    config: ClientConfig,
15    pub(crate) http: reqwest::Client,
16}
17
18fn verify(hash: &Hash, bytes: &[u8]) -> Result<()> {
19    ensure!(
20        bytes.len() <= MAX_BLOCK && Sha256::digest(bytes).as_slice() == hash,
21        "invalid Hashtree block hash or size"
22    );
23    Ok(())
24}
25
26fn transient_http_error(error: &reqwest::Error) -> bool {
27    if error.is_connect()
28        || error.is_timeout()
29        || error.is_body()
30        || error.is_decode()
31        || error.status().is_some_and(|status| {
32            status.is_server_error() || status == reqwest::StatusCode::TOO_MANY_REQUESTS
33        })
34    {
35        return true;
36    }
37    // A connection can reset after connecting but before response headers.
38    // reqwest reports this as a request error, not necessarily is_connect().
39    // Inspect typed causes rather than retrying all request/protocol failures.
40    let mut cause = error.source();
41    while let Some(error) = cause {
42        if error.downcast_ref::<std::io::Error>().is_some_and(|io| {
43            matches!(
44                io.kind(),
45                ErrorKind::ConnectionReset | ErrorKind::ConnectionAborted | ErrorKind::BrokenPipe
46            )
47        }) {
48            return true;
49        }
50        cause = error.source();
51    }
52    false
53}
54
55impl BlobStore {
56    pub fn new(cache: &Path, config: ClientConfig) -> Result<Self> {
57        Ok(Self {
58            cache: FsBlobStore::new(cache)?,
59            http: reqwest::Client::builder()
60                .timeout(config.request_timeout)
61                .redirect(reqwest::redirect::Policy::none())
62                .build()?,
63            config,
64        })
65    }
66
67    async fn fetch(&self, server: &str, hash: &Hash) -> Result<Option<Vec<u8>>> {
68        // Keep credentials, query strings and private URL paths out of diagnostics.
69        let origin = reqwest::Url::parse(server)
70            .map(|url| url.origin().ascii_serialization())
71            .unwrap_or_else(|_| "invalid source URL".into());
72        let context = || format!("Hashtree block {} from {origin}", hex::encode(hash));
73        match self.fetch_once(server, hash).await {
74            Err(error)
75                if error
76                    .downcast_ref::<reqwest::Error>()
77                    .is_some_and(transient_http_error) =>
78            {
79                // A partial response is never cached. Retry just this source once;
80                // the other hedged sources remain free to finish first.
81                tokio::time::sleep(Duration::from_millis(250)).await;
82                self.fetch_once(server, hash).await.with_context(context)
83            }
84            result => result.with_context(context),
85        }
86    }
87
88    async fn fetch_once(&self, server: &str, hash: &Hash) -> Result<Option<Vec<u8>>> {
89        let response = self
90            .http
91            .get(format!(
92                "{}/{}.bin",
93                server.trim_end_matches('/'),
94                hex::encode(hash)
95            ))
96            .send()
97            .await
98            .map_err(reqwest::Error::without_url)?;
99        if response.status() == reqwest::StatusCode::NOT_FOUND {
100            return Ok(None);
101        }
102        let response = response
103            .error_for_status()
104            .map_err(reqwest::Error::without_url)?;
105        ensure!(
106            response.status().is_success(),
107            "unexpected Hashtree HTTP status: {}",
108            response.status()
109        );
110        ensure!(
111            response
112                .content_length()
113                .is_none_or(|n| n <= MAX_BLOCK as u64),
114            "oversized Hashtree block"
115        );
116        let mut body = response.bytes_stream();
117        let mut bytes = Vec::new();
118        while let Some(part) = body.next().await {
119            let part = part.map_err(reqwest::Error::without_url)?;
120            ensure!(
121                bytes.len().saturating_add(part.len()) <= MAX_BLOCK,
122                "oversized Hashtree block"
123            );
124            bytes.extend_from_slice(&part);
125        }
126        verify(hash, &bytes)?;
127        Ok(Some(bytes))
128    }
129
130    async fn retrieve(&self, hash: &Hash) -> Result<Option<Vec<u8>>> {
131        if let Some(bytes) = self.cache.get(hash).await? {
132            verify(hash, &bytes)?;
133            return Ok(Some(bytes));
134        }
135        let mut servers: Vec<&str> = self.config.daemon_url.as_deref().into_iter().collect();
136        if !self.config.local_only {
137            servers.extend(self.config.read_servers.iter().map(String::as_str));
138        }
139        ensure!(
140            !servers.is_empty(),
141            "no Hashtree content sources configured"
142        );
143        let mut pending = FuturesUnordered::new();
144        for (i, server) in servers.into_iter().enumerate() {
145            pending.push(async move {
146                // Give the existing daemon first chance; slow peers do not block
147                // other sources or get misreported as a definitive absence.
148                tokio::time::sleep(Duration::from_millis((i as u64).min(8) * 150)).await;
149                self.fetch(server, hash).await
150            });
151        }
152        let mut errors = Vec::new();
153        while let Some(result) = pending.next().await {
154            match result {
155                Ok(Some(bytes)) => {
156                    self.cache.put(*hash, bytes.clone()).await?;
157                    return Ok(Some(bytes));
158                }
159                Ok(None) => {}
160                Err(error) => errors.push(format!("{error:#}")),
161            }
162        }
163        if !errors.is_empty() {
164            bail!("all Hashtree content sources failed: {}", errors.join("; "));
165        }
166        Ok(None)
167    }
168}
169
170#[async_trait]
171impl Store for BlobStore {
172    async fn get(&self, hash: &Hash) -> Result<Option<Vec<u8>>, StoreError> {
173        self.retrieve(hash)
174            .await
175            .map_err(|e| StoreError::Other(format!("{e:#}")))
176    }
177    async fn put(&self, hash: Hash, bytes: Vec<u8>) -> Result<bool, StoreError> {
178        verify(&hash, &bytes).map_err(|e| StoreError::Other(e.to_string()))?;
179        self.cache.put(hash, bytes).await
180    }
181    async fn has(&self, hash: &Hash) -> Result<bool, StoreError> {
182        Ok(self.get(hash).await?.is_some())
183    }
184    async fn delete(&self, hash: &Hash) -> Result<bool, StoreError> {
185        self.cache.delete(hash).await
186    }
187}