OXYGENHUB

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

435 of 736 lines run, 62 of 241 functions · run #328 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 stat(&self, key: &str) -> Result<Option<Entry>> {
960×
        self.0.stat(key)
970×
    }
980×
    fn delete(&self, key: &str) -> Result<()> {
990×
        self.0.delete(key)
1000×
    }
1010×
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
1020×
        self.0.read_ref(key)
1030×
    }
1040×
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
1050×
        self.0.write_ref(key, bytes, expected)
1060×
    }
107
}
108
109
static OPENS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
110
static CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
111
static MICROS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
112
static BY_OP: [std::sync::atomic::AtomicU64; Op::ALL.len()] =
113
    [const { std::sync::atomic::AtomicU64::new(0) }; Op::ALL.len()];
114
115
/// The kinds of request a cloud store makes, counted apart so a server can
116
/// tell which of them its time goes to.
117
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
118
pub enum Op {
119
    /// `has` that found the object.
120
    Has,
121
    /// `has` that did not: an absent object is never cached.
122
    HasMissing,
123
    Get,
124
    Range,
125
    Put,
126
    List,
127
    /// A listing of a repository's packs, sent.
128
    ListPacks,
129
    /// A listing answered from [`Listings`], not sent.
130
    ListKept,
131
    Delete,
132
    ReadRef,
133
    WriteRef,
134
}
135
136
impl Op {
137
    pub const ALL: [Op; 11] = [
138
        Op::Has,
139
        Op::HasMissing,
140
        Op::Get,
141
        Op::Range,
142
        Op::Put,
143
        Op::List,
144
        Op::ListPacks,
145
        Op::ListKept,
146
        Op::Delete,
147
        Op::ReadRef,
148
        Op::WriteRef,
149
    ];
150
15111×
    pub fn name(self) -> &'static str {
15211×
        match self {
1531×
            Op::Has => "has",
1541×
            Op::HasMissing => "has_missing",
1551×
            Op::Get => "get",
1561×
            Op::Range => "range",
1571×
            Op::Put => "put",
1581×
            Op::List => "list",
1591×
            Op::ListPacks => "list_packs",
1601×
            Op::ListKept => "list_kept",
1611×
            Op::Delete => "delete",
1621×
            Op::ReadRef => "read_ref",
1631×
            Op::WriteRef => "write_ref",
164
        }
16511×
    }
166
}
167
1680×
fn counted(op: Op) {
1690×
    BY_OP[op as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1700×
}
171
172
/// What the cloud stores have done since the process started: clients
173
/// opened, requests made and the time spent in them, for a server to show
174
/// (a hub's /health).
175
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
176
pub struct Stats {
177
    pub opens: u64,
178
    pub calls: u64,
179
    pub millis: u64,
180
    /// Requests by kind, in [`Op::ALL`]'s order.
181
    pub by_op: [u64; Op::ALL.len()],
182
}
183
184
impl Stats {
185
    /// Each kind of request with how many were made.
1861×
    pub fn ops(&self) -> impl Iterator<Item = (&'static str, u64)> + '_ {
1871×
        Op::ALL
1881×
            .iter()
18911×
            .map(|op| (op.name(), self.by_op[*op as usize]))
1901×
    }
191
}
192
1933×
pub fn stats() -> Stats {
194
    use std::sync::atomic::Ordering::Relaxed;
195
    Stats {
1963×
        opens: OPENS.load(Relaxed),
1973×
        calls: CALLS.load(Relaxed),
1983×
        millis: MICROS.load(Relaxed) / 1000,
19933×
        by_op: std::array::from_fn(|i| BY_OP[i].load(Relaxed)),
200
    }
2013×
}
202
203
/// Credentials a program keeps itself and hands over, instead of the
204
/// provider's usual places: a hub keeps each repository's sealed. When a
205
/// store is opened with them, nothing from the environment or the
206
/// provider's files is used.
207
#[derive(Clone, PartialEq, Eq, Hash)]
208
pub enum Credentials {
209
    /// An S3 access key.
210
    Aws {
211
        access_key_id: String,
212
        secret_access_key: String,
213
        session_token: Option<String>,
214
    },
215
    /// A Google Cloud service account key, as the JSON Google issues.
216
    Gcp { service_account_key: String },
217
    /// An Azure service principal.
218
    Azure {
219
        tenant_id: String,
220
        client_id: String,
221
        client_secret: String,
222
    },
223
}
224
225
impl std::fmt::Debug for Credentials {
226
    /// Names the kind and the public part only: never the secret.
2273×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2283×
        match self {
2291×
            Credentials::Aws { access_key_id, .. } => {
2301×
                write!(f, "Aws({access_key_id}, secret hidden)")
231
            }
2321×
            Credentials::Gcp { .. } => write!(f, "Gcp(service account key hidden)"),
2331×
            Credentials::Azure { client_id, .. } => write!(f, "Azure({client_id}, secret hidden)"),
234
        }
2353×
    }
236
}
237
238
impl Credentials {
239
    /// The scheme of the stores these are for.
2404×
    pub fn scheme(&self) -> &'static str {
2414×
        match self {
2424×
            Credentials::Aws { .. } => "s3",
2430×
            Credentials::Gcp { .. } => "gs",
2440×
            Credentials::Azure { .. } => "az",
245
        }
2464×
    }
247
248
    /// As JSON, for keeping (sealed) and reading back with [`Credentials::from_json`].
2493×
    pub fn to_json(&self) -> String {
2503×
        let v = match self {
251
            Credentials::Aws {
2521×
                access_key_id,
2531×
                secret_access_key,
2541×
                session_token,
2551×
            } => serde_json::json!({
2561×
                "kind": "aws", "access_key_id": access_key_id, "secret_access_key": secret_access_key,
2571×
                "session_token": session_token,
258
            }),
259
            Credentials::Gcp {
2601×
                service_account_key,
261
            } => {
2621×
                serde_json::json!({ "kind": "gcp", "service_account_key": service_account_key })
263
            }
264
            Credentials::Azure {
2651×
                tenant_id,
2661×
                client_id,
2671×
                client_secret,
2681×
            } => serde_json::json!({
2691×
                "kind": "azure", "tenant_id": tenant_id, "client_id": client_id, "client_secret": client_secret,
270
            }),
271
        };
2723×
        v.to_string()
2733×
    }
274
2757×
    pub fn from_json(text: &str) -> Result<Credentials> {
2767×
        let v: serde_json::Value = serde_json::from_str(text)
2777×
            .map_err(|e| Error::Backend(format!("credentials are not JSON: {e}")))?;
27810×
        let field = |k: &str| -> Result<String> {
27910×
            v.get(k)
28010×
                .and_then(|x| x.as_str())
28110×
                .filter(|x| !x.trim().is_empty())
28210×
                .map(|x| x.trim().to_string())
28310×
                .ok_or_else(|| Error::Backend(format!("credentials need {k}")))
28410×
        };
2856×
        match v.get("kind").and_then(|k| k.as_str()) {
2866×
            Some("aws") => Ok(Credentials::Aws {
2872×
                access_key_id: field("access_key_id")?,
2882×
                secret_access_key: field("secret_access_key")?,
2891×
                session_token: field("session_token").ok(),
290
            }),
2914×
            Some("gcp") => {
2922×
                let key = field("service_account_key")?;
2932×
                let parsed: serde_json::Value = serde_json::from_str(&key).map_err(|_| {
2940×
                    Error::Backend("the service account key is not the JSON Google issues".into())
2950×
                })?;
2962×
                if parsed.get("type").and_then(|t| t.as_str()) != Some("service_account") {
2971×
                    return Err(Error::Backend(
2981×
                        "the key is not a service account key (its type is not service_account)"
2991×
                            .into(),
3001×
                    ));
3011×
                }
3021×
                Ok(Credentials::Gcp {
3031×
                    service_account_key: key,
3041×
                })
305
            }
3062×
            Some("azure") => Ok(Credentials::Azure {
3071×
                tenant_id: field("tenant_id")?,
3081×
                client_id: field("client_id")?,
3091×
                client_secret: field("client_secret")?,
310
            }),
3111×
            _ => Err(Error::Backend(
3121×
                "credentials need a kind: aws, gcp or azure".into(),
3131×
            )),
314
        }
3157×
    }
316
}
317
318
/// Finds the credentials a program keeps for a store URL.
319
pub type CredentialsLookup = fn(&str) -> Option<Credentials>;
320
321
static CREDENTIALS: Mutex<Option<CredentialsLookup>> = Mutex::new(None);
322
323
/// Have stores opened by URL (as a repository's `storage.url` is) use the
324
/// credentials `lookup` finds for it, where it finds any.
3250×
pub fn set_credentials_lookup(lookup: CredentialsLookup) {
3260×
    *CREDENTIALS.lock().unwrap_or_else(|p| p.into_inner()) = Some(lookup);
3270×
}
328
329
/// A parsed store URL: `SCHEME://HOST/PATH?PARAMS`.
330
#[derive(Clone, Debug, PartialEq, Eq)]
331
pub struct StoreUrl {
332
    pub scheme: String,
333
    /// The bucket (S3, GCS) or the storage account (Azure).
334
    pub host: String,
335
    /// The path under the host, without leading or trailing slashes; for
336
    /// Azure the container is its first segment.
337
    pub path: String,
338
    pub params: BTreeMap<String, String>,
339
}
340
341
impl StoreUrl {
3429×
    pub fn parse(url: &str) -> Result<StoreUrl> {
3439×
        let bad = |why: &str| Error::Backend(format!("{url}: {why}"));
3449×
        let (scheme, rest) = url.split_once("://").ok_or_else(|| bad("not a URL"))?;
3458×
        let (rest, query) = match rest.split_once('?') {
3465×
            Some((r, q)) => (r, Some(q)),
3473×
            None => (rest, None),
348
        };
3498×
        let (host, path) = match rest.split_once('/') {
3506×
            Some((h, p)) => (h, p.trim_matches('/')),
3512×
            None => (rest, ""),
352
        };
3538×
        if host.is_empty() {
3541×
            return Err(bad("names no bucket"));
3557×
        }
3567×
        let mut params = BTreeMap::new();
3579×
        for pair in query.unwrap_or("").split('&').filter(|p| !p.is_empty()) {
3587×
            let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
3597×
            params.insert(k.to_string(), percent_decode(v));
3607×
        }
3617×
        Ok(StoreUrl {
3627×
            scheme: scheme.to_string(),
3637×
            host: host.to_string(),
3647×
            path: path.to_string(),
3657×
            params,
3667×
        })
3679×
    }
368
369
    /// The URL without its parameters, for messages.
3706×
    pub fn plain(&self) -> String {
3716×
        if self.path.is_empty() {
3721×
            format!("{}://{}", self.scheme, self.host)
373
        } else {
3745×
            format!("{}://{}/{}", self.scheme, self.host, self.path)
375
        }
3766×
    }
377
37810×
    pub fn param(&self, name: &str) -> Option<&str> {
37910×
        self.params.get(name).map(String::as_str)
38010×
    }
381
}
382
3837×
fn percent_decode(s: &str) -> String {
3847×
    let bytes = s.as_bytes();
3857×
    let mut out = Vec::with_capacity(bytes.len());
3867×
    let mut i = 0;
38787×
    while i < bytes.len() {
38880×
        if bytes[i] == b'%' && i + 2 < bytes.len() {
3894×
            if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
3904×
                out.push(v);
3914×
                i += 3;
3924×
                continue;
3930×
            }
39476×
        }
39576×
        out.push(bytes[i]);
39676×
        i += 1;
397
    }
3987×
    String::from_utf8_lossy(&out).into_owned()
3997×
}
400
401
/// A store on a cloud provider: the provider's client, the prefix every
402
/// key goes under, and a runtime to run the client on.
403
pub struct CloudStore {
404
    inner: Arc<dyn ObjectStore>,
405
    prefix: String,
406
    name: String,
407
    hint: &'static str,
408
    /// Always there until the store is dropped: two workers, so the
409
    /// requests of a shared store run side by side.
410
    runtime: Option<tokio::runtime::Runtime>,
411
    /// Keys `has` found missing lately (see [`Misses`]).
412
    misses: Misses,
413
    /// Pack listings, kept a moment (see [`Listings`]).
414
    listings: Listings,
415
}
416
417
/// How long a key found missing is taken as missing without asking again.
418
const MISS_FOR: std::time::Duration = std::time::Duration::from_secs(30);
419
420
/// Keys found missing in the last [`MISS_FOR`], so a server answering the
421
/// same question again and again does not send a request each time
422
/// (oxygenhub#228: a client's negotiate asked about ~190 objects the hub
423
/// lacked every 8 s, 45 ms a request). This process forgets a key the
424
/// moment it writes it, so its own writes are never hidden; another writer
425
/// to the same keys is seen within `MISS_FOR`.
426
#[derive(Default)]
427
struct Misses(Mutex<std::collections::HashMap<String, std::time::Instant>>);
428
429
impl Misses {
430
    /// At most this many kept; past it the oldest half is let go.
431
    const MAX: usize = 100_000;
432
4335×
    fn known(&self, key: &str) -> bool {
4345×
        let map = self.0.lock().unwrap_or_else(|p| p.into_inner());
4355×
        map.get(key).is_some_and(|t| t.elapsed() < MISS_FOR)
4365×
    }
437
4382×
    fn missed(&self, key: &str) {
4392×
        let mut map = self.0.lock().unwrap_or_else(|p| p.into_inner());
4402×
        if map.len() >= Self::MAX {
4410×
            map.retain(|_, t| t.elapsed() < MISS_FOR / 2);
4420×
            if map.len() >= Self::MAX {
4430×
                map.clear();
4440×
            }
4452×
        }
4462×
        map.insert(key.to_string(), std::time::Instant::now());
4472×
    }
448
4491×
    fn written(&self, key: &str) {
4501×
        self.0.lock().unwrap_or_else(|p| p.into_inner()).remove(key);
4511×
    }
452
}
453
454
/// Listings kept for [`MISS_FOR`] (oxygen#116): the `pack-` keys, which
455
/// every open of a repository's store lists, so a forge serving a
456
/// repository from a bucket lists them once a while rather than once a
457
/// request. Like [`Misses`], this process forgets a listing the moment it
458
/// writes or deletes a key under it; another writer's pack is seen within
459
/// `MISS_FOR`, as a missing key is.
460
#[derive(Default)]
461
struct Listings(Mutex<std::collections::HashMap<String, (std::time::Instant, Vec<Entry>)>>);
462
463
impl Listings {
464
    /// The prefixes kept: those every open lists.
4658×
    fn kept(prefix: &str) -> bool {
4668×
        prefix == "pack-"
4678×
    }
468
4695×
    fn get(&self, prefix: &str) -> Option<Vec<Entry>> {
4705×
        if !Self::kept(prefix) {
4711×
            return None;
4724×
        }
4734×
        let map = self.0.lock().unwrap_or_else(|p| p.into_inner());
4744×
        map.get(prefix)
4754×
            .filter(|(t, _)| t.elapsed() < MISS_FOR)
4764×
            .map(|(_, e)| e.clone())
4775×
    }
478
4793×
    fn put(&self, prefix: &str, entries: &[Entry]) {
4803×
        if Self::kept(prefix) {
4812×
            self.0.lock().unwrap_or_else(|p| p.into_inner()).insert(
4822×
                prefix.to_string(),
4832×
                (std::time::Instant::now(), entries.to_vec()),
484
            );
4851×
        }
4863×
    }
487
4882×
    fn written(&self, key: &str) {
4892×
        self.0
4902×
            .lock()
4912×
            .unwrap_or_else(|p| p.into_inner())
4922×
            .retain(|prefix, _| !key.starts_with(prefix.as_str()));
4932×
    }
494
}
495
496
impl Drop for CloudStore {
497
    /// Without waiting, so a store can be dropped inside a runtime too.
4981×
    fn drop(&mut self) {
4991×
        if let Some(rt) = self.runtime.take() {
5001×
            rt.shutdown_background();
5011×
        }
5021×
    }
503
}
504
505
impl CloudStore {
506
    /// Open the store a URL names. Nothing is sent yet: credentials are
507
    /// resolved here, but the bucket is first spoken to on the first call.
5081×
    pub fn open(url: &str) -> Result<CloudStore> {
5091×
        Self::open_with(url, None)
5101×
    }
511
512
    /// [`CloudStore::open`] with credentials given, which must be for
513
    /// the URL's kind of store; then only they are used.
5144×
    pub fn open_with(url: &str, given: Option<&Credentials>) -> Result<CloudStore> {
5154×
        let parsed = StoreUrl::parse(url)?;
5164×
        if let Some(c) = given.filter(|c| c.scheme() != parsed.scheme) {
5171×
            return Err(Error::Backend(format!(
5181×
                "{}: the credentials given are for {}:// stores",
5191×
                parsed.plain(),
5201×
                c.scheme()
5211×
            )));
5223×
        }
5233×
        let aws_keys = match given {
524
            Some(Credentials::Aws {
5252×
                access_key_id,
5262×
                secret_access_key,
5272×
                session_token,
5282×
            }) => Some((
5292×
                access_key_id.as_str(),
5302×
                secret_access_key.as_str(),
5312×
                session_token.as_deref(),
5322×
            )),
5331×
            _ => None,
534
        };
5353×
        let gcp_key = match given {
536
            Some(Credentials::Gcp {
5370×
                service_account_key,
5380×
            }) => Some(service_account_key.as_str()),
5393×
            _ => None,
540
        };
5413×
        let principal = match given {
542
            Some(Credentials::Azure {
5430×
                tenant_id,
5440×
                client_id,
5450×
                client_secret,
5460×
            }) => Some((
5470×
                tenant_id.as_str(),
5480×
                client_id.as_str(),
5490×
                client_secret.as_str(),
5500×
            )),
5513×
            _ => None,
552
        };
5533×
        OPENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5543×
        let runtime = tokio::runtime::Builder::new_multi_thread()
5553×
            .worker_threads(2)
5563×
            .thread_name("oxy-strata")
5573×
            .enable_all()
5583×
            .build()
5593×
            .map_err(|e| Error::Backend(format!("starting the HTTP runtime: {e}")))?;
5603×
        let (inner, prefix, hint): (Arc<dyn ObjectStore>, String, &'static str) =
5613×
            match parsed.scheme.as_str() {
5623×
                "s3" => (
5633×
                    Arc::new(aws::open(&parsed, aws_keys)?),
5643×
                    parsed.path.clone(),
565
                    aws::HINT,
566
                ),
5670×
                "gs" => (
5680×
                    Arc::new(gcp::open(&parsed, gcp_key)?),
5690×
                    parsed.path.clone(),
570
                    gcp::HINT,
571
                ),
5720×
                "az" => {
5730×
                    let (store, prefix) = azure::open(&parsed, principal)?;
5740×
                    (Arc::new(store), prefix, azure::HINT)
575
                }
5760×
                other => {
5770×
                    return Err(Error::Backend(format!(
5780×
                        "{url}: {other}:// is not a store oxy knows (s3://, gs://, az://, dir://)"
5790×
                    )))
580
                }
581
            };
5823×
        Ok(CloudStore {
5833×
            inner,
5843×
            prefix,
5853×
            name: parsed.plain(),
5863×
            hint,
5873×
            runtime: Some(runtime),
5883×
            misses: Misses::default(),
5893×
            listings: Listings::default(),
5903×
        })
5914×
    }
592
593
    /// Run a request to completion. Called from a thread that is itself
594
    /// driving async tasks (a server's handler), where blocking on another
595
    /// runtime is not allowed, the request runs on a thread of its own.
5961×
    fn block<F>(&self, f: F) -> F::Output
5971×
    where
5981×
        F: Future + Send,
5991×
        F::Output: Send,
600
    {
6011×
        let runtime = self
6021×
            .runtime
6031×
            .as_ref()
6041×
            .expect("the runtime lives as long as the store");
6051×
        let started = std::time::Instant::now();
6061×
        let out = if tokio::runtime::Handle::try_current().is_ok() {
6071×
            std::thread::scope(|s| {
6081×
                s.spawn(|| runtime.block_on(f))
6091×
                    .join()
6101×
                    .unwrap_or_else(|p| std::panic::resume_unwind(p))
6111×
            })
612
        } else {
6130×
            runtime.block_on(f)
614
        };
6151×
        CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6161×
        MICROS.fetch_add(
6171×
            started.elapsed().as_micros() as u64,
6181×
            std::sync::atomic::Ordering::Relaxed,
619
        );
6201×
        out
6211×
    }
622
6230×
    fn path(&self, key: &str) -> Result<ObjectPath> {
6240×
        check_key(key)?;
6250×
        let full = if self.prefix.is_empty() {
6260×
            key.to_string()
627
        } else {
6280×
            format!("{}/{key}", self.prefix)
629
        };
6300×
        ObjectPath::parse(&full).map_err(|e| Error::Backend(format!("{full}: {e}")))
6310×
    }
632
633
    /// Our error for the provider's, with what to do next where it helps.
6340×
    fn map(&self, e: object_store::Error, key: &str) -> Error {
635
        use object_store::Error as E;
6360×
        match e {
6370×
            E::NotFound { .. } => Error::NotFound(key.to_string()),
6380×
            E::AlreadyExists { .. } => Error::Exists(key.to_string()),
6390×
            E::Precondition { .. } | E::NotModified { .. } => Error::Conflict(key.to_string()),
6400×
            other => {
6410×
                let text = other.to_string();
6420×
                let lower = text.to_ascii_lowercase();
6430×
                let advice = if lower.contains("403")
6440×
                    || lower.contains("accessdenied")
6450×
                    || lower.contains("forbidden")
6460×
                    || lower.contains("authorizationpermissionmismatch")
647
                {
6480×
                    format!(
649
                        ": access denied; the credentials in use may not do this on {}: {}",
650
                        self.name, self.hint
651
                    )
6520×
                } else if lower.contains("credential") || lower.contains("no valid credentials") {
6530×
                    format!(": no usable credentials: {}", self.hint)
6540×
                } else if lower.contains("nosuchbucket")
6550×
                    || lower.contains("bucketnotfound")
6560×
                    || lower.contains("containernotfound")
657
                {
6580×
                    format!(
659
                        ": {} does not exist, or the credentials cannot see it",
660
                        self.name
661
                    )
6620×
                } else if lower.contains("dns")
6630×
                    || lower.contains("connect")
6640×
                    || lower.contains("timed out")
665
                {
6660×
                    ": cannot reach the service; check the network, the endpoint and the region"
6670×
                        .to_string()
668
                } else {
6690×
                    String::new()
670
                };
6710×
                Error::Backend(format!("{}: {text}{advice}", self.name))
672
            }
673
        }
6740×
    }
675
6762×
    fn version_of(e_tag: Option<String>, version: Option<String>) -> Version {
6772×
        Version(format!(
6782×
            "{}\t{}",
6792×
            e_tag.unwrap_or_default(),
6802×
            version.unwrap_or_default()
6812×
        ))
6822×
    }
683
6842×
    fn update_version(v: &Version) -> UpdateVersion {
6852×
        let (e_tag, version) = v.0.split_once('\t').unwrap_or((v.0.as_str(), ""));
686
        UpdateVersion {
6872×
            e_tag: (!e_tag.is_empty()).then(|| e_tag.to_string()),
6882×
            version: (!version.is_empty()).then(|| version.to_string()),
689
        }
6902×
    }
691
}
692
693
impl Store for CloudStore {
6940×
    fn describe(&self) -> String {
6950×
        self.name.clone()
6960×
    }
697
6980×
    fn has(&self, key: &str) -> Result<bool> {
6990×
        let path = self.path(key)?;
7000×
        if self.misses.known(key) {
7010×
            return Ok(false);
7020×
        }
7030×
        match self.block(self.inner.head(&path)) {
704
            Ok(_) => {
7050×
                counted(Op::Has);
7060×
                Ok(true)
707
            }
708
            Err(object_store::Error::NotFound { .. }) => {
7090×
                counted(Op::HasMissing);
7100×
                self.misses.missed(key);
7110×
                Ok(false)
712
            }
7130×
            Err(e) => Err(self.map(e, key)),
714
        }
7150×
    }
716
7170×
    fn get(&self, key: &str) -> Result<Vec<u8>> {
7180×
        let path = self.path(key)?;
7190×
        counted(Op::Get);
7200×
        self.block(async {
7210×
            let r = self.inner.get(&path).await?;
7220×
            r.bytes().await
7230×
        })
7240×
        .map(|b| b.to_vec())
7250×
        .map_err(|e| self.map(e, key))
7260×
    }
727
7280×
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
7290×
        let path = self.path(key)?;
7300×
        if range.start > range.end {
7310×
            return Err(Error::Backend(format!(
7320×
                "{key}: bytes {}..{} is not a range",
7330×
                range.start, range.end
7340×
            )));
7350×
        }
7360×
        if range.is_empty() {
7370×
            return Ok(Vec::new());
7380×
        }
7390×
        let want = (range.end - range.start) as usize;
7400×
        counted(Op::Range);
7410×
        let bytes = self
7420×
            .block(self.inner.get_range(&path, range.clone()))
7430×
            .map_err(|e| self.map(e, key))?;
7440×
        if bytes.len() != want {
7450×
            return Err(Error::Backend(format!(
7460×
                "{key}: bytes {}..{} asked, {} returned: the object is shorter",
7470×
                range.start,
7480×
                range.end,
7490×
                bytes.len()
7500×
            )));
7510×
        }
7520×
        Ok(bytes.to_vec())
7530×
    }
754
7550×
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
7560×
        let path = self.path(key)?;
7570×
        self.misses.written(key);
7580×
        self.listings.written(key);
7590×
        let opts = PutOptions {
7600×
            mode: PutMode::Create,
7610×
            ..Default::default()
7620×
        };
7630×
        counted(Op::Put);
7640×
        self.block(
7650×
            self.inner
7660×
                .put_opts(&path, PutPayload::from(bytes.to_vec()), opts),
767
        )
7680×
        .map(|_| ())
7690×
        .map_err(|e| self.map(e, key))
7700×
    }
771
7720×
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
7730×
        if let Some(kept) = self.listings.get(prefix) {
7740×
            counted(Op::ListKept);
7750×
            return Ok(kept);
7760×
        }
777
        // Providers list by whole path segments; the asked prefix may end
778
        // mid-segment, so list its directory and filter here.
7790×
        let dir = prefix.rsplit_once('/').map(|(d, _)| d).unwrap_or("");
7800×
        let full_dir = match (self.prefix.as_str(), dir) {
7810×
            ("", "") => None,
7820×
            ("", d) => Some(d.to_string()),
7830×
            (p, "") => Some(p.to_string()),
7840×
            (p, d) => Some(format!("{p}/{d}")),
785
        };
7860×
        let full_dir = full_dir
7870×
            .map(|d| ObjectPath::parse(&d).map_err(|e| Error::Backend(format!("{d}: {e}"))))
7880×
            .transpose()?;
7890×
        counted(if Listings::kept(prefix) {
7900×
            Op::ListPacks
791
        } else {
7920×
            Op::List
793
        });
7940×
        let metas: Vec<object_store::ObjectMeta> = self
7950×
            .block(self.inner.list(full_dir.as_ref()).try_collect())
7960×
            .map_err(|e| self.map(e, prefix))?;
7970×
        let strip = if self.prefix.is_empty() {
7980×
            String::new()
799
        } else {
8000×
            format!("{}/", self.prefix)
801
        };
8020×
        let mut out: Vec<Entry> = metas
8030×
            .into_iter()
8040×
            .filter_map(|m| {
8050×
                let loc = m.location.to_string();
8060×
                let key = loc.strip_prefix(&strip)?;
8070×
                key.starts_with(prefix).then(|| Entry {
8080×
                    key: key.to_string(),
8090×
                    size: m.size,
8100×
                    modified_ms: u64::try_from(m.last_modified.timestamp_millis()).ok(),
8110×
                })
8120×
            })
8130×
            .collect();
8140×
        out.sort_by(|a, b| a.key.cmp(&b.key));
8150×
        self.listings.put(prefix, &out);
8160×
        Ok(out)
8170×
    }
818
819
    /// A HEAD of the key, not a listing of its directory (oxygen#116).
8200×
    fn stat(&self, key: &str) -> Result<Option<Entry>> {
8210×
        let path = self.path(key)?;
8220×
        counted(Op::Has);
8230×
        match self.block(self.inner.head(&path)) {
8240×
            Ok(m) => Ok(Some(Entry {
8250×
                key: key.to_string(),
8260×
                size: m.size,
8270×
                modified_ms: u64::try_from(m.last_modified.timestamp_millis()).ok(),
8280×
            })),
8290×
            Err(object_store::Error::NotFound { .. }) => Ok(None),
8300×
            Err(e) => Err(self.map(e, key)),
831
        }
8320×
    }
833
8340×
    fn delete(&self, key: &str) -> Result<()> {
8350×
        let path = self.path(key)?;
8360×
        self.listings.written(key);
8370×
        counted(Op::Delete);
8380×
        match self.block(self.inner.delete(&path)) {
8390×
            Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()),
8400×
            Err(e) => Err(self.map(e, key)),
841
        }
8420×
    }
843
8440×
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
8450×
        let path = self.path(key)?;
8460×
        counted(Op::ReadRef);
8470×
        let got = self.block(async {
8480×
            let r = self.inner.get_opts(&path, GetOptions::default()).await?;
8490×
            let meta = r.meta.clone();
8500×
            let bytes = r.bytes().await?;
8510×
            Ok::<_, object_store::Error>((bytes, meta))
8520×
        });
8530×
        match got {
8540×
            Ok((bytes, meta)) => Ok(Some((
8550×
                bytes.to_vec(),
8560×
                Self::version_of(meta.e_tag, meta.version),
8570×
            ))),
8580×
            Err(object_store::Error::NotFound { .. }) => Ok(None),
8590×
            Err(e) => Err(self.map(e, key)),
860
        }
8610×
    }
862
8630×
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
8640×
        let path = self.path(key)?;
8650×
        self.misses.written(key);
8660×
        self.listings.written(key);
8670×
        let mode = match expected {
8680×
            None => PutMode::Create,
8690×
            Some(v) => PutMode::Update(Self::update_version(v)),
870
        };
8710×
        let opts = PutOptions {
8720×
            mode,
8730×
            ..Default::default()
8740×
        };
8750×
        counted(Op::WriteRef);
8760×
        let put = self
8770×
            .block(
8780×
                self.inner
8790×
                    .put_opts(&path, PutPayload::from(bytes.to_vec()), opts),
880
            )
8810×
            .map_err(|e| match self.map(e, key) {
882
                // A record that exists when none was expected is a lost
883
                // race too, not a misuse of put_new.
8840×
                Error::Exists(k) => Error::Conflict(k),
8850×
                other => other,
8860×
            })?;
8870×
        Ok(Self::version_of(put.e_tag, put.version))
8880×
    }
889
}
890
891
#[cfg(test)]
892
mod tests {
893
894
    /// A miss is remembered until the key is written, or for MISS_FOR.
895
    #[test]
8961×
    fn a_miss_is_remembered_until_written() {
8971×
        let m = super::Misses::default();
8981×
        assert!(!m.known("loose/ab/cd"));
8991×
        m.missed("loose/ab/cd");
9001×
        assert!(m.known("loose/ab/cd") && !m.known("loose/ab/ce"));
9011×
        m.written("loose/ab/cd");
9021×
        assert!(!m.known("loose/ab/cd"), "a write forgets the miss");
9031×
        m.missed("old");
9041×
        m.0.lock()
9051×
            .unwrap()
9061×
            .insert("old".into(), std::time::Instant::now() - super::MISS_FOR);
9071×
        assert!(!m.known("old"), "a miss expires");
9081×
    }
909
910
    /// Every kind of request is reported, once and by its own name.
911
    /// The pack listing is kept until a pack key is written or deleted
912
    /// here, or for MISS_FOR; other prefixes are never kept (oxygen#116).
913
    #[test]
9141×
    fn the_pack_listing_is_kept_until_a_pack_is_written() {
9151×
        let l = super::Listings::default();
9161×
        let e = |k: &str| oxy_core::strata::Entry {
9173×
            key: k.into(),
918
            size: 1,
9193×
            modified_ms: None,
9203×
        };
9211×
        l.put("pack-", &[e("pack-1.idx")]);
9221×
        assert_eq!(l.get("pack-").map(|v| v.len()), Some(1));
9231×
        l.put("loose/", &[e("loose/ab")]);
9241×
        assert!(l.get("loose/").is_none(), "only the pack listing is kept");
9251×
        l.written("loose/cd");
9261×
        assert!(l.get("pack-").is_some(), "a loose object leaves it");
9271×
        l.written("pack-2.pack");
9281×
        assert!(l.get("pack-").is_none(), "a new pack forgets it");
9291×
        l.put("pack-", &[e("pack-1.idx")]);
9301×
        l.0.lock().unwrap().get_mut("pack-").unwrap().0 -= super::MISS_FOR;
9311×
        assert!(l.get("pack-").is_none(), "and it ages out");
9321×
    }
933
934
    #[test]
9351×
    fn stats_name_every_kind_of_request() {
9361×
        let names: Vec<&str> = super::stats().ops().map(|(n, _)| n).collect();
9371×
        assert_eq!(names.len(), super::Op::ALL.len());
9381×
        let mut unique = names.clone();
9391×
        unique.sort();
9401×
        unique.dedup();
9411×
        assert_eq!(unique.len(), names.len());
9421×
        assert!(names.contains(&"has_missing") && names.contains(&"range"));
9431×
    }
944
945
    /// One client per store and credentials (oxygenhub#234): opening the
946
    /// same again shares it, and only a new one counts as opened.
947
    #[test]
9481×
    fn a_store_opened_again_shares_its_client() {
9491×
        let creds = |k: &str| Credentials::Aws {
9503×
            access_key_id: k.into(),
9513×
            secret_access_key: "s".into(),
9523×
            session_token: None,
9533×
        };
9541×
        let url = "s3://oxy-shared-test/repos/a?region=eu-west-2";
9551×
        let before = super::stats().opens;
9561×
        let a = super::shared(url, Some(creds("one"))).unwrap();
9571×
        let b = super::shared(url, Some(creds("one"))).unwrap();
9581×
        assert!(std::sync::Arc::ptr_eq(&a, &b));
9591×
        let other_keys = super::shared(url, Some(creds("two"))).unwrap();
9601×
        assert!(
9611×
            !std::sync::Arc::ptr_eq(&a, &other_keys),
962
            "other credentials, another client"
963
        );
9641×
        assert!(
9651×
            super::stats().opens - before >= 2,
966
            "two clients opened (other tests may open more)"
967
        );
9681×
    }
969
970
    #[tokio::test]
9711×
    async fn a_store_can_be_used_from_inside_a_runtime() {
972
        // As a server's handler would: blocking on the store's own runtime
973
        // from here must neither panic nor deadlock, and nor must dropping it.
9741×
        let store = CloudStore::open(
9751×
            "s3://oxy-no-such-bucket/p?region=eu-west-2&endpoint=http://127.0.0.1:9",
976
        )
9771×
        .unwrap();
9781×
        assert_eq!(store.block(async { 7 }), 7);
9791×
        drop(store);
9801×
    }
981
982
    #[test]
9831×
    fn credentials_round_trip_and_never_show_their_secret() {
9841×
        let aws = Credentials::Aws {
9851×
            access_key_id: "AKIDEXAMPLE".into(),
9861×
            secret_access_key: "wJalrXUtnFEMI".into(),
9871×
            session_token: None,
9881×
        };
9891×
        assert_eq!(Credentials::from_json(&aws.to_json()).unwrap(), aws);
9901×
        assert_eq!(format!("{aws:?}"), "Aws(AKIDEXAMPLE, secret hidden)");
9911×
        let az = Credentials::Azure {
9921×
            tenant_id: "t".into(),
9931×
            client_id: "c".into(),
9941×
            client_secret: "s3cr3t".into(),
9951×
        };
9961×
        assert_eq!(Credentials::from_json(&az.to_json()).unwrap(), az);
9971×
        assert!(!format!("{az:?}").contains("s3cr3t"));
9981×
        let key = r#"{"type":"service_account","client_email":"x@y","private_key":"k"}"#;
9991×
        let gcp = Credentials::Gcp {
10001×
            service_account_key: key.into(),
10011×
        };
10021×
        assert_eq!(Credentials::from_json(&gcp.to_json()).unwrap(), gcp);
10031×
        assert!(!format!("{gcp:?}").contains("private_key"));
10044×
        for (bad, why) in [
10051×
            (r#"{"kind":"aws","access_key_id":"a"}"#, "secret_access_key"),
10061×
            (
10071×
                r#"{"kind":"gcp","service_account_key":"{\"type\":\"authorized_user\"}"}"#,
10081×
                "not a service account key",
10091×
            ),
10101×
            (r#"{"kind":"ftp"}"#, "aws, gcp or azure"),
10111×
            ("nope", "not JSON"),
10121×
        ] {
10134×
            let e = Credentials::from_json(bad).unwrap_err().to_string();
10144×
            assert!(e.contains(why), "{bad}: {e}");
1015
        }
10161×
        let e = CloudStore::open_with("gs://bucket/p", Some(&aws))
10171×
            .err()
10181×
            .unwrap()
10191×
            .to_string();
10201×
        assert!(e.contains("are for s3:// stores"), "{e}");
10211×
    }
1022
1023
    use super::*;
1024
1025
    #[test]
10261×
    fn urls_parse_with_their_parameters() {
10271×
        let u =
10281×
            StoreUrl::parse("s3://my-bucket/repos/oxygen?profile=work&region=eu-west-2").unwrap();
10291×
        assert_eq!(u.scheme, "s3");
10301×
        assert_eq!(u.host, "my-bucket");
10311×
        assert_eq!(u.path, "repos/oxygen");
10321×
        assert_eq!(u.param("profile"), Some("work"));
10331×
        assert_eq!(u.param("region"), Some("eu-west-2"));
10341×
        assert_eq!(u.plain(), "s3://my-bucket/repos/oxygen");
10351×
        let u = StoreUrl::parse("gs://bucket").unwrap();
10361×
        assert_eq!((u.host.as_str(), u.path.as_str()), ("bucket", ""));
10371×
        assert_eq!(u.plain(), "gs://bucket");
10381×
        let u = StoreUrl::parse("az://acct/container/a/b/?endpoint=http%3A%2F%2F127.0.0.1%3A10000")
10391×
            .unwrap();
10401×
        assert_eq!(u.path, "container/a/b");
10411×
        assert_eq!(u.param("endpoint"), Some("http://127.0.0.1:10000"));
10421×
        assert!(StoreUrl::parse("s3://").is_err());
10431×
        assert!(StoreUrl::parse("nonsense").is_err());
10441×
    }
1045
1046
    #[test]
10471×
    fn versions_carry_both_an_etag_and_a_generation() {
10481×
        let v = CloudStore::version_of(Some("\"abc\"".into()), Some("17".into()));
10491×
        let u = CloudStore::update_version(&v);
10501×
        assert_eq!(u.e_tag.as_deref(), Some("\"abc\""));
10511×
        assert_eq!(u.version.as_deref(), Some("17"));
10521×
        let u = CloudStore::update_version(&CloudStore::version_of(None, Some("3".into())));
10531×
        assert_eq!((u.e_tag, u.version.as_deref()), (None, Some("3")));
10541×
    }
1055
}