OXYGENHUB

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

357 of 616 lines run, 47 of 197 functions · run #304 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
}
401
402
impl Drop for CloudStore {
403
    /// Without waiting, so a store can be dropped inside a runtime too.
4041×
    fn drop(&mut self) {
4051×
        if let Some(rt) = self.runtime.take() {
4061×
            rt.shutdown_background();
4071×
        }
4081×
    }
409
}
410
411
impl CloudStore {
412
    /// Open the store a URL names. Nothing is sent yet: credentials are
413
    /// resolved here, but the bucket is first spoken to on the first call.
4141×
    pub fn open(url: &str) -> Result<CloudStore> {
4151×
        Self::open_with(url, None)
4161×
    }
417
418
    /// [`CloudStore::open`] with credentials given, which must be for
419
    /// the URL's kind of store; then only they are used.
4204×
    pub fn open_with(url: &str, given: Option<&Credentials>) -> Result<CloudStore> {
4214×
        let parsed = StoreUrl::parse(url)?;
4224×
        if let Some(c) = given.filter(|c| c.scheme() != parsed.scheme) {
4231×
            return Err(Error::Backend(format!(
4241×
                "{}: the credentials given are for {}:// stores",
4251×
                parsed.plain(),
4261×
                c.scheme()
4271×
            )));
4283×
        }
4293×
        let aws_keys = match given {
430
            Some(Credentials::Aws {
4312×
                access_key_id,
4322×
                secret_access_key,
4332×
                session_token,
4342×
            }) => Some((
4352×
                access_key_id.as_str(),
4362×
                secret_access_key.as_str(),
4372×
                session_token.as_deref(),
4382×
            )),
4391×
            _ => None,
440
        };
4413×
        let gcp_key = match given {
442
            Some(Credentials::Gcp {
4430×
                service_account_key,
4440×
            }) => Some(service_account_key.as_str()),
4453×
            _ => None,
446
        };
4473×
        let principal = match given {
448
            Some(Credentials::Azure {
4490×
                tenant_id,
4500×
                client_id,
4510×
                client_secret,
4520×
            }) => Some((
4530×
                tenant_id.as_str(),
4540×
                client_id.as_str(),
4550×
                client_secret.as_str(),
4560×
            )),
4573×
            _ => None,
458
        };
4593×
        OPENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4603×
        let runtime = tokio::runtime::Builder::new_multi_thread()
4613×
            .worker_threads(2)
4623×
            .thread_name("oxy-strata")
4633×
            .enable_all()
4643×
            .build()
4653×
            .map_err(|e| Error::Backend(format!("starting the HTTP runtime: {e}")))?;
4663×
        let (inner, prefix, hint): (Arc<dyn ObjectStore>, String, &'static str) =
4673×
            match parsed.scheme.as_str() {
4683×
                "s3" => (
4693×
                    Arc::new(aws::open(&parsed, aws_keys)?),
4703×
                    parsed.path.clone(),
471
                    aws::HINT,
472
                ),
4730×
                "gs" => (
4740×
                    Arc::new(gcp::open(&parsed, gcp_key)?),
4750×
                    parsed.path.clone(),
476
                    gcp::HINT,
477
                ),
4780×
                "az" => {
4790×
                    let (store, prefix) = azure::open(&parsed, principal)?;
4800×
                    (Arc::new(store), prefix, azure::HINT)
481
                }
4820×
                other => {
4830×
                    return Err(Error::Backend(format!(
4840×
                        "{url}: {other}:// is not a store oxy knows (s3://, gs://, az://, dir://)"
4850×
                    )))
486
                }
487
            };
4883×
        Ok(CloudStore {
4893×
            inner,
4903×
            prefix,
4913×
            name: parsed.plain(),
4923×
            hint,
4933×
            runtime: Some(runtime),
4943×
        })
4954×
    }
496
497
    /// Run a request to completion. Called from a thread that is itself
498
    /// driving async tasks (a server's handler), where blocking on another
499
    /// runtime is not allowed, the request runs on a thread of its own.
5001×
    fn block<F>(&self, f: F) -> F::Output
5011×
    where
5021×
        F: Future + Send,
5031×
        F::Output: Send,
504
    {
5051×
        let runtime = self
5061×
            .runtime
5071×
            .as_ref()
5081×
            .expect("the runtime lives as long as the store");
5091×
        let started = std::time::Instant::now();
5101×
        let out = if tokio::runtime::Handle::try_current().is_ok() {
5111×
            std::thread::scope(|s| {
5121×
                s.spawn(|| runtime.block_on(f))
5131×
                    .join()
5141×
                    .unwrap_or_else(|p| std::panic::resume_unwind(p))
5151×
            })
516
        } else {
5170×
            runtime.block_on(f)
518
        };
5191×
        CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5201×
        MICROS.fetch_add(
5211×
            started.elapsed().as_micros() as u64,
5221×
            std::sync::atomic::Ordering::Relaxed,
523
        );
5241×
        out
5251×
    }
526
5270×
    fn path(&self, key: &str) -> Result<ObjectPath> {
5280×
        check_key(key)?;
5290×
        let full = if self.prefix.is_empty() {
5300×
            key.to_string()
531
        } else {
5320×
            format!("{}/{key}", self.prefix)
533
        };
5340×
        ObjectPath::parse(&full).map_err(|e| Error::Backend(format!("{full}: {e}")))
5350×
    }
536
537
    /// Our error for the provider's, with what to do next where it helps.
5380×
    fn map(&self, e: object_store::Error, key: &str) -> Error {
539
        use object_store::Error as E;
5400×
        match e {
5410×
            E::NotFound { .. } => Error::NotFound(key.to_string()),
5420×
            E::AlreadyExists { .. } => Error::Exists(key.to_string()),
5430×
            E::Precondition { .. } | E::NotModified { .. } => Error::Conflict(key.to_string()),
5440×
            other => {
5450×
                let text = other.to_string();
5460×
                let lower = text.to_ascii_lowercase();
5470×
                let advice = if lower.contains("403")
5480×
                    || lower.contains("accessdenied")
5490×
                    || lower.contains("forbidden")
5500×
                    || lower.contains("authorizationpermissionmismatch")
551
                {
5520×
                    format!(
553
                        ": access denied; the credentials in use may not do this on {}: {}",
554
                        self.name, self.hint
555
                    )
5560×
                } else if lower.contains("credential") || lower.contains("no valid credentials") {
5570×
                    format!(": no usable credentials: {}", self.hint)
5580×
                } else if lower.contains("nosuchbucket")
5590×
                    || lower.contains("bucketnotfound")
5600×
                    || lower.contains("containernotfound")
561
                {
5620×
                    format!(
563
                        ": {} does not exist, or the credentials cannot see it",
564
                        self.name
565
                    )
5660×
                } else if lower.contains("dns")
5670×
                    || lower.contains("connect")
5680×
                    || lower.contains("timed out")
569
                {
5700×
                    ": cannot reach the service; check the network, the endpoint and the region"
5710×
                        .to_string()
572
                } else {
5730×
                    String::new()
574
                };
5750×
                Error::Backend(format!("{}: {text}{advice}", self.name))
576
            }
577
        }
5780×
    }
579
5802×
    fn version_of(e_tag: Option<String>, version: Option<String>) -> Version {
5812×
        Version(format!(
5822×
            "{}\t{}",
5832×
            e_tag.unwrap_or_default(),
5842×
            version.unwrap_or_default()
5852×
        ))
5862×
    }
587
5882×
    fn update_version(v: &Version) -> UpdateVersion {
5892×
        let (e_tag, version) = v.0.split_once('\t').unwrap_or((v.0.as_str(), ""));
590
        UpdateVersion {
5912×
            e_tag: (!e_tag.is_empty()).then(|| e_tag.to_string()),
5922×
            version: (!version.is_empty()).then(|| version.to_string()),
593
        }
5942×
    }
595
}
596
597
impl Store for CloudStore {
5980×
    fn describe(&self) -> String {
5990×
        self.name.clone()
6000×
    }
601
6020×
    fn has(&self, key: &str) -> Result<bool> {
6030×
        let path = self.path(key)?;
6040×
        match self.block(self.inner.head(&path)) {
605
            Ok(_) => {
6060×
                counted(Op::Has);
6070×
                Ok(true)
608
            }
609
            Err(object_store::Error::NotFound { .. }) => {
6100×
                counted(Op::HasMissing);
6110×
                Ok(false)
612
            }
6130×
            Err(e) => Err(self.map(e, key)),
614
        }
6150×
    }
616
6170×
    fn get(&self, key: &str) -> Result<Vec<u8>> {
6180×
        let path = self.path(key)?;
6190×
        counted(Op::Get);
6200×
        self.block(async {
6210×
            let r = self.inner.get(&path).await?;
6220×
            r.bytes().await
6230×
        })
6240×
        .map(|b| b.to_vec())
6250×
        .map_err(|e| self.map(e, key))
6260×
    }
627
6280×
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
6290×
        let path = self.path(key)?;
6300×
        if range.start > range.end {
6310×
            return Err(Error::Backend(format!(
6320×
                "{key}: bytes {}..{} is not a range",
6330×
                range.start, range.end
6340×
            )));
6350×
        }
6360×
        if range.is_empty() {
6370×
            return Ok(Vec::new());
6380×
        }
6390×
        let want = (range.end - range.start) as usize;
6400×
        counted(Op::Range);
6410×
        let bytes = self
6420×
            .block(self.inner.get_range(&path, range.clone()))
6430×
            .map_err(|e| self.map(e, key))?;
6440×
        if bytes.len() != want {
6450×
            return Err(Error::Backend(format!(
6460×
                "{key}: bytes {}..{} asked, {} returned: the object is shorter",
6470×
                range.start,
6480×
                range.end,
6490×
                bytes.len()
6500×
            )));
6510×
        }
6520×
        Ok(bytes.to_vec())
6530×
    }
654
6550×
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
6560×
        let path = self.path(key)?;
6570×
        let opts = PutOptions {
6580×
            mode: PutMode::Create,
6590×
            ..Default::default()
6600×
        };
6610×
        counted(Op::Put);
6620×
        self.block(
6630×
            self.inner
6640×
                .put_opts(&path, PutPayload::from(bytes.to_vec()), opts),
665
        )
6660×
        .map(|_| ())
6670×
        .map_err(|e| self.map(e, key))
6680×
    }
669
6700×
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
671
        // Providers list by whole path segments; the asked prefix may end
672
        // mid-segment, so list its directory and filter here.
6730×
        let dir = prefix.rsplit_once('/').map(|(d, _)| d).unwrap_or("");
6740×
        let full_dir = match (self.prefix.as_str(), dir) {
6750×
            ("", "") => None,
6760×
            ("", d) => Some(d.to_string()),
6770×
            (p, "") => Some(p.to_string()),
6780×
            (p, d) => Some(format!("{p}/{d}")),
679
        };
6800×
        let full_dir = full_dir
6810×
            .map(|d| ObjectPath::parse(&d).map_err(|e| Error::Backend(format!("{d}: {e}"))))
6820×
            .transpose()?;
6830×
        counted(Op::List);
6840×
        let metas: Vec<object_store::ObjectMeta> = self
6850×
            .block(self.inner.list(full_dir.as_ref()).try_collect())
6860×
            .map_err(|e| self.map(e, prefix))?;
6870×
        let strip = if self.prefix.is_empty() {
6880×
            String::new()
689
        } else {
6900×
            format!("{}/", self.prefix)
691
        };
6920×
        let mut out: Vec<Entry> = metas
6930×
            .into_iter()
6940×
            .filter_map(|m| {
6950×
                let loc = m.location.to_string();
6960×
                let key = loc.strip_prefix(&strip)?;
6970×
                key.starts_with(prefix).then(|| Entry {
6980×
                    key: key.to_string(),
6990×
                    size: m.size,
7000×
                    modified_ms: u64::try_from(m.last_modified.timestamp_millis()).ok(),
7010×
                })
7020×
            })
7030×
            .collect();
7040×
        out.sort_by(|a, b| a.key.cmp(&b.key));
7050×
        Ok(out)
7060×
    }
707
7080×
    fn delete(&self, key: &str) -> Result<()> {
7090×
        let path = self.path(key)?;
7100×
        counted(Op::Delete);
7110×
        match self.block(self.inner.delete(&path)) {
7120×
            Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()),
7130×
            Err(e) => Err(self.map(e, key)),
714
        }
7150×
    }
716
7170×
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
7180×
        let path = self.path(key)?;
7190×
        counted(Op::ReadRef);
7200×
        let got = self.block(async {
7210×
            let r = self.inner.get_opts(&path, GetOptions::default()).await?;
7220×
            let meta = r.meta.clone();
7230×
            let bytes = r.bytes().await?;
7240×
            Ok::<_, object_store::Error>((bytes, meta))
7250×
        });
7260×
        match got {
7270×
            Ok((bytes, meta)) => Ok(Some((
7280×
                bytes.to_vec(),
7290×
                Self::version_of(meta.e_tag, meta.version),
7300×
            ))),
7310×
            Err(object_store::Error::NotFound { .. }) => Ok(None),
7320×
            Err(e) => Err(self.map(e, key)),
733
        }
7340×
    }
735
7360×
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
7370×
        let path = self.path(key)?;
7380×
        let mode = match expected {
7390×
            None => PutMode::Create,
7400×
            Some(v) => PutMode::Update(Self::update_version(v)),
741
        };
7420×
        let opts = PutOptions {
7430×
            mode,
7440×
            ..Default::default()
7450×
        };
7460×
        counted(Op::WriteRef);
7470×
        let put = self
7480×
            .block(
7490×
                self.inner
7500×
                    .put_opts(&path, PutPayload::from(bytes.to_vec()), opts),
751
            )
7520×
            .map_err(|e| match self.map(e, key) {
753
                // A record that exists when none was expected is a lost
754
                // race too, not a misuse of put_new.
7550×
                Error::Exists(k) => Error::Conflict(k),
7560×
                other => other,
7570×
            })?;
7580×
        Ok(Self::version_of(put.e_tag, put.version))
7590×
    }
760
}
761
762
#[cfg(test)]
763
mod tests {
764
765
    /// Every kind of request is reported, once and by its own name.
766
    #[test]
7671×
    fn stats_name_every_kind_of_request() {
7681×
        let names: Vec<&str> = super::stats().ops().map(|(n, _)| n).collect();
7691×
        assert_eq!(names.len(), super::Op::ALL.len());
7701×
        let mut unique = names.clone();
7711×
        unique.sort();
7721×
        unique.dedup();
7731×
        assert_eq!(unique.len(), names.len());
7741×
        assert!(names.contains(&"has_missing") && names.contains(&"range"));
7751×
    }
776
777
    /// One client per store and credentials (oxygenhub#234): opening the
778
    /// same again shares it, and only a new one counts as opened.
779
    #[test]
7801×
    fn a_store_opened_again_shares_its_client() {
7811×
        let creds = |k: &str| Credentials::Aws {
7823×
            access_key_id: k.into(),
7833×
            secret_access_key: "s".into(),
7843×
            session_token: None,
7853×
        };
7861×
        let url = "s3://oxy-shared-test/repos/a?region=eu-west-2";
7871×
        let before = super::stats().opens;
7881×
        let a = super::shared(url, Some(creds("one"))).unwrap();
7891×
        let b = super::shared(url, Some(creds("one"))).unwrap();
7901×
        assert!(std::sync::Arc::ptr_eq(&a, &b));
7911×
        let other_keys = super::shared(url, Some(creds("two"))).unwrap();
7921×
        assert!(
7931×
            !std::sync::Arc::ptr_eq(&a, &other_keys),
794
            "other credentials, another client"
795
        );
7961×
        assert!(
7971×
            super::stats().opens - before >= 2,
798
            "two clients opened (other tests may open more)"
799
        );
8001×
    }
801
802
    #[tokio::test]
8031×
    async fn a_store_can_be_used_from_inside_a_runtime() {
804
        // As a server's handler would: blocking on the store's own runtime
805
        // from here must neither panic nor deadlock, and nor must dropping it.
8061×
        let store = CloudStore::open(
8071×
            "s3://oxy-no-such-bucket/p?region=eu-west-2&endpoint=http://127.0.0.1:9",
808
        )
8091×
        .unwrap();
8101×
        assert_eq!(store.block(async { 7 }), 7);
8111×
        drop(store);
8121×
    }
813
814
    #[test]
8151×
    fn credentials_round_trip_and_never_show_their_secret() {
8161×
        let aws = Credentials::Aws {
8171×
            access_key_id: "AKIDEXAMPLE".into(),
8181×
            secret_access_key: "wJalrXUtnFEMI".into(),
8191×
            session_token: None,
8201×
        };
8211×
        assert_eq!(Credentials::from_json(&aws.to_json()).unwrap(), aws);
8221×
        assert_eq!(format!("{aws:?}"), "Aws(AKIDEXAMPLE, secret hidden)");
8231×
        let az = Credentials::Azure {
8241×
            tenant_id: "t".into(),
8251×
            client_id: "c".into(),
8261×
            client_secret: "s3cr3t".into(),
8271×
        };
8281×
        assert_eq!(Credentials::from_json(&az.to_json()).unwrap(), az);
8291×
        assert!(!format!("{az:?}").contains("s3cr3t"));
8301×
        let key = r#"{"type":"service_account","client_email":"x@y","private_key":"k"}"#;
8311×
        let gcp = Credentials::Gcp {
8321×
            service_account_key: key.into(),
8331×
        };
8341×
        assert_eq!(Credentials::from_json(&gcp.to_json()).unwrap(), gcp);
8351×
        assert!(!format!("{gcp:?}").contains("private_key"));
8364×
        for (bad, why) in [
8371×
            (r#"{"kind":"aws","access_key_id":"a"}"#, "secret_access_key"),
8381×
            (
8391×
                r#"{"kind":"gcp","service_account_key":"{\"type\":\"authorized_user\"}"}"#,
8401×
                "not a service account key",
8411×
            ),
8421×
            (r#"{"kind":"ftp"}"#, "aws, gcp or azure"),
8431×
            ("nope", "not JSON"),
8441×
        ] {
8454×
            let e = Credentials::from_json(bad).unwrap_err().to_string();
8464×
            assert!(e.contains(why), "{bad}: {e}");
847
        }
8481×
        let e = CloudStore::open_with("gs://bucket/p", Some(&aws))
8491×
            .err()
8501×
            .unwrap()
8511×
            .to_string();
8521×
        assert!(e.contains("are for s3:// stores"), "{e}");
8531×
    }
854
855
    use super::*;
856
857
    #[test]
8581×
    fn urls_parse_with_their_parameters() {
8591×
        let u =
8601×
            StoreUrl::parse("s3://my-bucket/repos/oxygen?profile=work&region=eu-west-2").unwrap();
8611×
        assert_eq!(u.scheme, "s3");
8621×
        assert_eq!(u.host, "my-bucket");
8631×
        assert_eq!(u.path, "repos/oxygen");
8641×
        assert_eq!(u.param("profile"), Some("work"));
8651×
        assert_eq!(u.param("region"), Some("eu-west-2"));
8661×
        assert_eq!(u.plain(), "s3://my-bucket/repos/oxygen");
8671×
        let u = StoreUrl::parse("gs://bucket").unwrap();
8681×
        assert_eq!((u.host.as_str(), u.path.as_str()), ("bucket", ""));
8691×
        assert_eq!(u.plain(), "gs://bucket");
8701×
        let u = StoreUrl::parse("az://acct/container/a/b/?endpoint=http%3A%2F%2F127.0.0.1%3A10000")
8711×
            .unwrap();
8721×
        assert_eq!(u.path, "container/a/b");
8731×
        assert_eq!(u.param("endpoint"), Some("http://127.0.0.1:10000"));
8741×
        assert!(StoreUrl::parse("s3://").is_err());
8751×
        assert!(StoreUrl::parse("nonsense").is_err());
8761×
    }
877
878
    #[test]
8791×
    fn versions_carry_both_an_etag_and_a_generation() {
8801×
        let v = CloudStore::version_of(Some("\"abc\"".into()), Some("17".into()));
8811×
        let u = CloudStore::update_version(&v);
8821×
        assert_eq!(u.e_tag.as_deref(), Some("\"abc\""));
8831×
        assert_eq!(u.version.as_deref(), Some("17"));
8841×
        let u = CloudStore::update_version(&CloudStore::version_of(None, Some("3".into())));
8851×
        assert_eq!((u.e_tag, u.version.as_deref()), (None, Some("3")));
8861×
    }
887
}