OXYGENHUB
# 1e0fbb47ab90 oxygen / crates / oxy-strata / src / lib.rs
31.3 KiB · Rust · last changed Strata counts its requests by kind 20 days ago source blame history raw
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.
34
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.
37
    let _ = rustls::crypto::ring::default_provider().install_default();
38
    oxy_core::protocol::register_store_opener(open_url);
39
}
40
41
fn open_url(
42
    url: &str,
43
    _options: &oxy_core::protocol::RemoteOptions,
44
) -> Option<Result<Box<dyn Store>>> {
45
    let scheme = url.split_once("://")?.0;
46
    if !matches!(scheme, "s3" | "gs" | "az") {
47
        return None;
48
    }
49
    let lookup = *CREDENTIALS.lock().unwrap_or_else(|p| p.into_inner());
50
    let given = lookup.and_then(|f| f(url));
51
    Some(shared(url, given).map(|s| Box::new(Shared(s)) as Box<dyn Store>))
52
}
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
60
fn shared(url: &str, given: Option<Credentials>) -> Result<Arc<CloudStore>> {
61
    static OPEN: Mutex<Option<OpenStores>> = Mutex::new(None);
62
    let key = (url.to_string(), given);
63
    let mut open = OPEN.lock().unwrap_or_else(|p| p.into_inner());
64
    let map = open.get_or_insert_with(Default::default);
65
    if let Some(s) = map.get(&key) {
66
        return Ok(s.clone());
67
    }
68
    let store = Arc::new(CloudStore::open_with(url, key.1.as_ref())?);
69
    map.insert(key, store.clone());
70
    Ok(store)
71
}
72
73
/// A shared [`CloudStore`] as a [`Store`].
74
struct Shared(Arc<CloudStore>);
75
76
impl Store for Shared {
77
    fn describe(&self) -> String {
78
        self.0.describe()
79
    }
80
    fn has(&self, key: &str) -> Result<bool> {
81
        self.0.has(key)
82
    }
83
    fn get(&self, key: &str) -> Result<Vec<u8>> {
84
        self.0.get(key)
85
    }
86
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
87
        self.0.get_range(key, range)
88
    }
89
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
90
        self.0.put_new(key, bytes)
91
    }
92
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
93
        self.0.list(prefix)
94
    }
95
    fn delete(&self, key: &str) -> Result<()> {
96
        self.0.delete(key)
97
    }
98
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
99
        self.0.read_ref(key)
100
    }
101
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
102
        self.0.write_ref(key, bytes, expected)
103
    }
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
142
    pub fn name(self) -> &'static str {
143
        match self {
144
            Op::Has => "has",
145
            Op::HasMissing => "has_missing",
146
            Op::Get => "get",
147
            Op::Range => "range",
148
            Op::Put => "put",
149
            Op::List => "list",
150
            Op::Delete => "delete",
151
            Op::ReadRef => "read_ref",
152
            Op::WriteRef => "write_ref",
153
        }
154
    }
155
}
156
157
fn counted(op: Op) {
158
    BY_OP[op as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
159
}
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.
175
    pub fn ops(&self) -> impl Iterator<Item = (&'static str, u64)> + '_ {
176
        Op::ALL
177
            .iter()
178
            .map(|op| (op.name(), self.by_op[*op as usize]))
179
    }
180
}
181
182
pub fn stats() -> Stats {
183
    use std::sync::atomic::Ordering::Relaxed;
184
    Stats {
185
        opens: OPENS.load(Relaxed),
186
        calls: CALLS.load(Relaxed),
187
        millis: MICROS.load(Relaxed) / 1000,
188
        by_op: std::array::from_fn(|i| BY_OP[i].load(Relaxed)),
189
    }
190
}
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.
216
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
217
        match self {
218
            Credentials::Aws { access_key_id, .. } => {
219
                write!(f, "Aws({access_key_id}, secret hidden)")
220
            }
221
            Credentials::Gcp { .. } => write!(f, "Gcp(service account key hidden)"),
222
            Credentials::Azure { client_id, .. } => write!(f, "Azure({client_id}, secret hidden)"),
223
        }
224
    }
225
}
226
227
impl Credentials {
228
    /// The scheme of the stores these are for.
229
    pub fn scheme(&self) -> &'static str {
230
        match self {
231
            Credentials::Aws { .. } => "s3",
232
            Credentials::Gcp { .. } => "gs",
233
            Credentials::Azure { .. } => "az",
234
        }
235
    }
236
237
    /// As JSON, for keeping (sealed) and reading back with [`Credentials::from_json`].
238
    pub fn to_json(&self) -> String {
239
        let v = match self {
240
            Credentials::Aws {
241
                access_key_id,
242
                secret_access_key,
243
                session_token,
244
            } => serde_json::json!({
245
                "kind": "aws", "access_key_id": access_key_id, "secret_access_key": secret_access_key,
246
                "session_token": session_token,
247
            }),
248
            Credentials::Gcp {
249
                service_account_key,
250
            } => {
251
                serde_json::json!({ "kind": "gcp", "service_account_key": service_account_key })
252
            }
253
            Credentials::Azure {
254
                tenant_id,
255
                client_id,
256
                client_secret,
257
            } => serde_json::json!({
258
                "kind": "azure", "tenant_id": tenant_id, "client_id": client_id, "client_secret": client_secret,
259
            }),
260
        };
261
        v.to_string()
262
    }
263
264
    pub fn from_json(text: &str) -> Result<Credentials> {
265
        let v: serde_json::Value = serde_json::from_str(text)
266
            .map_err(|e| Error::Backend(format!("credentials are not JSON: {e}")))?;
267
        let field = |k: &str| -> Result<String> {
268
            v.get(k)
269
                .and_then(|x| x.as_str())
270
                .filter(|x| !x.trim().is_empty())
271
                .map(|x| x.trim().to_string())
272
                .ok_or_else(|| Error::Backend(format!("credentials need {k}")))
273
        };
274
        match v.get("kind").and_then(|k| k.as_str()) {
275
            Some("aws") => Ok(Credentials::Aws {
276
                access_key_id: field("access_key_id")?,
277
                secret_access_key: field("secret_access_key")?,
278
                session_token: field("session_token").ok(),
279
            }),
280
            Some("gcp") => {
281
                let key = field("service_account_key")?;
282
                let parsed: serde_json::Value = serde_json::from_str(&key).map_err(|_| {
283
                    Error::Backend("the service account key is not the JSON Google issues".into())
284
                })?;
285
                if parsed.get("type").and_then(|t| t.as_str()) != Some("service_account") {
286
                    return Err(Error::Backend(
287
                        "the key is not a service account key (its type is not service_account)"
288
                            .into(),
289
                    ));
290
                }
291
                Ok(Credentials::Gcp {
292
                    service_account_key: key,
293
                })
294
            }
295
            Some("azure") => Ok(Credentials::Azure {
296
                tenant_id: field("tenant_id")?,
297
                client_id: field("client_id")?,
298
                client_secret: field("client_secret")?,
299
            }),
300
            _ => Err(Error::Backend(
301
                "credentials need a kind: aws, gcp or azure".into(),
302
            )),
303
        }
304
    }
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.
314
pub fn set_credentials_lookup(lookup: CredentialsLookup) {
315
    *CREDENTIALS.lock().unwrap_or_else(|p| p.into_inner()) = Some(lookup);
316
}
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 {
331
    pub fn parse(url: &str) -> Result<StoreUrl> {
332
        let bad = |why: &str| Error::Backend(format!("{url}: {why}"));
333
        let (scheme, rest) = url.split_once("://").ok_or_else(|| bad("not a URL"))?;
334
        let (rest, query) = match rest.split_once('?') {
335
            Some((r, q)) => (r, Some(q)),
336
            None => (rest, None),
337
        };
338
        let (host, path) = match rest.split_once('/') {
339
            Some((h, p)) => (h, p.trim_matches('/')),
340
            None => (rest, ""),
341
        };
342
        if host.is_empty() {
343
            return Err(bad("names no bucket"));
344
        }
345
        let mut params = BTreeMap::new();
346
        for pair in query.unwrap_or("").split('&').filter(|p| !p.is_empty()) {
347
            let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
348
            params.insert(k.to_string(), percent_decode(v));
349
        }
350
        Ok(StoreUrl {
351
            scheme: scheme.to_string(),
352
            host: host.to_string(),
353
            path: path.to_string(),
354
            params,
355
        })
356
    }
357
358
    /// The URL without its parameters, for messages.
359
    pub fn plain(&self) -> String {
360
        if self.path.is_empty() {
361
            format!("{}://{}", self.scheme, self.host)
362
        } else {
363
            format!("{}://{}/{}", self.scheme, self.host, self.path)
364
        }
365
    }
366
367
    pub fn param(&self, name: &str) -> Option<&str> {
368
        self.params.get(name).map(String::as_str)
369
    }
370
}
371
372
fn percent_decode(s: &str) -> String {
373
    let bytes = s.as_bytes();
374
    let mut out = Vec::with_capacity(bytes.len());
375
    let mut i = 0;
376
    while i < bytes.len() {
377
        if bytes[i] == b'%' && i + 2 < bytes.len() {
378
            if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
379
                out.push(v);
380
                i += 3;
381
                continue;
382
            }
383
        }
384
        out.push(bytes[i]);
385
        i += 1;
386
    }
387
    String::from_utf8_lossy(&out).into_owned()
388
}
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.
404
    fn drop(&mut self) {
405
        if let Some(rt) = self.runtime.take() {
406
            rt.shutdown_background();
407
        }
408
    }
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.
414
    pub fn open(url: &str) -> Result<CloudStore> {
415
        Self::open_with(url, None)
416
    }
417
418
    /// [`CloudStore::open`] with credentials given, which must be for
419
    /// the URL's kind of store; then only they are used.
420
    pub fn open_with(url: &str, given: Option<&Credentials>) -> Result<CloudStore> {
421
        let parsed = StoreUrl::parse(url)?;
422
        if let Some(c) = given.filter(|c| c.scheme() != parsed.scheme) {
423
            return Err(Error::Backend(format!(
424
                "{}: the credentials given are for {}:// stores",
425
                parsed.plain(),
426
                c.scheme()
427
            )));
428
        }
429
        let aws_keys = match given {
430
            Some(Credentials::Aws {
431
                access_key_id,
432
                secret_access_key,
433
                session_token,
434
            }) => Some((
435
                access_key_id.as_str(),
436
                secret_access_key.as_str(),
437
                session_token.as_deref(),
438
            )),
439
            _ => None,
440
        };
441
        let gcp_key = match given {
442
            Some(Credentials::Gcp {
443
                service_account_key,
444
            }) => Some(service_account_key.as_str()),
445
            _ => None,
446
        };
447
        let principal = match given {
448
            Some(Credentials::Azure {
449
                tenant_id,
450
                client_id,
451
                client_secret,
452
            }) => Some((
453
                tenant_id.as_str(),
454
                client_id.as_str(),
455
                client_secret.as_str(),
456
            )),
457
            _ => None,
458
        };
459
        OPENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
460
        let runtime = tokio::runtime::Builder::new_multi_thread()
461
            .worker_threads(2)
462
            .thread_name("oxy-strata")
463
            .enable_all()
464
            .build()
465
            .map_err(|e| Error::Backend(format!("starting the HTTP runtime: {e}")))?;
466
        let (inner, prefix, hint): (Arc<dyn ObjectStore>, String, &'static str) =
467
            match parsed.scheme.as_str() {
468
                "s3" => (
469
                    Arc::new(aws::open(&parsed, aws_keys)?),
470
                    parsed.path.clone(),
471
                    aws::HINT,
472
                ),
473
                "gs" => (
474
                    Arc::new(gcp::open(&parsed, gcp_key)?),
475
                    parsed.path.clone(),
476
                    gcp::HINT,
477
                ),
478
                "az" => {
479
                    let (store, prefix) = azure::open(&parsed, principal)?;
480
                    (Arc::new(store), prefix, azure::HINT)
481
                }
482
                other => {
483
                    return Err(Error::Backend(format!(
484
                        "{url}: {other}:// is not a store oxy knows (s3://, gs://, az://, dir://)"
485
                    )))
486
                }
487
            };
488
        Ok(CloudStore {
489
            inner,
490
            prefix,
491
            name: parsed.plain(),
492
            hint,
493
            runtime: Some(runtime),
494
        })
495
    }
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.
500
    fn block<F>(&self, f: F) -> F::Output
501
    where
502
        F: Future + Send,
503
        F::Output: Send,
504
    {
505
        let runtime = self
506
            .runtime
507
            .as_ref()
508
            .expect("the runtime lives as long as the store");
509
        let started = std::time::Instant::now();
510
        let out = if tokio::runtime::Handle::try_current().is_ok() {
511
            std::thread::scope(|s| {
512
                s.spawn(|| runtime.block_on(f))
513
                    .join()
514
                    .unwrap_or_else(|p| std::panic::resume_unwind(p))
515
            })
516
        } else {
517
            runtime.block_on(f)
518
        };
519
        CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
520
        MICROS.fetch_add(
521
            started.elapsed().as_micros() as u64,
522
            std::sync::atomic::Ordering::Relaxed,
523
        );
524
        out
525
    }
526
527
    fn path(&self, key: &str) -> Result<ObjectPath> {
528
        check_key(key)?;
529
        let full = if self.prefix.is_empty() {
530
            key.to_string()
531
        } else {
532
            format!("{}/{key}", self.prefix)
533
        };
534
        ObjectPath::parse(&full).map_err(|e| Error::Backend(format!("{full}: {e}")))
535
    }
536
537
    /// Our error for the provider's, with what to do next where it helps.
538
    fn map(&self, e: object_store::Error, key: &str) -> Error {
539
        use object_store::Error as E;
540
        match e {
541
            E::NotFound { .. } => Error::NotFound(key.to_string()),
542
            E::AlreadyExists { .. } => Error::Exists(key.to_string()),
543
            E::Precondition { .. } | E::NotModified { .. } => Error::Conflict(key.to_string()),
544
            other => {
545
                let text = other.to_string();
546
                let lower = text.to_ascii_lowercase();
547
                let advice = if lower.contains("403")
548
                    || lower.contains("accessdenied")
549
                    || lower.contains("forbidden")
550
                    || lower.contains("authorizationpermissionmismatch")
551
                {
552
                    format!(
553
                        ": access denied; the credentials in use may not do this on {}: {}",
554
                        self.name, self.hint
555
                    )
556
                } else if lower.contains("credential") || lower.contains("no valid credentials") {
557
                    format!(": no usable credentials: {}", self.hint)
558
                } else if lower.contains("nosuchbucket")
559
                    || lower.contains("bucketnotfound")
560
                    || lower.contains("containernotfound")
561
                {
562
                    format!(
563
                        ": {} does not exist, or the credentials cannot see it",
564
                        self.name
565
                    )
566
                } else if lower.contains("dns")
567
                    || lower.contains("connect")
568
                    || lower.contains("timed out")
569
                {
570
                    ": cannot reach the service; check the network, the endpoint and the region"
571
                        .to_string()
572
                } else {
573
                    String::new()
574
                };
575
                Error::Backend(format!("{}: {text}{advice}", self.name))
576
            }
577
        }
578
    }
579
580
    fn version_of(e_tag: Option<String>, version: Option<String>) -> Version {
581
        Version(format!(
582
            "{}\t{}",
583
            e_tag.unwrap_or_default(),
584
            version.unwrap_or_default()
585
        ))
586
    }
587
588
    fn update_version(v: &Version) -> UpdateVersion {
589
        let (e_tag, version) = v.0.split_once('\t').unwrap_or((v.0.as_str(), ""));
590
        UpdateVersion {
591
            e_tag: (!e_tag.is_empty()).then(|| e_tag.to_string()),
592
            version: (!version.is_empty()).then(|| version.to_string()),
593
        }
594
    }
595
}
596
597
impl Store for CloudStore {
598
    fn describe(&self) -> String {
599
        self.name.clone()
600
    }
601
602
    fn has(&self, key: &str) -> Result<bool> {
603
        let path = self.path(key)?;
604
        match self.block(self.inner.head(&path)) {
605
            Ok(_) => {
606
                counted(Op::Has);
607
                Ok(true)
608
            }
609
            Err(object_store::Error::NotFound { .. }) => {
610
                counted(Op::HasMissing);
611
                Ok(false)
612
            }
613
            Err(e) => Err(self.map(e, key)),
614
        }
615
    }
616
617
    fn get(&self, key: &str) -> Result<Vec<u8>> {
618
        let path = self.path(key)?;
619
        counted(Op::Get);
620
        self.block(async {
621
            let r = self.inner.get(&path).await?;
622
            r.bytes().await
623
        })
624
        .map(|b| b.to_vec())
625
        .map_err(|e| self.map(e, key))
626
    }
627
628
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
629
        let path = self.path(key)?;
630
        if range.start > range.end {
631
            return Err(Error::Backend(format!(
632
                "{key}: bytes {}..{} is not a range",
633
                range.start, range.end
634
            )));
635
        }
636
        if range.is_empty() {
637
            return Ok(Vec::new());
638
        }
639
        let want = (range.end - range.start) as usize;
640
        counted(Op::Range);
641
        let bytes = self
642
            .block(self.inner.get_range(&path, range.clone()))
643
            .map_err(|e| self.map(e, key))?;
644
        if bytes.len() != want {
645
            return Err(Error::Backend(format!(
646
                "{key}: bytes {}..{} asked, {} returned: the object is shorter",
647
                range.start,
648
                range.end,
649
                bytes.len()
650
            )));
651
        }
652
        Ok(bytes.to_vec())
653
    }
654
655
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
656
        let path = self.path(key)?;
657
        let opts = PutOptions {
658
            mode: PutMode::Create,
659
            ..Default::default()
660
        };
661
        counted(Op::Put);
662
        self.block(
663
            self.inner
664
                .put_opts(&path, PutPayload::from(bytes.to_vec()), opts),
665
        )
666
        .map(|_| ())
667
        .map_err(|e| self.map(e, key))
668
    }
669
670
    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.
673
        let dir = prefix.rsplit_once('/').map(|(d, _)| d).unwrap_or("");
674
        let full_dir = match (self.prefix.as_str(), dir) {
675
            ("", "") => None,
676
            ("", d) => Some(d.to_string()),
677
            (p, "") => Some(p.to_string()),
678
            (p, d) => Some(format!("{p}/{d}")),
679
        };
680
        let full_dir = full_dir
681
            .map(|d| ObjectPath::parse(&d).map_err(|e| Error::Backend(format!("{d}: {e}"))))
682
            .transpose()?;
683
        counted(Op::List);
684
        let metas: Vec<object_store::ObjectMeta> = self
685
            .block(self.inner.list(full_dir.as_ref()).try_collect())
686
            .map_err(|e| self.map(e, prefix))?;
687
        let strip = if self.prefix.is_empty() {
688
            String::new()
689
        } else {
690
            format!("{}/", self.prefix)
691
        };
692
        let mut out: Vec<Entry> = metas
693
            .into_iter()
694
            .filter_map(|m| {
695
                let loc = m.location.to_string();
696
                let key = loc.strip_prefix(&strip)?;
697
                key.starts_with(prefix).then(|| Entry {
698
                    key: key.to_string(),
699
                    size: m.size,
700
                    modified_ms: u64::try_from(m.last_modified.timestamp_millis()).ok(),
701
                })
702
            })
703
            .collect();
704
        out.sort_by(|a, b| a.key.cmp(&b.key));
705
        Ok(out)
706
    }
707
708
    fn delete(&self, key: &str) -> Result<()> {
709
        let path = self.path(key)?;
710
        counted(Op::Delete);
711
        match self.block(self.inner.delete(&path)) {
712
            Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()),
713
            Err(e) => Err(self.map(e, key)),
714
        }
715
    }
716
717
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
718
        let path = self.path(key)?;
719
        counted(Op::ReadRef);
720
        let got = self.block(async {
721
            let r = self.inner.get_opts(&path, GetOptions::default()).await?;
722
            let meta = r.meta.clone();
723
            let bytes = r.bytes().await?;
724
            Ok::<_, object_store::Error>((bytes, meta))
725
        });
726
        match got {
727
            Ok((bytes, meta)) => Ok(Some((
728
                bytes.to_vec(),
729
                Self::version_of(meta.e_tag, meta.version),
730
            ))),
731
            Err(object_store::Error::NotFound { .. }) => Ok(None),
732
            Err(e) => Err(self.map(e, key)),
733
        }
734
    }
735
736
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
737
        let path = self.path(key)?;
738
        let mode = match expected {
739
            None => PutMode::Create,
740
            Some(v) => PutMode::Update(Self::update_version(v)),
741
        };
742
        let opts = PutOptions {
743
            mode,
744
            ..Default::default()
745
        };
746
        counted(Op::WriteRef);
747
        let put = self
748
            .block(
749
                self.inner
750
                    .put_opts(&path, PutPayload::from(bytes.to_vec()), opts),
751
            )
752
            .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.
755
                Error::Exists(k) => Error::Conflict(k),
756
                other => other,
757
            })?;
758
        Ok(Self::version_of(put.e_tag, put.version))
759
    }
760
}
761
762
#[cfg(test)]
763
mod tests {
764
765
    /// Every kind of request is reported, once and by its own name.
766
    #[test]
767
    fn stats_name_every_kind_of_request() {
768
        let names: Vec<&str> = super::stats().ops().map(|(n, _)| n).collect();
769
        assert_eq!(names.len(), super::Op::ALL.len());
770
        let mut unique = names.clone();
771
        unique.sort();
772
        unique.dedup();
773
        assert_eq!(unique.len(), names.len());
774
        assert!(names.contains(&"has_missing") && names.contains(&"range"));
775
    }
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]
780
    fn a_store_opened_again_shares_its_client() {
781
        let creds = |k: &str| Credentials::Aws {
782
            access_key_id: k.into(),
783
            secret_access_key: "s".into(),
784
            session_token: None,
785
        };
786
        let url = "s3://oxy-shared-test/repos/a?region=eu-west-2";
787
        let before = super::stats().opens;
788
        let a = super::shared(url, Some(creds("one"))).unwrap();
789
        let b = super::shared(url, Some(creds("one"))).unwrap();
790
        assert!(std::sync::Arc::ptr_eq(&a, &b));
791
        let other_keys = super::shared(url, Some(creds("two"))).unwrap();
792
        assert!(
793
            !std::sync::Arc::ptr_eq(&a, &other_keys),
794
            "other credentials, another client"
795
        );
796
        assert!(
797
            super::stats().opens - before >= 2,
798
            "two clients opened (other tests may open more)"
799
        );
800
    }
801
802
    #[tokio::test]
803
    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.
806
        let store = CloudStore::open(
807
            "s3://oxy-no-such-bucket/p?region=eu-west-2&endpoint=http://127.0.0.1:9",
808
        )
809
        .unwrap();
810
        assert_eq!(store.block(async { 7 }), 7);
811
        drop(store);
812
    }
813
814
    #[test]
815
    fn credentials_round_trip_and_never_show_their_secret() {
816
        let aws = Credentials::Aws {
817
            access_key_id: "AKIDEXAMPLE".into(),
818
            secret_access_key: "wJalrXUtnFEMI".into(),
819
            session_token: None,
820
        };
821
        assert_eq!(Credentials::from_json(&aws.to_json()).unwrap(), aws);
822
        assert_eq!(format!("{aws:?}"), "Aws(AKIDEXAMPLE, secret hidden)");
823
        let az = Credentials::Azure {
824
            tenant_id: "t".into(),
825
            client_id: "c".into(),
826
            client_secret: "s3cr3t".into(),
827
        };
828
        assert_eq!(Credentials::from_json(&az.to_json()).unwrap(), az);
829
        assert!(!format!("{az:?}").contains("s3cr3t"));
830
        let key = r#"{"type":"service_account","client_email":"x@y","private_key":"k"}"#;
831
        let gcp = Credentials::Gcp {
832
            service_account_key: key.into(),
833
        };
834
        assert_eq!(Credentials::from_json(&gcp.to_json()).unwrap(), gcp);
835
        assert!(!format!("{gcp:?}").contains("private_key"));
836
        for (bad, why) in [
837
            (r#"{"kind":"aws","access_key_id":"a"}"#, "secret_access_key"),
838
            (
839
                r#"{"kind":"gcp","service_account_key":"{\"type\":\"authorized_user\"}"}"#,
840
                "not a service account key",
841
            ),
842
            (r#"{"kind":"ftp"}"#, "aws, gcp or azure"),
843
            ("nope", "not JSON"),
844
        ] {
845
            let e = Credentials::from_json(bad).unwrap_err().to_string();
846
            assert!(e.contains(why), "{bad}: {e}");
847
        }
848
        let e = CloudStore::open_with("gs://bucket/p", Some(&aws))
849
            .err()
850
            .unwrap()
851
            .to_string();
852
        assert!(e.contains("are for s3:// stores"), "{e}");
853
    }
854
855
    use super::*;
856
857
    #[test]
858
    fn urls_parse_with_their_parameters() {
859
        let u =
860
            StoreUrl::parse("s3://my-bucket/repos/oxygen?profile=work&region=eu-west-2").unwrap();
861
        assert_eq!(u.scheme, "s3");
862
        assert_eq!(u.host, "my-bucket");
863
        assert_eq!(u.path, "repos/oxygen");
864
        assert_eq!(u.param("profile"), Some("work"));
865
        assert_eq!(u.param("region"), Some("eu-west-2"));
866
        assert_eq!(u.plain(), "s3://my-bucket/repos/oxygen");
867
        let u = StoreUrl::parse("gs://bucket").unwrap();
868
        assert_eq!((u.host.as_str(), u.path.as_str()), ("bucket", ""));
869
        assert_eq!(u.plain(), "gs://bucket");
870
        let u = StoreUrl::parse("az://acct/container/a/b/?endpoint=http%3A%2F%2F127.0.0.1%3A10000")
871
            .unwrap();
872
        assert_eq!(u.path, "container/a/b");
873
        assert_eq!(u.param("endpoint"), Some("http://127.0.0.1:10000"));
874
        assert!(StoreUrl::parse("s3://").is_err());
875
        assert!(StoreUrl::parse("nonsense").is_err());
876
    }
877
878
    #[test]
879
    fn versions_carry_both_an_etag_and_a_generation() {
880
        let v = CloudStore::version_of(Some("\"abc\"".into()), Some("17".into()));
881
        let u = CloudStore::update_version(&v);
882
        assert_eq!(u.e_tag.as_deref(), Some("\"abc\""));
883
        assert_eq!(u.version.as_deref(), Some("17"));
884
        let u = CloudStore::update_version(&CloudStore::version_of(None, Some("3".into())));
885
        assert_eq!((u.e_tag, u.version.as_deref()), (None, Some("3")));
886
    }
887
}