OXYGENHUB

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

435 of 721 lines run, 62 of 237 functions · run #327 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.
34154×
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.
37154×
    let _ = rustls::crypto::ring::default_provider().install_default();
38154×
    oxy_core::protocol::register_store_opener(open_url);
39154×
}
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
    /// A listing of a repository's packs, sent.
125
    ListPacks,
126
    /// A listing answered from [`Listings`], not sent.
127
    ListKept,
128
    Delete,
129
    ReadRef,
130
    WriteRef,
131
}
132
133
impl Op {
134
    pub const ALL: [Op; 11] = [
135
        Op::Has,
136
        Op::HasMissing,
137
        Op::Get,
138
        Op::Range,
139
        Op::Put,
140
        Op::List,
141
        Op::ListPacks,
142
        Op::ListKept,
143
        Op::Delete,
144
        Op::ReadRef,
145
        Op::WriteRef,
146
    ];
147
14811×
    pub fn name(self) -> &'static str {
14911×
        match self {
1501×
            Op::Has => "has",
1511×
            Op::HasMissing => "has_missing",
1521×
            Op::Get => "get",
1531×
            Op::Range => "range",
1541×
            Op::Put => "put",
1551×
            Op::List => "list",
1561×
            Op::ListPacks => "list_packs",
1571×
            Op::ListKept => "list_kept",
1581×
            Op::Delete => "delete",
1591×
            Op::ReadRef => "read_ref",
1601×
            Op::WriteRef => "write_ref",
161
        }
16211×
    }
163
}
164
1650×
fn counted(op: Op) {
1660×
    BY_OP[op as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1670×
}
168
169
/// What the cloud stores have done since the process started: clients
170
/// opened, requests made and the time spent in them, for a server to show
171
/// (a hub's /health).
172
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
173
pub struct Stats {
174
    pub opens: u64,
175
    pub calls: u64,
176
    pub millis: u64,
177
    /// Requests by kind, in [`Op::ALL`]'s order.
178
    pub by_op: [u64; Op::ALL.len()],
179
}
180
181
impl Stats {
182
    /// Each kind of request with how many were made.
1831×
    pub fn ops(&self) -> impl Iterator<Item = (&'static str, u64)> + '_ {
1841×
        Op::ALL
1851×
            .iter()
18611×
            .map(|op| (op.name(), self.by_op[*op as usize]))
1871×
    }
188
}
189
1903×
pub fn stats() -> Stats {
191
    use std::sync::atomic::Ordering::Relaxed;
192
    Stats {
1933×
        opens: OPENS.load(Relaxed),
1943×
        calls: CALLS.load(Relaxed),
1953×
        millis: MICROS.load(Relaxed) / 1000,
19633×
        by_op: std::array::from_fn(|i| BY_OP[i].load(Relaxed)),
197
    }
1983×
}
199
200
/// Credentials a program keeps itself and hands over, instead of the
201
/// provider's usual places: a hub keeps each repository's sealed. When a
202
/// store is opened with them, nothing from the environment or the
203
/// provider's files is used.
204
#[derive(Clone, PartialEq, Eq, Hash)]
205
pub enum Credentials {
206
    /// An S3 access key.
207
    Aws {
208
        access_key_id: String,
209
        secret_access_key: String,
210
        session_token: Option<String>,
211
    },
212
    /// A Google Cloud service account key, as the JSON Google issues.
213
    Gcp { service_account_key: String },
214
    /// An Azure service principal.
215
    Azure {
216
        tenant_id: String,
217
        client_id: String,
218
        client_secret: String,
219
    },
220
}
221
222
impl std::fmt::Debug for Credentials {
223
    /// Names the kind and the public part only: never the secret.
2243×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2253×
        match self {
2261×
            Credentials::Aws { access_key_id, .. } => {
2271×
                write!(f, "Aws({access_key_id}, secret hidden)")
228
            }
2291×
            Credentials::Gcp { .. } => write!(f, "Gcp(service account key hidden)"),
2301×
            Credentials::Azure { client_id, .. } => write!(f, "Azure({client_id}, secret hidden)"),
231
        }
2323×
    }
233
}
234
235
impl Credentials {
236
    /// The scheme of the stores these are for.
2374×
    pub fn scheme(&self) -> &'static str {
2384×
        match self {
2394×
            Credentials::Aws { .. } => "s3",
2400×
            Credentials::Gcp { .. } => "gs",
2410×
            Credentials::Azure { .. } => "az",
242
        }
2434×
    }
244
245
    /// As JSON, for keeping (sealed) and reading back with [`Credentials::from_json`].
2463×
    pub fn to_json(&self) -> String {
2473×
        let v = match self {
248
            Credentials::Aws {
2491×
                access_key_id,
2501×
                secret_access_key,
2511×
                session_token,
2521×
            } => serde_json::json!({
2531×
                "kind": "aws", "access_key_id": access_key_id, "secret_access_key": secret_access_key,
2541×
                "session_token": session_token,
255
            }),
256
            Credentials::Gcp {
2571×
                service_account_key,
258
            } => {
2591×
                serde_json::json!({ "kind": "gcp", "service_account_key": service_account_key })
260
            }
261
            Credentials::Azure {
2621×
                tenant_id,
2631×
                client_id,
2641×
                client_secret,
2651×
            } => serde_json::json!({
2661×
                "kind": "azure", "tenant_id": tenant_id, "client_id": client_id, "client_secret": client_secret,
267
            }),
268
        };
2693×
        v.to_string()
2703×
    }
271
2727×
    pub fn from_json(text: &str) -> Result<Credentials> {
2737×
        let v: serde_json::Value = serde_json::from_str(text)
2747×
            .map_err(|e| Error::Backend(format!("credentials are not JSON: {e}")))?;
27510×
        let field = |k: &str| -> Result<String> {
27610×
            v.get(k)
27710×
                .and_then(|x| x.as_str())
27810×
                .filter(|x| !x.trim().is_empty())
27910×
                .map(|x| x.trim().to_string())
28010×
                .ok_or_else(|| Error::Backend(format!("credentials need {k}")))
28110×
        };
2826×
        match v.get("kind").and_then(|k| k.as_str()) {
2836×
            Some("aws") => Ok(Credentials::Aws {
2842×
                access_key_id: field("access_key_id")?,
2852×
                secret_access_key: field("secret_access_key")?,
2861×
                session_token: field("session_token").ok(),
287
            }),
2884×
            Some("gcp") => {
2892×
                let key = field("service_account_key")?;
2902×
                let parsed: serde_json::Value = serde_json::from_str(&key).map_err(|_| {
2910×
                    Error::Backend("the service account key is not the JSON Google issues".into())
2920×
                })?;
2932×
                if parsed.get("type").and_then(|t| t.as_str()) != Some("service_account") {
2941×
                    return Err(Error::Backend(
2951×
                        "the key is not a service account key (its type is not service_account)"
2961×
                            .into(),
2971×
                    ));
2981×
                }
2991×
                Ok(Credentials::Gcp {
3001×
                    service_account_key: key,
3011×
                })
302
            }
3032×
            Some("azure") => Ok(Credentials::Azure {
3041×
                tenant_id: field("tenant_id")?,
3051×
                client_id: field("client_id")?,
3061×
                client_secret: field("client_secret")?,
307
            }),
3081×
            _ => Err(Error::Backend(
3091×
                "credentials need a kind: aws, gcp or azure".into(),
3101×
            )),
311
        }
3127×
    }
313
}
314
315
/// Finds the credentials a program keeps for a store URL.
316
pub type CredentialsLookup = fn(&str) -> Option<Credentials>;
317
318
static CREDENTIALS: Mutex<Option<CredentialsLookup>> = Mutex::new(None);
319
320
/// Have stores opened by URL (as a repository's `storage.url` is) use the
321
/// credentials `lookup` finds for it, where it finds any.
3220×
pub fn set_credentials_lookup(lookup: CredentialsLookup) {
3230×
    *CREDENTIALS.lock().unwrap_or_else(|p| p.into_inner()) = Some(lookup);
3240×
}
325
326
/// A parsed store URL: `SCHEME://HOST/PATH?PARAMS`.
327
#[derive(Clone, Debug, PartialEq, Eq)]
328
pub struct StoreUrl {
329
    pub scheme: String,
330
    /// The bucket (S3, GCS) or the storage account (Azure).
331
    pub host: String,
332
    /// The path under the host, without leading or trailing slashes; for
333
    /// Azure the container is its first segment.
334
    pub path: String,
335
    pub params: BTreeMap<String, String>,
336
}
337
338
impl StoreUrl {
3399×
    pub fn parse(url: &str) -> Result<StoreUrl> {
3409×
        let bad = |why: &str| Error::Backend(format!("{url}: {why}"));
3419×
        let (scheme, rest) = url.split_once("://").ok_or_else(|| bad("not a URL"))?;
3428×
        let (rest, query) = match rest.split_once('?') {
3435×
            Some((r, q)) => (r, Some(q)),
3443×
            None => (rest, None),
345
        };
3468×
        let (host, path) = match rest.split_once('/') {
3476×
            Some((h, p)) => (h, p.trim_matches('/')),
3482×
            None => (rest, ""),
349
        };
3508×
        if host.is_empty() {
3511×
            return Err(bad("names no bucket"));
3527×
        }
3537×
        let mut params = BTreeMap::new();
3549×
        for pair in query.unwrap_or("").split('&').filter(|p| !p.is_empty()) {
3557×
            let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
3567×
            params.insert(k.to_string(), percent_decode(v));
3577×
        }
3587×
        Ok(StoreUrl {
3597×
            scheme: scheme.to_string(),
3607×
            host: host.to_string(),
3617×
            path: path.to_string(),
3627×
            params,
3637×
        })
3649×
    }
365
366
    /// The URL without its parameters, for messages.
3676×
    pub fn plain(&self) -> String {
3686×
        if self.path.is_empty() {
3691×
            format!("{}://{}", self.scheme, self.host)
370
        } else {
3715×
            format!("{}://{}/{}", self.scheme, self.host, self.path)
372
        }
3736×
    }
374
37510×
    pub fn param(&self, name: &str) -> Option<&str> {
37610×
        self.params.get(name).map(String::as_str)
37710×
    }
378
}
379
3807×
fn percent_decode(s: &str) -> String {
3817×
    let bytes = s.as_bytes();
3827×
    let mut out = Vec::with_capacity(bytes.len());
3837×
    let mut i = 0;
38487×
    while i < bytes.len() {
38580×
        if bytes[i] == b'%' && i + 2 < bytes.len() {
3864×
            if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
3874×
                out.push(v);
3884×
                i += 3;
3894×
                continue;
3900×
            }
39176×
        }
39276×
        out.push(bytes[i]);
39376×
        i += 1;
394
    }
3957×
    String::from_utf8_lossy(&out).into_owned()
3967×
}
397
398
/// A store on a cloud provider: the provider's client, the prefix every
399
/// key goes under, and a runtime to run the client on.
400
pub struct CloudStore {
401
    inner: Arc<dyn ObjectStore>,
402
    prefix: String,
403
    name: String,
404
    hint: &'static str,
405
    /// Always there until the store is dropped: two workers, so the
406
    /// requests of a shared store run side by side.
407
    runtime: Option<tokio::runtime::Runtime>,
408
    /// Keys `has` found missing lately (see [`Misses`]).
409
    misses: Misses,
410
    /// Pack listings, kept a moment (see [`Listings`]).
411
    listings: Listings,
412
}
413
414
/// How long a key found missing is taken as missing without asking again.
415
const MISS_FOR: std::time::Duration = std::time::Duration::from_secs(30);
416
417
/// Keys found missing in the last [`MISS_FOR`], so a server answering the
418
/// same question again and again does not send a request each time
419
/// (oxygenhub#228: a client's negotiate asked about ~190 objects the hub
420
/// lacked every 8 s, 45 ms a request). This process forgets a key the
421
/// moment it writes it, so its own writes are never hidden; another writer
422
/// to the same keys is seen within `MISS_FOR`.
423
#[derive(Default)]
424
struct Misses(Mutex<std::collections::HashMap<String, std::time::Instant>>);
425
426
impl Misses {
427
    /// At most this many kept; past it the oldest half is let go.
428
    const MAX: usize = 100_000;
429
4305×
    fn known(&self, key: &str) -> bool {
4315×
        let map = self.0.lock().unwrap_or_else(|p| p.into_inner());
4325×
        map.get(key).is_some_and(|t| t.elapsed() < MISS_FOR)
4335×
    }
434
4352×
    fn missed(&self, key: &str) {
4362×
        let mut map = self.0.lock().unwrap_or_else(|p| p.into_inner());
4372×
        if map.len() >= Self::MAX {
4380×
            map.retain(|_, t| t.elapsed() < MISS_FOR / 2);
4390×
            if map.len() >= Self::MAX {
4400×
                map.clear();
4410×
            }
4422×
        }
4432×
        map.insert(key.to_string(), std::time::Instant::now());
4442×
    }
445
4461×
    fn written(&self, key: &str) {
4471×
        self.0.lock().unwrap_or_else(|p| p.into_inner()).remove(key);
4481×
    }
449
}
450
451
/// Listings kept for [`MISS_FOR`] (oxygen#116): the `pack-` keys, which
452
/// every open of a repository's store lists, so a forge serving a
453
/// repository from a bucket lists them once a while rather than once a
454
/// request. Like [`Misses`], this process forgets a listing the moment it
455
/// writes or deletes a key under it; another writer's pack is seen within
456
/// `MISS_FOR`, as a missing key is.
457
#[derive(Default)]
458
struct Listings(Mutex<std::collections::HashMap<String, (std::time::Instant, Vec<Entry>)>>);
459
460
impl Listings {
461
    /// The prefixes kept: those every open lists.
4628×
    fn kept(prefix: &str) -> bool {
4638×
        prefix == "pack-"
4648×
    }
465
4665×
    fn get(&self, prefix: &str) -> Option<Vec<Entry>> {
4675×
        if !Self::kept(prefix) {
4681×
            return None;
4694×
        }
4704×
        let map = self.0.lock().unwrap_or_else(|p| p.into_inner());
4714×
        map.get(prefix)
4724×
            .filter(|(t, _)| t.elapsed() < MISS_FOR)
4734×
            .map(|(_, e)| e.clone())
4745×
    }
475
4763×
    fn put(&self, prefix: &str, entries: &[Entry]) {
4773×
        if Self::kept(prefix) {
4782×
            self.0.lock().unwrap_or_else(|p| p.into_inner()).insert(
4792×
                prefix.to_string(),
4802×
                (std::time::Instant::now(), entries.to_vec()),
481
            );
4821×
        }
4833×
    }
484
4852×
    fn written(&self, key: &str) {
4862×
        self.0
4872×
            .lock()
4882×
            .unwrap_or_else(|p| p.into_inner())
4892×
            .retain(|prefix, _| !key.starts_with(prefix.as_str()));
4902×
    }
491
}
492
493
impl Drop for CloudStore {
494
    /// Without waiting, so a store can be dropped inside a runtime too.
4951×
    fn drop(&mut self) {
4961×
        if let Some(rt) = self.runtime.take() {
4971×
            rt.shutdown_background();
4981×
        }
4991×
    }
500
}
501
502
impl CloudStore {
503
    /// Open the store a URL names. Nothing is sent yet: credentials are
504
    /// resolved here, but the bucket is first spoken to on the first call.
5051×
    pub fn open(url: &str) -> Result<CloudStore> {
5061×
        Self::open_with(url, None)
5071×
    }
508
509
    /// [`CloudStore::open`] with credentials given, which must be for
510
    /// the URL's kind of store; then only they are used.
5114×
    pub fn open_with(url: &str, given: Option<&Credentials>) -> Result<CloudStore> {
5124×
        let parsed = StoreUrl::parse(url)?;
5134×
        if let Some(c) = given.filter(|c| c.scheme() != parsed.scheme) {
5141×
            return Err(Error::Backend(format!(
5151×
                "{}: the credentials given are for {}:// stores",
5161×
                parsed.plain(),
5171×
                c.scheme()
5181×
            )));
5193×
        }
5203×
        let aws_keys = match given {
521
            Some(Credentials::Aws {
5222×
                access_key_id,
5232×
                secret_access_key,
5242×
                session_token,
5252×
            }) => Some((
5262×
                access_key_id.as_str(),
5272×
                secret_access_key.as_str(),
5282×
                session_token.as_deref(),
5292×
            )),
5301×
            _ => None,
531
        };
5323×
        let gcp_key = match given {
533
            Some(Credentials::Gcp {
5340×
                service_account_key,
5350×
            }) => Some(service_account_key.as_str()),
5363×
            _ => None,
537
        };
5383×
        let principal = match given {
539
            Some(Credentials::Azure {
5400×
                tenant_id,
5410×
                client_id,
5420×
                client_secret,
5430×
            }) => Some((
5440×
                tenant_id.as_str(),
5450×
                client_id.as_str(),
5460×
                client_secret.as_str(),
5470×
            )),
5483×
            _ => None,
549
        };
5503×
        OPENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5513×
        let runtime = tokio::runtime::Builder::new_multi_thread()
5523×
            .worker_threads(2)
5533×
            .thread_name("oxy-strata")
5543×
            .enable_all()
5553×
            .build()
5563×
            .map_err(|e| Error::Backend(format!("starting the HTTP runtime: {e}")))?;
5573×
        let (inner, prefix, hint): (Arc<dyn ObjectStore>, String, &'static str) =
5583×
            match parsed.scheme.as_str() {
5593×
                "s3" => (
5603×
                    Arc::new(aws::open(&parsed, aws_keys)?),
5613×
                    parsed.path.clone(),
562
                    aws::HINT,
563
                ),
5640×
                "gs" => (
5650×
                    Arc::new(gcp::open(&parsed, gcp_key)?),
5660×
                    parsed.path.clone(),
567
                    gcp::HINT,
568
                ),
5690×
                "az" => {
5700×
                    let (store, prefix) = azure::open(&parsed, principal)?;
5710×
                    (Arc::new(store), prefix, azure::HINT)
572
                }
5730×
                other => {
5740×
                    return Err(Error::Backend(format!(
5750×
                        "{url}: {other}:// is not a store oxy knows (s3://, gs://, az://, dir://)"
5760×
                    )))
577
                }
578
            };
5793×
        Ok(CloudStore {
5803×
            inner,
5813×
            prefix,
5823×
            name: parsed.plain(),
5833×
            hint,
5843×
            runtime: Some(runtime),
5853×
            misses: Misses::default(),
5863×
            listings: Listings::default(),
5873×
        })
5884×
    }
589
590
    /// Run a request to completion. Called from a thread that is itself
591
    /// driving async tasks (a server's handler), where blocking on another
592
    /// runtime is not allowed, the request runs on a thread of its own.
5931×
    fn block<F>(&self, f: F) -> F::Output
5941×
    where
5951×
        F: Future + Send,
5961×
        F::Output: Send,
597
    {
5981×
        let runtime = self
5991×
            .runtime
6001×
            .as_ref()
6011×
            .expect("the runtime lives as long as the store");
6021×
        let started = std::time::Instant::now();
6031×
        let out = if tokio::runtime::Handle::try_current().is_ok() {
6041×
            std::thread::scope(|s| {
6051×
                s.spawn(|| runtime.block_on(f))
6061×
                    .join()
6071×
                    .unwrap_or_else(|p| std::panic::resume_unwind(p))
6081×
            })
609
        } else {
6100×
            runtime.block_on(f)
611
        };
6121×
        CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6131×
        MICROS.fetch_add(
6141×
            started.elapsed().as_micros() as u64,
6151×
            std::sync::atomic::Ordering::Relaxed,
616
        );
6171×
        out
6181×
    }
619
6200×
    fn path(&self, key: &str) -> Result<ObjectPath> {
6210×
        check_key(key)?;
6220×
        let full = if self.prefix.is_empty() {
6230×
            key.to_string()
624
        } else {
6250×
            format!("{}/{key}", self.prefix)
626
        };
6270×
        ObjectPath::parse(&full).map_err(|e| Error::Backend(format!("{full}: {e}")))
6280×
    }
629
630
    /// Our error for the provider's, with what to do next where it helps.
6310×
    fn map(&self, e: object_store::Error, key: &str) -> Error {
632
        use object_store::Error as E;
6330×
        match e {
6340×
            E::NotFound { .. } => Error::NotFound(key.to_string()),
6350×
            E::AlreadyExists { .. } => Error::Exists(key.to_string()),
6360×
            E::Precondition { .. } | E::NotModified { .. } => Error::Conflict(key.to_string()),
6370×
            other => {
6380×
                let text = other.to_string();
6390×
                let lower = text.to_ascii_lowercase();
6400×
                let advice = if lower.contains("403")
6410×
                    || lower.contains("accessdenied")
6420×
                    || lower.contains("forbidden")
6430×
                    || lower.contains("authorizationpermissionmismatch")
644
                {
6450×
                    format!(
646
                        ": access denied; the credentials in use may not do this on {}: {}",
647
                        self.name, self.hint
648
                    )
6490×
                } else if lower.contains("credential") || lower.contains("no valid credentials") {
6500×
                    format!(": no usable credentials: {}", self.hint)
6510×
                } else if lower.contains("nosuchbucket")
6520×
                    || lower.contains("bucketnotfound")
6530×
                    || lower.contains("containernotfound")
654
                {
6550×
                    format!(
656
                        ": {} does not exist, or the credentials cannot see it",
657
                        self.name
658
                    )
6590×
                } else if lower.contains("dns")
6600×
                    || lower.contains("connect")
6610×
                    || lower.contains("timed out")
662
                {
6630×
                    ": cannot reach the service; check the network, the endpoint and the region"
6640×
                        .to_string()
665
                } else {
6660×
                    String::new()
667
                };
6680×
                Error::Backend(format!("{}: {text}{advice}", self.name))
669
            }
670
        }
6710×
    }
672
6732×
    fn version_of(e_tag: Option<String>, version: Option<String>) -> Version {
6742×
        Version(format!(
6752×
            "{}\t{}",
6762×
            e_tag.unwrap_or_default(),
6772×
            version.unwrap_or_default()
6782×
        ))
6792×
    }
680
6812×
    fn update_version(v: &Version) -> UpdateVersion {
6822×
        let (e_tag, version) = v.0.split_once('\t').unwrap_or((v.0.as_str(), ""));
683
        UpdateVersion {
6842×
            e_tag: (!e_tag.is_empty()).then(|| e_tag.to_string()),
6852×
            version: (!version.is_empty()).then(|| version.to_string()),
686
        }
6872×
    }
688
}
689
690
impl Store for CloudStore {
6910×
    fn describe(&self) -> String {
6920×
        self.name.clone()
6930×
    }
694
6950×
    fn has(&self, key: &str) -> Result<bool> {
6960×
        let path = self.path(key)?;
6970×
        if self.misses.known(key) {
6980×
            return Ok(false);
6990×
        }
7000×
        match self.block(self.inner.head(&path)) {
701
            Ok(_) => {
7020×
                counted(Op::Has);
7030×
                Ok(true)
704
            }
705
            Err(object_store::Error::NotFound { .. }) => {
7060×
                counted(Op::HasMissing);
7070×
                self.misses.missed(key);
7080×
                Ok(false)
709
            }
7100×
            Err(e) => Err(self.map(e, key)),
711
        }
7120×
    }
713
7140×
    fn get(&self, key: &str) -> Result<Vec<u8>> {
7150×
        let path = self.path(key)?;
7160×
        counted(Op::Get);
7170×
        self.block(async {
7180×
            let r = self.inner.get(&path).await?;
7190×
            r.bytes().await
7200×
        })
7210×
        .map(|b| b.to_vec())
7220×
        .map_err(|e| self.map(e, key))
7230×
    }
724
7250×
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
7260×
        let path = self.path(key)?;
7270×
        if range.start > range.end {
7280×
            return Err(Error::Backend(format!(
7290×
                "{key}: bytes {}..{} is not a range",
7300×
                range.start, range.end
7310×
            )));
7320×
        }
7330×
        if range.is_empty() {
7340×
            return Ok(Vec::new());
7350×
        }
7360×
        let want = (range.end - range.start) as usize;
7370×
        counted(Op::Range);
7380×
        let bytes = self
7390×
            .block(self.inner.get_range(&path, range.clone()))
7400×
            .map_err(|e| self.map(e, key))?;
7410×
        if bytes.len() != want {
7420×
            return Err(Error::Backend(format!(
7430×
                "{key}: bytes {}..{} asked, {} returned: the object is shorter",
7440×
                range.start,
7450×
                range.end,
7460×
                bytes.len()
7470×
            )));
7480×
        }
7490×
        Ok(bytes.to_vec())
7500×
    }
751
7520×
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
7530×
        let path = self.path(key)?;
7540×
        self.misses.written(key);
7550×
        self.listings.written(key);
7560×
        let opts = PutOptions {
7570×
            mode: PutMode::Create,
7580×
            ..Default::default()
7590×
        };
7600×
        counted(Op::Put);
7610×
        self.block(
7620×
            self.inner
7630×
                .put_opts(&path, PutPayload::from(bytes.to_vec()), opts),
764
        )
7650×
        .map(|_| ())
7660×
        .map_err(|e| self.map(e, key))
7670×
    }
768
7690×
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
7700×
        if let Some(kept) = self.listings.get(prefix) {
7710×
            counted(Op::ListKept);
7720×
            return Ok(kept);
7730×
        }
774
        // Providers list by whole path segments; the asked prefix may end
775
        // mid-segment, so list its directory and filter here.
7760×
        let dir = prefix.rsplit_once('/').map(|(d, _)| d).unwrap_or("");
7770×
        let full_dir = match (self.prefix.as_str(), dir) {
7780×
            ("", "") => None,
7790×
            ("", d) => Some(d.to_string()),
7800×
            (p, "") => Some(p.to_string()),
7810×
            (p, d) => Some(format!("{p}/{d}")),
782
        };
7830×
        let full_dir = full_dir
7840×
            .map(|d| ObjectPath::parse(&d).map_err(|e| Error::Backend(format!("{d}: {e}"))))
7850×
            .transpose()?;
7860×
        counted(if Listings::kept(prefix) {
7870×
            Op::ListPacks
788
        } else {
7890×
            Op::List
790
        });
7910×
        let metas: Vec<object_store::ObjectMeta> = self
7920×
            .block(self.inner.list(full_dir.as_ref()).try_collect())
7930×
            .map_err(|e| self.map(e, prefix))?;
7940×
        let strip = if self.prefix.is_empty() {
7950×
            String::new()
796
        } else {
7970×
            format!("{}/", self.prefix)
798
        };
7990×
        let mut out: Vec<Entry> = metas
8000×
            .into_iter()
8010×
            .filter_map(|m| {
8020×
                let loc = m.location.to_string();
8030×
                let key = loc.strip_prefix(&strip)?;
8040×
                key.starts_with(prefix).then(|| Entry {
8050×
                    key: key.to_string(),
8060×
                    size: m.size,
8070×
                    modified_ms: u64::try_from(m.last_modified.timestamp_millis()).ok(),
8080×
                })
8090×
            })
8100×
            .collect();
8110×
        out.sort_by(|a, b| a.key.cmp(&b.key));
8120×
        self.listings.put(prefix, &out);
8130×
        Ok(out)
8140×
    }
815
8160×
    fn delete(&self, key: &str) -> Result<()> {
8170×
        let path = self.path(key)?;
8180×
        self.listings.written(key);
8190×
        counted(Op::Delete);
8200×
        match self.block(self.inner.delete(&path)) {
8210×
            Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()),
8220×
            Err(e) => Err(self.map(e, key)),
823
        }
8240×
    }
825
8260×
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
8270×
        let path = self.path(key)?;
8280×
        counted(Op::ReadRef);
8290×
        let got = self.block(async {
8300×
            let r = self.inner.get_opts(&path, GetOptions::default()).await?;
8310×
            let meta = r.meta.clone();
8320×
            let bytes = r.bytes().await?;
8330×
            Ok::<_, object_store::Error>((bytes, meta))
8340×
        });
8350×
        match got {
8360×
            Ok((bytes, meta)) => Ok(Some((
8370×
                bytes.to_vec(),
8380×
                Self::version_of(meta.e_tag, meta.version),
8390×
            ))),
8400×
            Err(object_store::Error::NotFound { .. }) => Ok(None),
8410×
            Err(e) => Err(self.map(e, key)),
842
        }
8430×
    }
844
8450×
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
8460×
        let path = self.path(key)?;
8470×
        self.misses.written(key);
8480×
        self.listings.written(key);
8490×
        let mode = match expected {
8500×
            None => PutMode::Create,
8510×
            Some(v) => PutMode::Update(Self::update_version(v)),
852
        };
8530×
        let opts = PutOptions {
8540×
            mode,
8550×
            ..Default::default()
8560×
        };
8570×
        counted(Op::WriteRef);
8580×
        let put = self
8590×
            .block(
8600×
                self.inner
8610×
                    .put_opts(&path, PutPayload::from(bytes.to_vec()), opts),
862
            )
8630×
            .map_err(|e| match self.map(e, key) {
864
                // A record that exists when none was expected is a lost
865
                // race too, not a misuse of put_new.
8660×
                Error::Exists(k) => Error::Conflict(k),
8670×
                other => other,
8680×
            })?;
8690×
        Ok(Self::version_of(put.e_tag, put.version))
8700×
    }
871
}
872
873
#[cfg(test)]
874
mod tests {
875
876
    /// A miss is remembered until the key is written, or for MISS_FOR.
877
    #[test]
8781×
    fn a_miss_is_remembered_until_written() {
8791×
        let m = super::Misses::default();
8801×
        assert!(!m.known("loose/ab/cd"));
8811×
        m.missed("loose/ab/cd");
8821×
        assert!(m.known("loose/ab/cd") && !m.known("loose/ab/ce"));
8831×
        m.written("loose/ab/cd");
8841×
        assert!(!m.known("loose/ab/cd"), "a write forgets the miss");
8851×
        m.missed("old");
8861×
        m.0.lock()
8871×
            .unwrap()
8881×
            .insert("old".into(), std::time::Instant::now() - super::MISS_FOR);
8891×
        assert!(!m.known("old"), "a miss expires");
8901×
    }
891
892
    /// Every kind of request is reported, once and by its own name.
893
    /// The pack listing is kept until a pack key is written or deleted
894
    /// here, or for MISS_FOR; other prefixes are never kept (oxygen#116).
895
    #[test]
8961×
    fn the_pack_listing_is_kept_until_a_pack_is_written() {
8971×
        let l = super::Listings::default();
8981×
        let e = |k: &str| oxy_core::strata::Entry {
8993×
            key: k.into(),
900
            size: 1,
9013×
            modified_ms: None,
9023×
        };
9031×
        l.put("pack-", &[e("pack-1.idx")]);
9041×
        assert_eq!(l.get("pack-").map(|v| v.len()), Some(1));
9051×
        l.put("loose/", &[e("loose/ab")]);
9061×
        assert!(l.get("loose/").is_none(), "only the pack listing is kept");
9071×
        l.written("loose/cd");
9081×
        assert!(l.get("pack-").is_some(), "a loose object leaves it");
9091×
        l.written("pack-2.pack");
9101×
        assert!(l.get("pack-").is_none(), "a new pack forgets it");
9111×
        l.put("pack-", &[e("pack-1.idx")]);
9121×
        l.0.lock().unwrap().get_mut("pack-").unwrap().0 -= super::MISS_FOR;
9131×
        assert!(l.get("pack-").is_none(), "and it ages out");
9141×
    }
915
916
    #[test]
9171×
    fn stats_name_every_kind_of_request() {
9181×
        let names: Vec<&str> = super::stats().ops().map(|(n, _)| n).collect();
9191×
        assert_eq!(names.len(), super::Op::ALL.len());
9201×
        let mut unique = names.clone();
9211×
        unique.sort();
9221×
        unique.dedup();
9231×
        assert_eq!(unique.len(), names.len());
9241×
        assert!(names.contains(&"has_missing") && names.contains(&"range"));
9251×
    }
926
927
    /// One client per store and credentials (oxygenhub#234): opening the
928
    /// same again shares it, and only a new one counts as opened.
929
    #[test]
9301×
    fn a_store_opened_again_shares_its_client() {
9311×
        let creds = |k: &str| Credentials::Aws {
9323×
            access_key_id: k.into(),
9333×
            secret_access_key: "s".into(),
9343×
            session_token: None,
9353×
        };
9361×
        let url = "s3://oxy-shared-test/repos/a?region=eu-west-2";
9371×
        let before = super::stats().opens;
9381×
        let a = super::shared(url, Some(creds("one"))).unwrap();
9391×
        let b = super::shared(url, Some(creds("one"))).unwrap();
9401×
        assert!(std::sync::Arc::ptr_eq(&a, &b));
9411×
        let other_keys = super::shared(url, Some(creds("two"))).unwrap();
9421×
        assert!(
9431×
            !std::sync::Arc::ptr_eq(&a, &other_keys),
944
            "other credentials, another client"
945
        );
9461×
        assert!(
9471×
            super::stats().opens - before >= 2,
948
            "two clients opened (other tests may open more)"
949
        );
9501×
    }
951
952
    #[tokio::test]
9531×
    async fn a_store_can_be_used_from_inside_a_runtime() {
954
        // As a server's handler would: blocking on the store's own runtime
955
        // from here must neither panic nor deadlock, and nor must dropping it.
9561×
        let store = CloudStore::open(
9571×
            "s3://oxy-no-such-bucket/p?region=eu-west-2&endpoint=http://127.0.0.1:9",
958
        )
9591×
        .unwrap();
9601×
        assert_eq!(store.block(async { 7 }), 7);
9611×
        drop(store);
9621×
    }
963
964
    #[test]
9651×
    fn credentials_round_trip_and_never_show_their_secret() {
9661×
        let aws = Credentials::Aws {
9671×
            access_key_id: "AKIDEXAMPLE".into(),
9681×
            secret_access_key: "wJalrXUtnFEMI".into(),
9691×
            session_token: None,
9701×
        };
9711×
        assert_eq!(Credentials::from_json(&aws.to_json()).unwrap(), aws);
9721×
        assert_eq!(format!("{aws:?}"), "Aws(AKIDEXAMPLE, secret hidden)");
9731×
        let az = Credentials::Azure {
9741×
            tenant_id: "t".into(),
9751×
            client_id: "c".into(),
9761×
            client_secret: "s3cr3t".into(),
9771×
        };
9781×
        assert_eq!(Credentials::from_json(&az.to_json()).unwrap(), az);
9791×
        assert!(!format!("{az:?}").contains("s3cr3t"));
9801×
        let key = r#"{"type":"service_account","client_email":"x@y","private_key":"k"}"#;
9811×
        let gcp = Credentials::Gcp {
9821×
            service_account_key: key.into(),
9831×
        };
9841×
        assert_eq!(Credentials::from_json(&gcp.to_json()).unwrap(), gcp);
9851×
        assert!(!format!("{gcp:?}").contains("private_key"));
9864×
        for (bad, why) in [
9871×
            (r#"{"kind":"aws","access_key_id":"a"}"#, "secret_access_key"),
9881×
            (
9891×
                r#"{"kind":"gcp","service_account_key":"{\"type\":\"authorized_user\"}"}"#,
9901×
                "not a service account key",
9911×
            ),
9921×
            (r#"{"kind":"ftp"}"#, "aws, gcp or azure"),
9931×
            ("nope", "not JSON"),
9941×
        ] {
9954×
            let e = Credentials::from_json(bad).unwrap_err().to_string();
9964×
            assert!(e.contains(why), "{bad}: {e}");
997
        }
9981×
        let e = CloudStore::open_with("gs://bucket/p", Some(&aws))
9991×
            .err()
10001×
            .unwrap()
10011×
            .to_string();
10021×
        assert!(e.contains("are for s3:// stores"), "{e}");
10031×
    }
1004
1005
    use super::*;
1006
1007
    #[test]
10081×
    fn urls_parse_with_their_parameters() {
10091×
        let u =
10101×
            StoreUrl::parse("s3://my-bucket/repos/oxygen?profile=work&region=eu-west-2").unwrap();
10111×
        assert_eq!(u.scheme, "s3");
10121×
        assert_eq!(u.host, "my-bucket");
10131×
        assert_eq!(u.path, "repos/oxygen");
10141×
        assert_eq!(u.param("profile"), Some("work"));
10151×
        assert_eq!(u.param("region"), Some("eu-west-2"));
10161×
        assert_eq!(u.plain(), "s3://my-bucket/repos/oxygen");
10171×
        let u = StoreUrl::parse("gs://bucket").unwrap();
10181×
        assert_eq!((u.host.as_str(), u.path.as_str()), ("bucket", ""));
10191×
        assert_eq!(u.plain(), "gs://bucket");
10201×
        let u = StoreUrl::parse("az://acct/container/a/b/?endpoint=http%3A%2F%2F127.0.0.1%3A10000")
10211×
            .unwrap();
10221×
        assert_eq!(u.path, "container/a/b");
10231×
        assert_eq!(u.param("endpoint"), Some("http://127.0.0.1:10000"));
10241×
        assert!(StoreUrl::parse("s3://").is_err());
10251×
        assert!(StoreUrl::parse("nonsense").is_err());
10261×
    }
1027
1028
    #[test]
10291×
    fn versions_carry_both_an_etag_and_a_generation() {
10301×
        let v = CloudStore::version_of(Some("\"abc\"".into()), Some("17".into()));
10311×
        let u = CloudStore::update_version(&v);
10321×
        assert_eq!(u.e_tag.as_deref(), Some("\"abc\""));
10331×
        assert_eq!(u.version.as_deref(), Some("17"));
10341×
        let u = CloudStore::update_version(&CloudStore::version_of(None, Some("3".into())));
10351×
        assert_eq!((u.e_tag, u.version.as_deref()), (None, Some("3")));
10361×
    }
1037
}