OXYGENHUB

Coverage / crates/oxy-strata/src/lib.rs 58.5%

385 of 658 lines run, 52 of 214 functions · run #309 on main · run missed

1
//! Oxygen Strata: repositories kept on cloud object storage (docs/stores.md).
2
//!
3
//! This crate gives `oxy` the stores that need an HTTP client and the
4
//! providers' signing: Amazon S3 (`s3://BUCKET/PREFIX`), Google Cloud
5
//! Storage (`gs://BUCKET/PREFIX`) and Azure Blob Storage
6
//! (`az://ACCOUNT/CONTAINER/PREFIX`), each as a [`Store`] over the
7
//! `object_store` crate. Credentials come from each provider's standard
8
//! places, with nothing oxy-specific to set up; a URL may carry settings
9
//! as query parameters (`?profile=work&region=eu-west-2`), which is where
10
//! `oxy remote add --profile` keeps them.
11
//!
12
//! [`register`] hands these stores to oxy-core's remote opener; a program
13
//! that links this crate calls it once at start.
14
15
mod aws;
16
mod azure;
17
mod gcp;
18
mod http;
19
mod ini;
20
21
use futures::TryStreamExt;
22
use object_store::path::Path as ObjectPath;
23
use object_store::{
24
    GetOptions, ObjectStore, ObjectStoreExt, PutMode, PutOptions, PutPayload, UpdateVersion,
25
};
26
use oxy_core::strata::{check_key, Entry, Error, Result, Store, Version};
27
use std::collections::BTreeMap;
28
use std::future::Future;
29
use std::ops::Range;
30
use std::sync::{Arc, Mutex};
31
32
/// Make the cloud stores available to `oxy_core::protocol::open_remote`.
33
/// Safe to call more than once.
34152×
pub fn register() {
35
    // object_store's reqwest is built with rustls and no bundled crypto
36
    // provider; oxy links ring already, so that is the one to install.
37152×
    let _ = rustls::crypto::ring::default_provider().install_default();
38152×
    oxy_core::protocol::register_store_opener(open_url);
39152×
}
40
4117×
fn open_url(
4217×
    url: &str,
4317×
    _options: &oxy_core::protocol::RemoteOptions,
4417×
) -> Option<Result<Box<dyn Store>>> {
4517×
    let scheme = url.split_once("://")?.0;
460×
    if !matches!(scheme, "s3" | "gs" | "az") {
470×
        return None;
480×
    }
490×
    let lookup = *CREDENTIALS.lock().unwrap_or_else(|p| p.into_inner());
500×
    let given = lookup.and_then(|f| f(url));
510×
    Some(shared(url, given).map(|s| Box::new(Shared(s)) as Box<dyn Store>))
5217×
}
53
54
/// One client per store and credentials, kept for the life of the process
55
/// (oxygenhub#234): a server opens a repository for every request, and a
56
/// new client each time meant a new runtime, new connections and signing
57
/// in to the provider again before the first byte.
58
type OpenStores = std::collections::HashMap<(String, Option<Credentials>), Arc<CloudStore>>;
59
603×
fn shared(url: &str, given: Option<Credentials>) -> Result<Arc<CloudStore>> {
61
    static OPEN: Mutex<Option<OpenStores>> = Mutex::new(None);
623×
    let key = (url.to_string(), given);
633×
    let mut open = OPEN.lock().unwrap_or_else(|p| p.into_inner());
643×
    let map = open.get_or_insert_with(Default::default);
653×
    if let Some(s) = map.get(&key) {
661×
        return Ok(s.clone());
672×
    }
682×
    let store = Arc::new(CloudStore::open_with(url, key.1.as_ref())?);
692×
    map.insert(key, store.clone());
702×
    Ok(store)
713×
}
72
73
/// A shared [`CloudStore`] as a [`Store`].
74
struct Shared(Arc<CloudStore>);
75
76
impl Store for Shared {
770×
    fn describe(&self) -> String {
780×
        self.0.describe()
790×
    }
800×
    fn has(&self, key: &str) -> Result<bool> {
810×
        self.0.has(key)
820×
    }
830×
    fn get(&self, key: &str) -> Result<Vec<u8>> {
840×
        self.0.get(key)
850×
    }
860×
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
870×
        self.0.get_range(key, range)
880×
    }
890×
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
900×
        self.0.put_new(key, bytes)
910×
    }
920×
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
930×
        self.0.list(prefix)
940×
    }
950×
    fn delete(&self, key: &str) -> Result<()> {
960×
        self.0.delete(key)
970×
    }
980×
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
990×
        self.0.read_ref(key)
1000×
    }
1010×
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
1020×
        self.0.write_ref(key, bytes, expected)
1030×
    }
104
}
105
106
static OPENS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
107
static CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
108
static MICROS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
109
static BY_OP: [std::sync::atomic::AtomicU64; Op::ALL.len()] =
110
    [const { std::sync::atomic::AtomicU64::new(0) }; Op::ALL.len()];
111
112
/// The kinds of request a cloud store makes, counted apart so a server can
113
/// tell which of them its time goes to.
114
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115
pub enum Op {
116
    /// `has` that found the object.
117
    Has,
118
    /// `has` that did not: an absent object is never cached.
119
    HasMissing,
120
    Get,
121
    Range,
122
    Put,
123
    List,
124
    Delete,
125
    ReadRef,
126
    WriteRef,
127
}
128
129
impl Op {
130
    pub const ALL: [Op; 9] = [
131
        Op::Has,
132
        Op::HasMissing,
133
        Op::Get,
134
        Op::Range,
135
        Op::Put,
136
        Op::List,
137
        Op::Delete,
138
        Op::ReadRef,
139
        Op::WriteRef,
140
    ];
141
1429×
    pub fn name(self) -> &'static str {
1439×
        match self {
1441×
            Op::Has => "has",
1451×
            Op::HasMissing => "has_missing",
1461×
            Op::Get => "get",
1471×
            Op::Range => "range",
1481×
            Op::Put => "put",
1491×
            Op::List => "list",
1501×
            Op::Delete => "delete",
1511×
            Op::ReadRef => "read_ref",
1521×
            Op::WriteRef => "write_ref",
153
        }
1549×
    }
155
}
156
1570×
fn counted(op: Op) {
1580×
    BY_OP[op as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1590×
}
160
161
/// What the cloud stores have done since the process started: clients
162
/// opened, requests made and the time spent in them, for a server to show
163
/// (a hub's /health).
164
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
165
pub struct Stats {
166
    pub opens: u64,
167
    pub calls: u64,
168
    pub millis: u64,
169
    /// Requests by kind, in [`Op::ALL`]'s order.
170
    pub by_op: [u64; Op::ALL.len()],
171
}
172
173
impl Stats {
174
    /// Each kind of request with how many were made.
1751×
    pub fn ops(&self) -> impl Iterator<Item = (&'static str, u64)> + '_ {
1761×
        Op::ALL
1771×
            .iter()
1789×
            .map(|op| (op.name(), self.by_op[*op as usize]))
1791×
    }
180
}
181
1823×
pub fn stats() -> Stats {
183
    use std::sync::atomic::Ordering::Relaxed;
184
    Stats {
1853×
        opens: OPENS.load(Relaxed),
1863×
        calls: CALLS.load(Relaxed),
1873×
        millis: MICROS.load(Relaxed) / 1000,
18827×
        by_op: std::array::from_fn(|i| BY_OP[i].load(Relaxed)),
189
    }
1903×
}
191
192
/// Credentials a program keeps itself and hands over, instead of the
193
/// provider's usual places: a hub keeps each repository's sealed. When a
194
/// store is opened with them, nothing from the environment or the
195
/// provider's files is used.
196
#[derive(Clone, PartialEq, Eq, Hash)]
197
pub enum Credentials {
198
    /// An S3 access key.
199
    Aws {
200
        access_key_id: String,
201
        secret_access_key: String,
202
        session_token: Option<String>,
203
    },
204
    /// A Google Cloud service account key, as the JSON Google issues.
205
    Gcp { service_account_key: String },
206
    /// An Azure service principal.
207
    Azure {
208
        tenant_id: String,
209
        client_id: String,
210
        client_secret: String,
211
    },
212
}
213
214
impl std::fmt::Debug for Credentials {
215
    /// Names the kind and the public part only: never the secret.
2163×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2173×
        match self {
2181×
            Credentials::Aws { access_key_id, .. } => {
2191×
                write!(f, "Aws({access_key_id}, secret hidden)")
220
            }
2211×
            Credentials::Gcp { .. } => write!(f, "Gcp(service account key hidden)"),
2221×
            Credentials::Azure { client_id, .. } => write!(f, "Azure({client_id}, secret hidden)"),
223
        }
2243×
    }
225
}
226
227
impl Credentials {
228
    /// The scheme of the stores these are for.
2294×
    pub fn scheme(&self) -> &'static str {
2304×
        match self {
2314×
            Credentials::Aws { .. } => "s3",
2320×
            Credentials::Gcp { .. } => "gs",
2330×
            Credentials::Azure { .. } => "az",
234
        }
2354×
    }
236
237
    /// As JSON, for keeping (sealed) and reading back with [`Credentials::from_json`].
2383×
    pub fn to_json(&self) -> String {
2393×
        let v = match self {
240
            Credentials::Aws {
2411×
                access_key_id,
2421×
                secret_access_key,
2431×
                session_token,
2441×
            } => serde_json::json!({
2451×
                "kind": "aws", "access_key_id": access_key_id, "secret_access_key": secret_access_key,
2461×
                "session_token": session_token,
247
            }),
248
            Credentials::Gcp {
2491×
                service_account_key,
250
            } => {
2511×
                serde_json::json!({ "kind": "gcp", "service_account_key": service_account_key })
252
            }
253
            Credentials::Azure {
2541×
                tenant_id,
2551×
                client_id,
2561×
                client_secret,
2571×
            } => serde_json::json!({
2581×
                "kind": "azure", "tenant_id": tenant_id, "client_id": client_id, "client_secret": client_secret,
259
            }),
260
        };
2613×
        v.to_string()
2623×
    }
263
2647×
    pub fn from_json(text: &str) -> Result<Credentials> {
2657×
        let v: serde_json::Value = serde_json::from_str(text)
2667×
            .map_err(|e| Error::Backend(format!("credentials are not JSON: {e}")))?;
26710×
        let field = |k: &str| -> Result<String> {
26810×
            v.get(k)
26910×
                .and_then(|x| x.as_str())
27010×
                .filter(|x| !x.trim().is_empty())
27110×
                .map(|x| x.trim().to_string())
27210×
                .ok_or_else(|| Error::Backend(format!("credentials need {k}")))
27310×
        };
2746×
        match v.get("kind").and_then(|k| k.as_str()) {
2756×
            Some("aws") => Ok(Credentials::Aws {
2762×
                access_key_id: field("access_key_id")?,
2772×
                secret_access_key: field("secret_access_key")?,
2781×
                session_token: field("session_token").ok(),
279
            }),
2804×
            Some("gcp") => {
2812×
                let key = field("service_account_key")?;
2822×
                let parsed: serde_json::Value = serde_json::from_str(&key).map_err(|_| {
2830×
                    Error::Backend("the service account key is not the JSON Google issues".into())
2840×
                })?;
2852×
                if parsed.get("type").and_then(|t| t.as_str()) != Some("service_account") {
2861×
                    return Err(Error::Backend(
2871×
                        "the key is not a service account key (its type is not service_account)"
2881×
                            .into(),
2891×
                    ));
2901×
                }
2911×
                Ok(Credentials::Gcp {
2921×
                    service_account_key: key,
2931×
                })
294
            }
2952×
            Some("azure") => Ok(Credentials::Azure {
2961×
                tenant_id: field("tenant_id")?,
2971×
                client_id: field("client_id")?,
2981×
                client_secret: field("client_secret")?,
299
            }),
3001×
            _ => Err(Error::Backend(
3011×
                "credentials need a kind: aws, gcp or azure".into(),
3021×
            )),
303
        }
3047×
    }
305
}
306
307
/// Finds the credentials a program keeps for a store URL.
308
pub type CredentialsLookup = fn(&str) -> Option<Credentials>;
309
310
static CREDENTIALS: Mutex<Option<CredentialsLookup>> = Mutex::new(None);
311
312
/// Have stores opened by URL (as a repository's `storage.url` is) use the
313
/// credentials `lookup` finds for it, where it finds any.
3140×
pub fn set_credentials_lookup(lookup: CredentialsLookup) {
3150×
    *CREDENTIALS.lock().unwrap_or_else(|p| p.into_inner()) = Some(lookup);
3160×
}
317
318
/// A parsed store URL: `SCHEME://HOST/PATH?PARAMS`.
319
#[derive(Clone, Debug, PartialEq, Eq)]
320
pub struct StoreUrl {
321
    pub scheme: String,
322
    /// The bucket (S3, GCS) or the storage account (Azure).
323
    pub host: String,
324
    /// The path under the host, without leading or trailing slashes; for
325
    /// Azure the container is its first segment.
326
    pub path: String,
327
    pub params: BTreeMap<String, String>,
328
}
329
330
impl StoreUrl {
3319×
    pub fn parse(url: &str) -> Result<StoreUrl> {
3329×
        let bad = |why: &str| Error::Backend(format!("{url}: {why}"));
3339×
        let (scheme, rest) = url.split_once("://").ok_or_else(|| bad("not a URL"))?;
3348×
        let (rest, query) = match rest.split_once('?') {
3355×
            Some((r, q)) => (r, Some(q)),
3363×
            None => (rest, None),
337
        };
3388×
        let (host, path) = match rest.split_once('/') {
3396×
            Some((h, p)) => (h, p.trim_matches('/')),
3402×
            None => (rest, ""),
341
        };
3428×
        if host.is_empty() {
3431×
            return Err(bad("names no bucket"));
3447×
        }
3457×
        let mut params = BTreeMap::new();
3469×
        for pair in query.unwrap_or("").split('&').filter(|p| !p.is_empty()) {
3477×
            let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
3487×
            params.insert(k.to_string(), percent_decode(v));
3497×
        }
3507×
        Ok(StoreUrl {
3517×
            scheme: scheme.to_string(),
3527×
            host: host.to_string(),
3537×
            path: path.to_string(),
3547×
            params,
3557×
        })
3569×
    }
357
358
    /// The URL without its parameters, for messages.
3596×
    pub fn plain(&self) -> String {
3606×
        if self.path.is_empty() {
3611×
            format!("{}://{}", self.scheme, self.host)
362
        } else {
3635×
            format!("{}://{}/{}", self.scheme, self.host, self.path)
364
        }
3656×
    }
366
36710×
    pub fn param(&self, name: &str) -> Option<&str> {
36810×
        self.params.get(name).map(String::as_str)
36910×
    }
370
}
371
3727×
fn percent_decode(s: &str) -> String {
3737×
    let bytes = s.as_bytes();
3747×
    let mut out = Vec::with_capacity(bytes.len());
3757×
    let mut i = 0;
37687×
    while i < bytes.len() {
37780×
        if bytes[i] == b'%' && i + 2 < bytes.len() {
3784×
            if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
3794×
                out.push(v);
3804×
                i += 3;
3814×
                continue;
3820×
            }
38376×
        }
38476×
        out.push(bytes[i]);
38576×
        i += 1;
386
    }
3877×
    String::from_utf8_lossy(&out).into_owned()
3887×
}
389
390
/// A store on a cloud provider: the provider's client, the prefix every
391
/// key goes under, and a runtime to run the client on.
392
pub struct CloudStore {
393
    inner: Arc<dyn ObjectStore>,
394
    prefix: String,
395
    name: String,
396
    hint: &'static str,
397
    /// Always there until the store is dropped: two workers, so the
398
    /// requests of a shared store run side by side.
399
    runtime: Option<tokio::runtime::Runtime>,
400
    /// Keys `has` found missing lately (see [`Misses`]).
401
    misses: Misses,
402
}
403
404
/// How long a key found missing is taken as missing without asking again.
405
const MISS_FOR: std::time::Duration = std::time::Duration::from_secs(30);
406
407
/// Keys found missing in the last [`MISS_FOR`], so a server answering the
408
/// same question again and again does not send a request each time
409
/// (oxygenhub#228: a client's negotiate asked about ~190 objects the hub
410
/// lacked every 8 s, 45 ms a request). This process forgets a key the
411
/// moment it writes it, so its own writes are never hidden; another writer
412
/// to the same keys is seen within `MISS_FOR`.
413
#[derive(Default)]
414
struct Misses(Mutex<std::collections::HashMap<String, std::time::Instant>>);
415
416
impl Misses {
417
    /// At most this many kept; past it the oldest half is let go.
418
    const MAX: usize = 100_000;
419
4205×
    fn known(&self, key: &str) -> bool {
4215×
        let map = self.0.lock().unwrap_or_else(|p| p.into_inner());
4225×
        map.get(key).is_some_and(|t| t.elapsed() < MISS_FOR)
4235×
    }
424
4252×
    fn missed(&self, key: &str) {
4262×
        let mut map = self.0.lock().unwrap_or_else(|p| p.into_inner());
4272×
        if map.len() >= Self::MAX {
4280×
            map.retain(|_, t| t.elapsed() < MISS_FOR / 2);
4290×
            if map.len() >= Self::MAX {
4300×
                map.clear();
4310×
            }
4322×
        }
4332×
        map.insert(key.to_string(), std::time::Instant::now());
4342×
    }
435
4361×
    fn written(&self, key: &str) {
4371×
        self.0.lock().unwrap_or_else(|p| p.into_inner()).remove(key);
4381×
    }
439
}
440
441
impl Drop for CloudStore {
442
    /// Without waiting, so a store can be dropped inside a runtime too.
4431×
    fn drop(&mut self) {
4441×
        if let Some(rt) = self.runtime.take() {
4451×
            rt.shutdown_background();
4461×
        }
4471×
    }
448
}
449
450
impl CloudStore {
451
    /// Open the store a URL names. Nothing is sent yet: credentials are
452
    /// resolved here, but the bucket is first spoken to on the first call.
4531×
    pub fn open(url: &str) -> Result<CloudStore> {
4541×
        Self::open_with(url, None)
4551×
    }
456
457
    /// [`CloudStore::open`] with credentials given, which must be for
458
    /// the URL's kind of store; then only they are used.
4594×
    pub fn open_with(url: &str, given: Option<&Credentials>) -> Result<CloudStore> {
4604×
        let parsed = StoreUrl::parse(url)?;
4614×
        if let Some(c) = given.filter(|c| c.scheme() != parsed.scheme) {
4621×
            return Err(Error::Backend(format!(
4631×
                "{}: the credentials given are for {}:// stores",
4641×
                parsed.plain(),
4651×
                c.scheme()
4661×
            )));
4673×
        }
4683×
        let aws_keys = match given {
469
            Some(Credentials::Aws {
4702×
                access_key_id,
4712×
                secret_access_key,
4722×
                session_token,
4732×
            }) => Some((
4742×
                access_key_id.as_str(),
4752×
                secret_access_key.as_str(),
4762×
                session_token.as_deref(),
4772×
            )),
4781×
            _ => None,
479
        };
4803×
        let gcp_key = match given {
481
            Some(Credentials::Gcp {
4820×
                service_account_key,
4830×
            }) => Some(service_account_key.as_str()),
4843×
            _ => None,
485
        };
4863×
        let principal = match given {
487
            Some(Credentials::Azure {
4880×
                tenant_id,
4890×
                client_id,
4900×
                client_secret,
4910×
            }) => Some((
4920×
                tenant_id.as_str(),
4930×
                client_id.as_str(),
4940×
                client_secret.as_str(),
4950×
            )),
4963×
            _ => None,
497
        };
4983×
        OPENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4993×
        let runtime = tokio::runtime::Builder::new_multi_thread()
5003×
            .worker_threads(2)
5013×
            .thread_name("oxy-strata")
5023×
            .enable_all()
5033×
            .build()
5043×
            .map_err(|e| Error::Backend(format!("starting the HTTP runtime: {e}")))?;
5053×
        let (inner, prefix, hint): (Arc<dyn ObjectStore>, String, &'static str) =
5063×
            match parsed.scheme.as_str() {
5073×
                "s3" => (
5083×
                    Arc::new(aws::open(&parsed, aws_keys)?),
5093×
                    parsed.path.clone(),
510
                    aws::HINT,
511
                ),
5120×
                "gs" => (
5130×
                    Arc::new(gcp::open(&parsed, gcp_key)?),
5140×
                    parsed.path.clone(),
515
                    gcp::HINT,
516
                ),
5170×
                "az" => {
5180×
                    let (store, prefix) = azure::open(&parsed, principal)?;
5190×
                    (Arc::new(store), prefix, azure::HINT)
520
                }
5210×
                other => {
5220×
                    return Err(Error::Backend(format!(
5230×
                        "{url}: {other}:// is not a store oxy knows (s3://, gs://, az://, dir://)"
5240×
                    )))
525
                }
526
            };
5273×
        Ok(CloudStore {
5283×
            inner,
5293×
            prefix,
5303×
            name: parsed.plain(),
5313×
            hint,
5323×
            runtime: Some(runtime),
5333×
            misses: Misses::default(),
5343×
        })
5354×
    }
536
537
    /// Run a request to completion. Called from a thread that is itself
538
    /// driving async tasks (a server's handler), where blocking on another
539
    /// runtime is not allowed, the request runs on a thread of its own.
5401×
    fn block<F>(&self, f: F) -> F::Output
5411×
    where
5421×
        F: Future + Send,
5431×
        F::Output: Send,
544
    {
5451×
        let runtime = self
5461×
            .runtime
5471×
            .as_ref()
5481×
            .expect("the runtime lives as long as the store");
5491×
        let started = std::time::Instant::now();
5501×
        let out = if tokio::runtime::Handle::try_current().is_ok() {
5511×
            std::thread::scope(|s| {
5521×
                s.spawn(|| runtime.block_on(f))
5531×
                    .join()
5541×
                    .unwrap_or_else(|p| std::panic::resume_unwind(p))
5551×
            })
556
        } else {
5570×
            runtime.block_on(f)
558
        };
5591×
        CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5601×
        MICROS.fetch_add(
5611×
            started.elapsed().as_micros() as u64,
5621×
            std::sync::atomic::Ordering::Relaxed,
563
        );
5641×
        out
5651×
    }
566
5670×
    fn path(&self, key: &str) -> Result<ObjectPath> {
5680×
        check_key(key)?;
5690×
        let full = if self.prefix.is_empty() {
5700×
            key.to_string()
571
        } else {
5720×
            format!("{}/{key}", self.prefix)
573
        };
5740×
        ObjectPath::parse(&full).map_err(|e| Error::Backend(format!("{full}: {e}")))
5750×
    }
576
577
    /// Our error for the provider's, with what to do next where it helps.
5780×
    fn map(&self, e: object_store::Error, key: &str) -> Error {
579
        use object_store::Error as E;
5800×
        match e {
5810×
            E::NotFound { .. } => Error::NotFound(key.to_string()),
5820×
            E::AlreadyExists { .. } => Error::Exists(key.to_string()),
5830×
            E::Precondition { .. } | E::NotModified { .. } => Error::Conflict(key.to_string()),
5840×
            other => {
5850×
                let text = other.to_string();
5860×
                let lower = text.to_ascii_lowercase();
5870×
                let advice = if lower.contains("403")
5880×
                    || lower.contains("accessdenied")
5890×
                    || lower.contains("forbidden")
5900×
                    || lower.contains("authorizationpermissionmismatch")
591
                {
5920×
                    format!(
593
                        ": access denied; the credentials in use may not do this on {}: {}",
594
                        self.name, self.hint
595
                    )
5960×
                } else if lower.contains("credential") || lower.contains("no valid credentials") {
5970×
                    format!(": no usable credentials: {}", self.hint)
5980×
                } else if lower.contains("nosuchbucket")
5990×
                    || lower.contains("bucketnotfound")
6000×
                    || lower.contains("containernotfound")
601
                {
6020×
                    format!(
603
                        ": {} does not exist, or the credentials cannot see it",
604
                        self.name
605
                    )
6060×
                } else if lower.contains("dns")
6070×
                    || lower.contains("connect")
6080×
                    || lower.contains("timed out")
609
                {
6100×
                    ": cannot reach the service; check the network, the endpoint and the region"
6110×
                        .to_string()
612
                } else {
6130×
                    String::new()
614
                };
6150×
                Error::Backend(format!("{}: {text}{advice}", self.name))
616
            }
617
        }
6180×
    }
619
6202×
    fn version_of(e_tag: Option<String>, version: Option<String>) -> Version {
6212×
        Version(format!(
6222×
            "{}\t{}",
6232×
            e_tag.unwrap_or_default(),
6242×
            version.unwrap_or_default()
6252×
        ))
6262×
    }
627
6282×
    fn update_version(v: &Version) -> UpdateVersion {
6292×
        let (e_tag, version) = v.0.split_once('\t').unwrap_or((v.0.as_str(), ""));
630
        UpdateVersion {
6312×
            e_tag: (!e_tag.is_empty()).then(|| e_tag.to_string()),
6322×
            version: (!version.is_empty()).then(|| version.to_string()),
633
        }
6342×
    }
635
}
636
637
impl Store for CloudStore {
6380×
    fn describe(&self) -> String {
6390×
        self.name.clone()
6400×
    }
641
6420×
    fn has(&self, key: &str) -> Result<bool> {
6430×
        let path = self.path(key)?;
6440×
        if self.misses.known(key) {
6450×
            return Ok(false);
6460×
        }
6470×
        match self.block(self.inner.head(&path)) {
648
            Ok(_) => {
6490×
                counted(Op::Has);
6500×
                Ok(true)
651
            }
652
            Err(object_store::Error::NotFound { .. }) => {
6530×
                counted(Op::HasMissing);
6540×
                self.misses.missed(key);
6550×
                Ok(false)
656
            }
6570×
            Err(e) => Err(self.map(e, key)),
658
        }
6590×
    }
660
6610×
    fn get(&self, key: &str) -> Result<Vec<u8>> {
6620×
        let path = self.path(key)?;
6630×
        counted(Op::Get);
6640×
        self.block(async {
6650×
            let r = self.inner.get(&path).await?;
6660×
            r.bytes().await
6670×
        })
6680×
        .map(|b| b.to_vec())
6690×
        .map_err(|e| self.map(e, key))
6700×
    }
671
6720×
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
6730×
        let path = self.path(key)?;
6740×
        if range.start > range.end {
6750×
            return Err(Error::Backend(format!(
6760×
                "{key}: bytes {}..{} is not a range",
6770×
                range.start, range.end
6780×
            )));
6790×
        }
6800×
        if range.is_empty() {
6810×
            return Ok(Vec::new());
6820×
        }
6830×
        let want = (range.end - range.start) as usize;
6840×
        counted(Op::Range);
6850×
        let bytes = self
6860×
            .block(self.inner.get_range(&path, range.clone()))
6870×
            .map_err(|e| self.map(e, key))?;
6880×
        if bytes.len() != want {
6890×
            return Err(Error::Backend(format!(
6900×
                "{key}: bytes {}..{} asked, {} returned: the object is shorter",
6910×
                range.start,
6920×
                range.end,
6930×
                bytes.len()
6940×
            )));
6950×
        }
6960×
        Ok(bytes.to_vec())
6970×
    }
698
6990×
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
7000×
        let path = self.path(key)?;
7010×
        self.misses.written(key);
7020×
        let opts = PutOptions {
7030×
            mode: PutMode::Create,
7040×
            ..Default::default()
7050×
        };
7060×
        counted(Op::Put);
7070×
        self.block(
7080×
            self.inner
7090×
                .put_opts(&path, PutPayload::from(bytes.to_vec()), opts),
710
        )
7110×
        .map(|_| ())
7120×
        .map_err(|e| self.map(e, key))
7130×
    }
714
7150×
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
716
        // Providers list by whole path segments; the asked prefix may end
717
        // mid-segment, so list its directory and filter here.
7180×
        let dir = prefix.rsplit_once('/').map(|(d, _)| d).unwrap_or("");
7190×
        let full_dir = match (self.prefix.as_str(), dir) {
7200×
            ("", "") => None,
7210×
            ("", d) => Some(d.to_string()),
7220×
            (p, "") => Some(p.to_string()),
7230×
            (p, d) => Some(format!("{p}/{d}")),
724
        };
7250×
        let full_dir = full_dir
7260×
            .map(|d| ObjectPath::parse(&d).map_err(|e| Error::Backend(format!("{d}: {e}"))))
7270×
            .transpose()?;
7280×
        counted(Op::List);
7290×
        let metas: Vec<object_store::ObjectMeta> = self
7300×
            .block(self.inner.list(full_dir.as_ref()).try_collect())
7310×
            .map_err(|e| self.map(e, prefix))?;
7320×
        let strip = if self.prefix.is_empty() {
7330×
            String::new()
734
        } else {
7350×
            format!("{}/", self.prefix)
736
        };
7370×
        let mut out: Vec<Entry> = metas
7380×
            .into_iter()
7390×
            .filter_map(|m| {
7400×
                let loc = m.location.to_string();
7410×
                let key = loc.strip_prefix(&strip)?;
7420×
                key.starts_with(prefix).then(|| Entry {
7430×
                    key: key.to_string(),
7440×
                    size: m.size,
7450×
                    modified_ms: u64::try_from(m.last_modified.timestamp_millis()).ok(),
7460×
                })
7470×
            })
7480×
            .collect();
7490×
        out.sort_by(|a, b| a.key.cmp(&b.key));
7500×
        Ok(out)
7510×
    }
752
7530×
    fn delete(&self, key: &str) -> Result<()> {
7540×
        let path = self.path(key)?;
7550×
        counted(Op::Delete);
7560×
        match self.block(self.inner.delete(&path)) {
7570×
            Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()),
7580×
            Err(e) => Err(self.map(e, key)),
759
        }
7600×
    }
761
7620×
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
7630×
        let path = self.path(key)?;
7640×
        counted(Op::ReadRef);
7650×
        let got = self.block(async {
7660×
            let r = self.inner.get_opts(&path, GetOptions::default()).await?;
7670×
            let meta = r.meta.clone();
7680×
            let bytes = r.bytes().await?;
7690×
            Ok::<_, object_store::Error>((bytes, meta))
7700×
        });
7710×
        match got {
7720×
            Ok((bytes, meta)) => Ok(Some((
7730×
                bytes.to_vec(),
7740×
                Self::version_of(meta.e_tag, meta.version),
7750×
            ))),
7760×
            Err(object_store::Error::NotFound { .. }) => Ok(None),
7770×
            Err(e) => Err(self.map(e, key)),
778
        }
7790×
    }
780
7810×
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
7820×
        let path = self.path(key)?;
7830×
        self.misses.written(key);
7840×
        let mode = match expected {
7850×
            None => PutMode::Create,
7860×
            Some(v) => PutMode::Update(Self::update_version(v)),
787
        };
7880×
        let opts = PutOptions {
7890×
            mode,
7900×
            ..Default::default()
7910×
        };
7920×
        counted(Op::WriteRef);
7930×
        let put = self
7940×
            .block(
7950×
                self.inner
7960×
                    .put_opts(&path, PutPayload::from(bytes.to_vec()), opts),
797
            )
7980×
            .map_err(|e| match self.map(e, key) {
799
                // A record that exists when none was expected is a lost
800
                // race too, not a misuse of put_new.
8010×
                Error::Exists(k) => Error::Conflict(k),
8020×
                other => other,
8030×
            })?;
8040×
        Ok(Self::version_of(put.e_tag, put.version))
8050×
    }
806
}
807
808
#[cfg(test)]
809
mod tests {
810
811
    /// A miss is remembered until the key is written, or for MISS_FOR.
812
    #[test]
8131×
    fn a_miss_is_remembered_until_written() {
8141×
        let m = super::Misses::default();
8151×
        assert!(!m.known("loose/ab/cd"));
8161×
        m.missed("loose/ab/cd");
8171×
        assert!(m.known("loose/ab/cd") && !m.known("loose/ab/ce"));
8181×
        m.written("loose/ab/cd");
8191×
        assert!(!m.known("loose/ab/cd"), "a write forgets the miss");
8201×
        m.missed("old");
8211×
        m.0.lock()
8221×
            .unwrap()
8231×
            .insert("old".into(), std::time::Instant::now() - super::MISS_FOR);
8241×
        assert!(!m.known("old"), "a miss expires");
8251×
    }
826
827
    /// Every kind of request is reported, once and by its own name.
828
    #[test]
8291×
    fn stats_name_every_kind_of_request() {
8301×
        let names: Vec<&str> = super::stats().ops().map(|(n, _)| n).collect();
8311×
        assert_eq!(names.len(), super::Op::ALL.len());
8321×
        let mut unique = names.clone();
8331×
        unique.sort();
8341×
        unique.dedup();
8351×
        assert_eq!(unique.len(), names.len());
8361×
        assert!(names.contains(&"has_missing") && names.contains(&"range"));
8371×
    }
838
839
    /// One client per store and credentials (oxygenhub#234): opening the
840
    /// same again shares it, and only a new one counts as opened.
841
    #[test]
8421×
    fn a_store_opened_again_shares_its_client() {
8431×
        let creds = |k: &str| Credentials::Aws {
8443×
            access_key_id: k.into(),
8453×
            secret_access_key: "s".into(),
8463×
            session_token: None,
8473×
        };
8481×
        let url = "s3://oxy-shared-test/repos/a?region=eu-west-2";
8491×
        let before = super::stats().opens;
8501×
        let a = super::shared(url, Some(creds("one"))).unwrap();
8511×
        let b = super::shared(url, Some(creds("one"))).unwrap();
8521×
        assert!(std::sync::Arc::ptr_eq(&a, &b));
8531×
        let other_keys = super::shared(url, Some(creds("two"))).unwrap();
8541×
        assert!(
8551×
            !std::sync::Arc::ptr_eq(&a, &other_keys),
856
            "other credentials, another client"
857
        );
8581×
        assert!(
8591×
            super::stats().opens - before >= 2,
860
            "two clients opened (other tests may open more)"
861
        );
8621×
    }
863
864
    #[tokio::test]
8651×
    async fn a_store_can_be_used_from_inside_a_runtime() {
866
        // As a server's handler would: blocking on the store's own runtime
867
        // from here must neither panic nor deadlock, and nor must dropping it.
8681×
        let store = CloudStore::open(
8691×
            "s3://oxy-no-such-bucket/p?region=eu-west-2&endpoint=http://127.0.0.1:9",
870
        )
8711×
        .unwrap();
8721×
        assert_eq!(store.block(async { 7 }), 7);
8731×
        drop(store);
8741×
    }
875
876
    #[test]
8771×
    fn credentials_round_trip_and_never_show_their_secret() {
8781×
        let aws = Credentials::Aws {
8791×
            access_key_id: "AKIDEXAMPLE".into(),
8801×
            secret_access_key: "wJalrXUtnFEMI".into(),
8811×
            session_token: None,
8821×
        };
8831×
        assert_eq!(Credentials::from_json(&aws.to_json()).unwrap(), aws);
8841×
        assert_eq!(format!("{aws:?}"), "Aws(AKIDEXAMPLE, secret hidden)");
8851×
        let az = Credentials::Azure {
8861×
            tenant_id: "t".into(),
8871×
            client_id: "c".into(),
8881×
            client_secret: "s3cr3t".into(),
8891×
        };
8901×
        assert_eq!(Credentials::from_json(&az.to_json()).unwrap(), az);
8911×
        assert!(!format!("{az:?}").contains("s3cr3t"));
8921×
        let key = r#"{"type":"service_account","client_email":"x@y","private_key":"k"}"#;
8931×
        let gcp = Credentials::Gcp {
8941×
            service_account_key: key.into(),
8951×
        };
8961×
        assert_eq!(Credentials::from_json(&gcp.to_json()).unwrap(), gcp);
8971×
        assert!(!format!("{gcp:?}").contains("private_key"));
8984×
        for (bad, why) in [
8991×
            (r#"{"kind":"aws","access_key_id":"a"}"#, "secret_access_key"),
9001×
            (
9011×
                r#"{"kind":"gcp","service_account_key":"{\"type\":\"authorized_user\"}"}"#,
9021×
                "not a service account key",
9031×
            ),
9041×
            (r#"{"kind":"ftp"}"#, "aws, gcp or azure"),
9051×
            ("nope", "not JSON"),
9061×
        ] {
9074×
            let e = Credentials::from_json(bad).unwrap_err().to_string();
9084×
            assert!(e.contains(why), "{bad}: {e}");
909
        }
9101×
        let e = CloudStore::open_with("gs://bucket/p", Some(&aws))
9111×
            .err()
9121×
            .unwrap()
9131×
            .to_string();
9141×
        assert!(e.contains("are for s3:// stores"), "{e}");
9151×
    }
916
917
    use super::*;
918
919
    #[test]
9201×
    fn urls_parse_with_their_parameters() {
9211×
        let u =
9221×
            StoreUrl::parse("s3://my-bucket/repos/oxygen?profile=work&region=eu-west-2").unwrap();
9231×
        assert_eq!(u.scheme, "s3");
9241×
        assert_eq!(u.host, "my-bucket");
9251×
        assert_eq!(u.path, "repos/oxygen");
9261×
        assert_eq!(u.param("profile"), Some("work"));
9271×
        assert_eq!(u.param("region"), Some("eu-west-2"));
9281×
        assert_eq!(u.plain(), "s3://my-bucket/repos/oxygen");
9291×
        let u = StoreUrl::parse("gs://bucket").unwrap();
9301×
        assert_eq!((u.host.as_str(), u.path.as_str()), ("bucket", ""));
9311×
        assert_eq!(u.plain(), "gs://bucket");
9321×
        let u = StoreUrl::parse("az://acct/container/a/b/?endpoint=http%3A%2F%2F127.0.0.1%3A10000")
9331×
            .unwrap();
9341×
        assert_eq!(u.path, "container/a/b");
9351×
        assert_eq!(u.param("endpoint"), Some("http://127.0.0.1:10000"));
9361×
        assert!(StoreUrl::parse("s3://").is_err());
9371×
        assert!(StoreUrl::parse("nonsense").is_err());
9381×
    }
939
940
    #[test]
9411×
    fn versions_carry_both_an_etag_and_a_generation() {
9421×
        let v = CloudStore::version_of(Some("\"abc\"".into()), Some("17".into()));
9431×
        let u = CloudStore::update_version(&v);
9441×
        assert_eq!(u.e_tag.as_deref(), Some("\"abc\""));
9451×
        assert_eq!(u.version.as_deref(), Some("17"));
9461×
        let u = CloudStore::update_version(&CloudStore::version_of(None, Some("3".into())));
9471×
        assert_eq!((u.e_tag, u.version.as_deref()), (None, Some("3")));
9481×
    }
949
}