OXYGENHUB
◆ merge-remote-bookmark oxygen / crates / oxy-strata / src / lib.rs
39.4 KiB · Rust · last changed Readers never wait: one head per handle, retry on a miss, retire before deleting 17 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 stat(&self, key: &str) -> Result<Option<Entry>> {
96
        self.0.stat(key)
97
    }
98
    fn delete(&self, key: &str) -> Result<()> {
99
        self.0.delete(key)
100
    }
101
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
102
        self.0.read_ref(key)
103
    }
104
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
105
        self.0.write_ref(key, bytes, expected)
106
    }
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
151
    pub fn name(self) -> &'static str {
152
        match self {
153
            Op::Has => "has",
154
            Op::HasMissing => "has_missing",
155
            Op::Get => "get",
156
            Op::Range => "range",
157
            Op::Put => "put",
158
            Op::List => "list",
159
            Op::ListPacks => "list_packs",
160
            Op::ListKept => "list_kept",
161
            Op::Delete => "delete",
162
            Op::ReadRef => "read_ref",
163
            Op::WriteRef => "write_ref",
164
        }
165
    }
166
}
167
168
fn counted(op: Op) {
169
    BY_OP[op as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
170
}
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.
186
    pub fn ops(&self) -> impl Iterator<Item = (&'static str, u64)> + '_ {
187
        Op::ALL
188
            .iter()
189
            .map(|op| (op.name(), self.by_op[*op as usize]))
190
    }
191
}
192
193
pub fn stats() -> Stats {
194
    use std::sync::atomic::Ordering::Relaxed;
195
    Stats {
196
        opens: OPENS.load(Relaxed),
197
        calls: CALLS.load(Relaxed),
198
        millis: MICROS.load(Relaxed) / 1000,
199
        by_op: std::array::from_fn(|i| BY_OP[i].load(Relaxed)),
200
    }
201
}
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.
227
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228
        match self {
229
            Credentials::Aws { access_key_id, .. } => {
230
                write!(f, "Aws({access_key_id}, secret hidden)")
231
            }
232
            Credentials::Gcp { .. } => write!(f, "Gcp(service account key hidden)"),
233
            Credentials::Azure { client_id, .. } => write!(f, "Azure({client_id}, secret hidden)"),
234
        }
235
    }
236
}
237
238
impl Credentials {
239
    /// The scheme of the stores these are for.
240
    pub fn scheme(&self) -> &'static str {
241
        match self {
242
            Credentials::Aws { .. } => "s3",
243
            Credentials::Gcp { .. } => "gs",
244
            Credentials::Azure { .. } => "az",
245
        }
246
    }
247
248
    /// As JSON, for keeping (sealed) and reading back with [`Credentials::from_json`].
249
    pub fn to_json(&self) -> String {
250
        let v = match self {
251
            Credentials::Aws {
252
                access_key_id,
253
                secret_access_key,
254
                session_token,
255
            } => serde_json::json!({
256
                "kind": "aws", "access_key_id": access_key_id, "secret_access_key": secret_access_key,
257
                "session_token": session_token,
258
            }),
259
            Credentials::Gcp {
260
                service_account_key,
261
            } => {
262
                serde_json::json!({ "kind": "gcp", "service_account_key": service_account_key })
263
            }
264
            Credentials::Azure {
265
                tenant_id,
266
                client_id,
267
                client_secret,
268
            } => serde_json::json!({
269
                "kind": "azure", "tenant_id": tenant_id, "client_id": client_id, "client_secret": client_secret,
270
            }),
271
        };
272
        v.to_string()
273
    }
274
275
    pub fn from_json(text: &str) -> Result<Credentials> {
276
        let v: serde_json::Value = serde_json::from_str(text)
277
            .map_err(|e| Error::Backend(format!("credentials are not JSON: {e}")))?;
278
        let field = |k: &str| -> Result<String> {
279
            v.get(k)
280
                .and_then(|x| x.as_str())
281
                .filter(|x| !x.trim().is_empty())
282
                .map(|x| x.trim().to_string())
283
                .ok_or_else(|| Error::Backend(format!("credentials need {k}")))
284
        };
285
        match v.get("kind").and_then(|k| k.as_str()) {
286
            Some("aws") => Ok(Credentials::Aws {
287
                access_key_id: field("access_key_id")?,
288
                secret_access_key: field("secret_access_key")?,
289
                session_token: field("session_token").ok(),
290
            }),
291
            Some("gcp") => {
292
                let key = field("service_account_key")?;
293
                let parsed: serde_json::Value = serde_json::from_str(&key).map_err(|_| {
294
                    Error::Backend("the service account key is not the JSON Google issues".into())
295
                })?;
296
                if parsed.get("type").and_then(|t| t.as_str()) != Some("service_account") {
297
                    return Err(Error::Backend(
298
                        "the key is not a service account key (its type is not service_account)"
299
                            .into(),
300
                    ));
301
                }
302
                Ok(Credentials::Gcp {
303
                    service_account_key: key,
304
                })
305
            }
306
            Some("azure") => Ok(Credentials::Azure {
307
                tenant_id: field("tenant_id")?,
308
                client_id: field("client_id")?,
309
                client_secret: field("client_secret")?,
310
            }),
311
            _ => Err(Error::Backend(
312
                "credentials need a kind: aws, gcp or azure".into(),
313
            )),
314
        }
315
    }
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.
325
pub fn set_credentials_lookup(lookup: CredentialsLookup) {
326
    *CREDENTIALS.lock().unwrap_or_else(|p| p.into_inner()) = Some(lookup);
327
}
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 {
342
    pub fn parse(url: &str) -> Result<StoreUrl> {
343
        let bad = |why: &str| Error::Backend(format!("{url}: {why}"));
344
        let (scheme, rest) = url.split_once("://").ok_or_else(|| bad("not a URL"))?;
345
        let (rest, query) = match rest.split_once('?') {
346
            Some((r, q)) => (r, Some(q)),
347
            None => (rest, None),
348
        };
349
        let (host, path) = match rest.split_once('/') {
350
            Some((h, p)) => (h, p.trim_matches('/')),
351
            None => (rest, ""),
352
        };
353
        if host.is_empty() {
354
            return Err(bad("names no bucket"));
355
        }
356
        let mut params = BTreeMap::new();
357
        for pair in query.unwrap_or("").split('&').filter(|p| !p.is_empty()) {
358
            let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
359
            params.insert(k.to_string(), percent_decode(v));
360
        }
361
        Ok(StoreUrl {
362
            scheme: scheme.to_string(),
363
            host: host.to_string(),
364
            path: path.to_string(),
365
            params,
366
        })
367
    }
368
369
    /// The URL without its parameters, for messages.
370
    pub fn plain(&self) -> String {
371
        if self.path.is_empty() {
372
            format!("{}://{}", self.scheme, self.host)
373
        } else {
374
            format!("{}://{}/{}", self.scheme, self.host, self.path)
375
        }
376
    }
377
378
    pub fn param(&self, name: &str) -> Option<&str> {
379
        self.params.get(name).map(String::as_str)
380
    }
381
}
382
383
fn percent_decode(s: &str) -> String {
384
    let bytes = s.as_bytes();
385
    let mut out = Vec::with_capacity(bytes.len());
386
    let mut i = 0;
387
    while i < bytes.len() {
388
        if bytes[i] == b'%' && i + 2 < bytes.len() {
389
            if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
390
                out.push(v);
391
                i += 3;
392
                continue;
393
            }
394
        }
395
        out.push(bytes[i]);
396
        i += 1;
397
    }
398
    String::from_utf8_lossy(&out).into_owned()
399
}
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
433
    fn known(&self, key: &str) -> bool {
434
        let map = self.0.lock().unwrap_or_else(|p| p.into_inner());
435
        map.get(key).is_some_and(|t| t.elapsed() < MISS_FOR)
436
    }
437
438
    fn missed(&self, key: &str) {
439
        let mut map = self.0.lock().unwrap_or_else(|p| p.into_inner());
440
        if map.len() >= Self::MAX {
441
            map.retain(|_, t| t.elapsed() < MISS_FOR / 2);
442
            if map.len() >= Self::MAX {
443
                map.clear();
444
            }
445
        }
446
        map.insert(key.to_string(), std::time::Instant::now());
447
    }
448
449
    fn written(&self, key: &str) {
450
        self.0.lock().unwrap_or_else(|p| p.into_inner()).remove(key);
451
    }
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.
465
    fn kept(prefix: &str) -> bool {
466
        prefix == "pack-"
467
    }
468
469
    fn get(&self, prefix: &str) -> Option<Vec<Entry>> {
470
        if !Self::kept(prefix) {
471
            return None;
472
        }
473
        let map = self.0.lock().unwrap_or_else(|p| p.into_inner());
474
        map.get(prefix)
475
            .filter(|(t, _)| t.elapsed() < MISS_FOR)
476
            .map(|(_, e)| e.clone())
477
    }
478
479
    fn put(&self, prefix: &str, entries: &[Entry]) {
480
        if Self::kept(prefix) {
481
            self.0.lock().unwrap_or_else(|p| p.into_inner()).insert(
482
                prefix.to_string(),
483
                (std::time::Instant::now(), entries.to_vec()),
484
            );
485
        }
486
    }
487
488
    fn written(&self, key: &str) {
489
        self.0
490
            .lock()
491
            .unwrap_or_else(|p| p.into_inner())
492
            .retain(|prefix, _| !key.starts_with(prefix.as_str()));
493
    }
494
}
495
496
/// Run a request that writes or deletes `key`, forgetting what the caches
497
/// hold for it both before it is sent and after it completes, whatever it
498
/// returns: a listing or a miss taken by another thread while the request
499
/// was in flight may predate it, and would otherwise be kept for
500
/// `MISS_FOR` (oxygenhub#249).
501
fn writing<T>(misses: &Misses, listings: &Listings, key: &str, request: impl FnOnce() -> T) -> T {
502
    misses.written(key);
503
    listings.written(key);
504
    let out = request();
505
    misses.written(key);
506
    listings.written(key);
507
    out
508
}
509
510
impl Drop for CloudStore {
511
    /// Without waiting, so a store can be dropped inside a runtime too.
512
    fn drop(&mut self) {
513
        if let Some(rt) = self.runtime.take() {
514
            rt.shutdown_background();
515
        }
516
    }
517
}
518
519
impl CloudStore {
520
    /// Open the store a URL names. Nothing is sent yet: credentials are
521
    /// resolved here, but the bucket is first spoken to on the first call.
522
    pub fn open(url: &str) -> Result<CloudStore> {
523
        Self::open_with(url, None)
524
    }
525
526
    /// [`CloudStore::open`] with credentials given, which must be for
527
    /// the URL's kind of store; then only they are used.
528
    pub fn open_with(url: &str, given: Option<&Credentials>) -> Result<CloudStore> {
529
        let parsed = StoreUrl::parse(url)?;
530
        if let Some(c) = given.filter(|c| c.scheme() != parsed.scheme) {
531
            return Err(Error::Backend(format!(
532
                "{}: the credentials given are for {}:// stores",
533
                parsed.plain(),
534
                c.scheme()
535
            )));
536
        }
537
        let aws_keys = match given {
538
            Some(Credentials::Aws {
539
                access_key_id,
540
                secret_access_key,
541
                session_token,
542
            }) => Some((
543
                access_key_id.as_str(),
544
                secret_access_key.as_str(),
545
                session_token.as_deref(),
546
            )),
547
            _ => None,
548
        };
549
        let gcp_key = match given {
550
            Some(Credentials::Gcp {
551
                service_account_key,
552
            }) => Some(service_account_key.as_str()),
553
            _ => None,
554
        };
555
        let principal = match given {
556
            Some(Credentials::Azure {
557
                tenant_id,
558
                client_id,
559
                client_secret,
560
            }) => Some((
561
                tenant_id.as_str(),
562
                client_id.as_str(),
563
                client_secret.as_str(),
564
            )),
565
            _ => None,
566
        };
567
        OPENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
568
        let runtime = tokio::runtime::Builder::new_multi_thread()
569
            .worker_threads(2)
570
            .thread_name("oxy-strata")
571
            .enable_all()
572
            .build()
573
            .map_err(|e| Error::Backend(format!("starting the HTTP runtime: {e}")))?;
574
        let (inner, prefix, hint): (Arc<dyn ObjectStore>, String, &'static str) =
575
            match parsed.scheme.as_str() {
576
                "s3" => (
577
                    Arc::new(aws::open(&parsed, aws_keys)?),
578
                    parsed.path.clone(),
579
                    aws::HINT,
580
                ),
581
                "gs" => (
582
                    Arc::new(gcp::open(&parsed, gcp_key)?),
583
                    parsed.path.clone(),
584
                    gcp::HINT,
585
                ),
586
                "az" => {
587
                    let (store, prefix) = azure::open(&parsed, principal)?;
588
                    (Arc::new(store), prefix, azure::HINT)
589
                }
590
                other => {
591
                    return Err(Error::Backend(format!(
592
                        "{url}: {other}:// is not a store oxy knows (s3://, gs://, az://, dir://)"
593
                    )))
594
                }
595
            };
596
        Ok(CloudStore {
597
            inner,
598
            prefix,
599
            name: parsed.plain(),
600
            hint,
601
            runtime: Some(runtime),
602
            misses: Misses::default(),
603
            listings: Listings::default(),
604
        })
605
    }
606
607
    /// Run a request to completion. Called from a thread that is itself
608
    /// driving async tasks (a server's handler), where blocking on another
609
    /// runtime is not allowed, the request runs on a thread of its own.
610
    fn block<F>(&self, f: F) -> F::Output
611
    where
612
        F: Future + Send,
613
        F::Output: Send,
614
    {
615
        let runtime = self
616
            .runtime
617
            .as_ref()
618
            .expect("the runtime lives as long as the store");
619
        let started = std::time::Instant::now();
620
        let out = if tokio::runtime::Handle::try_current().is_ok() {
621
            std::thread::scope(|s| {
622
                s.spawn(|| runtime.block_on(f))
623
                    .join()
624
                    .unwrap_or_else(|p| std::panic::resume_unwind(p))
625
            })
626
        } else {
627
            runtime.block_on(f)
628
        };
629
        CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
630
        MICROS.fetch_add(
631
            started.elapsed().as_micros() as u64,
632
            std::sync::atomic::Ordering::Relaxed,
633
        );
634
        out
635
    }
636
637
    fn path(&self, key: &str) -> Result<ObjectPath> {
638
        check_key(key)?;
639
        let full = if self.prefix.is_empty() {
640
            key.to_string()
641
        } else {
642
            format!("{}/{key}", self.prefix)
643
        };
644
        ObjectPath::parse(&full).map_err(|e| Error::Backend(format!("{full}: {e}")))
645
    }
646
647
    /// Our error for the provider's, with what to do next where it helps.
648
    fn map(&self, e: object_store::Error, key: &str) -> Error {
649
        use object_store::Error as E;
650
        match e {
651
            E::NotFound { .. } => Error::NotFound(key.to_string()),
652
            E::AlreadyExists { .. } => Error::Exists(key.to_string()),
653
            E::Precondition { .. } | E::NotModified { .. } => Error::Conflict(key.to_string()),
654
            other => {
655
                let text = other.to_string();
656
                let lower = text.to_ascii_lowercase();
657
                let advice = if lower.contains("403")
658
                    || lower.contains("accessdenied")
659
                    || lower.contains("forbidden")
660
                    || lower.contains("authorizationpermissionmismatch")
661
                {
662
                    format!(
663
                        ": access denied; the credentials in use may not do this on {}: {}",
664
                        self.name, self.hint
665
                    )
666
                } else if lower.contains("credential") || lower.contains("no valid credentials") {
667
                    format!(": no usable credentials: {}", self.hint)
668
                } else if lower.contains("nosuchbucket")
669
                    || lower.contains("bucketnotfound")
670
                    || lower.contains("containernotfound")
671
                {
672
                    format!(
673
                        ": {} does not exist, or the credentials cannot see it",
674
                        self.name
675
                    )
676
                } else if lower.contains("dns")
677
                    || lower.contains("connect")
678
                    || lower.contains("timed out")
679
                {
680
                    ": cannot reach the service; check the network, the endpoint and the region"
681
                        .to_string()
682
                } else {
683
                    String::new()
684
                };
685
                Error::Backend(format!("{}: {text}{advice}", self.name))
686
            }
687
        }
688
    }
689
690
    fn version_of(e_tag: Option<String>, version: Option<String>) -> Version {
691
        Version(format!(
692
            "{}\t{}",
693
            e_tag.unwrap_or_default(),
694
            version.unwrap_or_default()
695
        ))
696
    }
697
698
    fn update_version(v: &Version) -> UpdateVersion {
699
        let (e_tag, version) = v.0.split_once('\t').unwrap_or((v.0.as_str(), ""));
700
        UpdateVersion {
701
            e_tag: (!e_tag.is_empty()).then(|| e_tag.to_string()),
702
            version: (!version.is_empty()).then(|| version.to_string()),
703
        }
704
    }
705
}
706
707
impl Store for CloudStore {
708
    fn describe(&self) -> String {
709
        self.name.clone()
710
    }
711
712
    fn has(&self, key: &str) -> Result<bool> {
713
        let path = self.path(key)?;
714
        if self.misses.known(key) {
715
            return Ok(false);
716
        }
717
        match self.block(self.inner.head(&path)) {
718
            Ok(_) => {
719
                counted(Op::Has);
720
                Ok(true)
721
            }
722
            Err(object_store::Error::NotFound { .. }) => {
723
                counted(Op::HasMissing);
724
                self.misses.missed(key);
725
                Ok(false)
726
            }
727
            Err(e) => Err(self.map(e, key)),
728
        }
729
    }
730
731
    fn get(&self, key: &str) -> Result<Vec<u8>> {
732
        let path = self.path(key)?;
733
        counted(Op::Get);
734
        self.block(async {
735
            let r = self.inner.get(&path).await?;
736
            r.bytes().await
737
        })
738
        .map(|b| b.to_vec())
739
        .map_err(|e| self.map(e, key))
740
    }
741
742
    fn get_range(&self, key: &str, range: Range<u64>) -> Result<Vec<u8>> {
743
        let path = self.path(key)?;
744
        if range.start > range.end {
745
            return Err(Error::Backend(format!(
746
                "{key}: bytes {}..{} is not a range",
747
                range.start, range.end
748
            )));
749
        }
750
        if range.is_empty() {
751
            return Ok(Vec::new());
752
        }
753
        let want = (range.end - range.start) as usize;
754
        counted(Op::Range);
755
        let bytes = self
756
            .block(self.inner.get_range(&path, range.clone()))
757
            .map_err(|e| self.map(e, key))?;
758
        if bytes.len() != want {
759
            return Err(Error::Backend(format!(
760
                "{key}: bytes {}..{} asked, {} returned: the object is shorter",
761
                range.start,
762
                range.end,
763
                bytes.len()
764
            )));
765
        }
766
        Ok(bytes.to_vec())
767
    }
768
769
    fn put_new(&self, key: &str, bytes: &[u8]) -> Result<()> {
770
        let path = self.path(key)?;
771
        let opts = PutOptions {
772
            mode: PutMode::Create,
773
            ..Default::default()
774
        };
775
        counted(Op::Put);
776
        writing(&self.misses, &self.listings, key, || {
777
            self.block(
778
                self.inner
779
                    .put_opts(&path, PutPayload::from(bytes.to_vec()), opts),
780
            )
781
        })
782
        .map(|_| ())
783
        .map_err(|e| self.map(e, key))
784
    }
785
786
    fn list(&self, prefix: &str) -> Result<Vec<Entry>> {
787
        if let Some(kept) = self.listings.get(prefix) {
788
            counted(Op::ListKept);
789
            return Ok(kept);
790
        }
791
        // Providers list by whole path segments; the asked prefix may end
792
        // mid-segment, so list its directory and filter here.
793
        let dir = prefix.rsplit_once('/').map(|(d, _)| d).unwrap_or("");
794
        let full_dir = match (self.prefix.as_str(), dir) {
795
            ("", "") => None,
796
            ("", d) => Some(d.to_string()),
797
            (p, "") => Some(p.to_string()),
798
            (p, d) => Some(format!("{p}/{d}")),
799
        };
800
        let full_dir = full_dir
801
            .map(|d| ObjectPath::parse(&d).map_err(|e| Error::Backend(format!("{d}: {e}"))))
802
            .transpose()?;
803
        counted(if Listings::kept(prefix) {
804
            Op::ListPacks
805
        } else {
806
            Op::List
807
        });
808
        let metas: Vec<object_store::ObjectMeta> = self
809
            .block(self.inner.list(full_dir.as_ref()).try_collect())
810
            .map_err(|e| self.map(e, prefix))?;
811
        let strip = if self.prefix.is_empty() {
812
            String::new()
813
        } else {
814
            format!("{}/", self.prefix)
815
        };
816
        let mut out: Vec<Entry> = metas
817
            .into_iter()
818
            .filter_map(|m| {
819
                let loc = m.location.to_string();
820
                let key = loc.strip_prefix(&strip)?;
821
                key.starts_with(prefix).then(|| Entry {
822
                    key: key.to_string(),
823
                    size: m.size,
824
                    modified_ms: u64::try_from(m.last_modified.timestamp_millis()).ok(),
825
                })
826
            })
827
            .collect();
828
        out.sort_by(|a, b| a.key.cmp(&b.key));
829
        self.listings.put(prefix, &out);
830
        Ok(out)
831
    }
832
833
    /// A HEAD of the key, not a listing of its directory (oxygen#116).
834
    fn stat(&self, key: &str) -> Result<Option<Entry>> {
835
        let path = self.path(key)?;
836
        counted(Op::Has);
837
        match self.block(self.inner.head(&path)) {
838
            Ok(m) => Ok(Some(Entry {
839
                key: key.to_string(),
840
                size: m.size,
841
                modified_ms: u64::try_from(m.last_modified.timestamp_millis()).ok(),
842
            })),
843
            Err(object_store::Error::NotFound { .. }) => Ok(None),
844
            Err(e) => Err(self.map(e, key)),
845
        }
846
    }
847
848
    fn delete(&self, key: &str) -> Result<()> {
849
        let path = self.path(key)?;
850
        counted(Op::Delete);
851
        match writing(&self.misses, &self.listings, key, || {
852
            self.block(self.inner.delete(&path))
853
        }) {
854
            Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()),
855
            Err(e) => Err(self.map(e, key)),
856
        }
857
    }
858
859
    fn read_ref(&self, key: &str) -> Result<Option<(Vec<u8>, Version)>> {
860
        let path = self.path(key)?;
861
        counted(Op::ReadRef);
862
        let got = self.block(async {
863
            let r = self.inner.get_opts(&path, GetOptions::default()).await?;
864
            let meta = r.meta.clone();
865
            let bytes = r.bytes().await?;
866
            Ok::<_, object_store::Error>((bytes, meta))
867
        });
868
        match got {
869
            Ok((bytes, meta)) => Ok(Some((
870
                bytes.to_vec(),
871
                Self::version_of(meta.e_tag, meta.version),
872
            ))),
873
            Err(object_store::Error::NotFound { .. }) => Ok(None),
874
            Err(e) => Err(self.map(e, key)),
875
        }
876
    }
877
878
    fn write_ref(&self, key: &str, bytes: &[u8], expected: Option<&Version>) -> Result<Version> {
879
        let path = self.path(key)?;
880
        let mode = match expected {
881
            None => PutMode::Create,
882
            Some(v) => PutMode::Update(Self::update_version(v)),
883
        };
884
        let opts = PutOptions {
885
            mode,
886
            ..Default::default()
887
        };
888
        counted(Op::WriteRef);
889
        let put = writing(&self.misses, &self.listings, key, || {
890
            self.block(
891
                self.inner
892
                    .put_opts(&path, PutPayload::from(bytes.to_vec()), opts),
893
            )
894
        })
895
        .map_err(|e| match self.map(e, key) {
896
            // A record that exists when none was expected is a lost
897
            // race too, not a misuse of put_new.
898
            Error::Exists(k) => Error::Conflict(k),
899
            other => other,
900
        })?;
901
        Ok(Self::version_of(put.e_tag, put.version))
902
    }
903
}
904
905
#[cfg(test)]
906
mod tests {
907
908
    /// A miss is remembered until the key is written, or for MISS_FOR.
909
    #[test]
910
    fn a_miss_is_remembered_until_written() {
911
        let m = super::Misses::default();
912
        assert!(!m.known("loose/ab/cd"));
913
        m.missed("loose/ab/cd");
914
        assert!(m.known("loose/ab/cd") && !m.known("loose/ab/ce"));
915
        m.written("loose/ab/cd");
916
        assert!(!m.known("loose/ab/cd"), "a write forgets the miss");
917
        m.missed("old");
918
        m.0.lock()
919
            .unwrap()
920
            .insert("old".into(), std::time::Instant::now() - super::MISS_FOR);
921
        assert!(!m.known("old"), "a miss expires");
922
    }
923
924
    /// Every kind of request is reported, once and by its own name.
925
    /// The pack listing is kept until a pack key is written or deleted
926
    /// here, or for MISS_FOR; other prefixes are never kept (oxygen#116).
927
    #[test]
928
    fn the_pack_listing_is_kept_until_a_pack_is_written() {
929
        let l = super::Listings::default();
930
        let e = |k: &str| oxy_core::strata::Entry {
931
            key: k.into(),
932
            size: 1,
933
            modified_ms: None,
934
        };
935
        l.put("pack-", &[e("pack-1.idx")]);
936
        assert_eq!(l.get("pack-").map(|v| v.len()), Some(1));
937
        l.put("loose/", &[e("loose/ab")]);
938
        assert!(l.get("loose/").is_none(), "only the pack listing is kept");
939
        l.written("loose/cd");
940
        assert!(l.get("pack-").is_some(), "a loose object leaves it");
941
        l.written("pack-2.pack");
942
        assert!(l.get("pack-").is_none(), "a new pack forgets it");
943
        l.put("pack-", &[e("pack-1.idx")]);
944
        l.0.lock().unwrap().get_mut("pack-").unwrap().0 -= super::MISS_FOR;
945
        assert!(l.get("pack-").is_none(), "and it ages out");
946
    }
947
948
    /// A listing or miss taken by another thread while a write is in
949
    /// flight is forgotten when the write completes, not kept stale for
950
    /// MISS_FOR (oxygenhub#249), whether the write succeeded or not.
951
    #[test]
952
    fn a_listing_taken_during_a_write_is_forgotten_after_it() {
953
        let (m, l) = (super::Misses::default(), super::Listings::default());
954
        let e = |k: &str| oxy_core::strata::Entry {
955
            key: k.into(),
956
            size: 1,
957
            modified_ms: None,
958
        };
959
        l.put("pack-", &[e("pack-1.idx")]);
960
        let got = super::writing(&m, &l, "pack-2.idx", || {
961
            assert!(l.get("pack-").is_none(), "forgotten before it is sent");
962
            // Another thread lists, and misses, mid-request.
963
            l.put("pack-", &[e("pack-1.idx")]);
964
            m.missed("pack-2.idx");
965
            7
966
        });
967
        assert_eq!(got, 7);
968
        assert!(l.get("pack-").is_none(), "the mid-request listing is gone");
969
        assert!(!m.known("pack-2.idx"), "and the miss");
970
        // A delete that fails is treated the same.
971
        l.put("pack-", &[e("pack-1.idx")]);
972
        let r: std::result::Result<(), &str> = super::writing(&m, &l, "pack-1.idx", || {
973
            l.put("pack-", &[e("pack-1.idx")]);
974
            Err("network")
975
        });
976
        assert!(r.is_err() && l.get("pack-").is_none());
977
        // Other prefixes' writes leave the pack listing.
978
        l.put("pack-", &[e("pack-1.idx")]);
979
        super::writing(&m, &l, "loose/ab/cd", || ());
980
        assert!(l.get("pack-").is_some());
981
    }
982
983
    #[test]
984
    fn stats_name_every_kind_of_request() {
985
        let names: Vec<&str> = super::stats().ops().map(|(n, _)| n).collect();
986
        assert_eq!(names.len(), super::Op::ALL.len());
987
        let mut unique = names.clone();
988
        unique.sort();
989
        unique.dedup();
990
        assert_eq!(unique.len(), names.len());
991
        assert!(names.contains(&"has_missing") && names.contains(&"range"));
992
    }
993
994
    /// One client per store and credentials (oxygenhub#234): opening the
995
    /// same again shares it, and only a new one counts as opened.
996
    #[test]
997
    fn a_store_opened_again_shares_its_client() {
998
        let creds = |k: &str| Credentials::Aws {
999
            access_key_id: k.into(),
1000
            secret_access_key: "s".into(),
1001
            session_token: None,
1002
        };
1003
        let url = "s3://oxy-shared-test/repos/a?region=eu-west-2";
1004
        let before = super::stats().opens;
1005
        let a = super::shared(url, Some(creds("one"))).unwrap();
1006
        let b = super::shared(url, Some(creds("one"))).unwrap();
1007
        assert!(std::sync::Arc::ptr_eq(&a, &b));
1008
        let other_keys = super::shared(url, Some(creds("two"))).unwrap();
1009
        assert!(
1010
            !std::sync::Arc::ptr_eq(&a, &other_keys),
1011
            "other credentials, another client"
1012
        );
1013
        assert!(
1014
            super::stats().opens - before >= 2,
1015
            "two clients opened (other tests may open more)"
1016
        );
1017
    }
1018
1019
    #[tokio::test]
1020
    async fn a_store_can_be_used_from_inside_a_runtime() {
1021
        // As a server's handler would: blocking on the store's own runtime
1022
        // from here must neither panic nor deadlock, and nor must dropping it.
1023
        let store = CloudStore::open(
1024
            "s3://oxy-no-such-bucket/p?region=eu-west-2&endpoint=http://127.0.0.1:9",
1025
        )
1026
        .unwrap();
1027
        assert_eq!(store.block(async { 7 }), 7);
1028
        drop(store);
1029
    }
1030
1031
    #[test]
1032
    fn credentials_round_trip_and_never_show_their_secret() {
1033
        let aws = Credentials::Aws {
1034
            access_key_id: "AKIDEXAMPLE".into(),
1035
            secret_access_key: "wJalrXUtnFEMI".into(),
1036
            session_token: None,
1037
        };
1038
        assert_eq!(Credentials::from_json(&aws.to_json()).unwrap(), aws);
1039
        assert_eq!(format!("{aws:?}"), "Aws(AKIDEXAMPLE, secret hidden)");
1040
        let az = Credentials::Azure {
1041
            tenant_id: "t".into(),
1042
            client_id: "c".into(),
1043
            client_secret: "s3cr3t".into(),
1044
        };
1045
        assert_eq!(Credentials::from_json(&az.to_json()).unwrap(), az);
1046
        assert!(!format!("{az:?}").contains("s3cr3t"));
1047
        let key = r#"{"type":"service_account","client_email":"x@y","private_key":"k"}"#;
1048
        let gcp = Credentials::Gcp {
1049
            service_account_key: key.into(),
1050
        };
1051
        assert_eq!(Credentials::from_json(&gcp.to_json()).unwrap(), gcp);
1052
        assert!(!format!("{gcp:?}").contains("private_key"));
1053
        for (bad, why) in [
1054
            (r#"{"kind":"aws","access_key_id":"a"}"#, "secret_access_key"),
1055
            (
1056
                r#"{"kind":"gcp","service_account_key":"{\"type\":\"authorized_user\"}"}"#,
1057
                "not a service account key",
1058
            ),
1059
            (r#"{"kind":"ftp"}"#, "aws, gcp or azure"),
1060
            ("nope", "not JSON"),
1061
        ] {
1062
            let e = Credentials::from_json(bad).unwrap_err().to_string();
1063
            assert!(e.contains(why), "{bad}: {e}");
1064
        }
1065
        let e = CloudStore::open_with("gs://bucket/p", Some(&aws))
1066
            .err()
1067
            .unwrap()
1068
            .to_string();
1069
        assert!(e.contains("are for s3:// stores"), "{e}");
1070
    }
1071
1072
    use super::*;
1073
1074
    #[test]
1075
    fn urls_parse_with_their_parameters() {
1076
        let u =
1077
            StoreUrl::parse("s3://my-bucket/repos/oxygen?profile=work&region=eu-west-2").unwrap();
1078
        assert_eq!(u.scheme, "s3");
1079
        assert_eq!(u.host, "my-bucket");
1080
        assert_eq!(u.path, "repos/oxygen");
1081
        assert_eq!(u.param("profile"), Some("work"));
1082
        assert_eq!(u.param("region"), Some("eu-west-2"));
1083
        assert_eq!(u.plain(), "s3://my-bucket/repos/oxygen");
1084
        let u = StoreUrl::parse("gs://bucket").unwrap();
1085
        assert_eq!((u.host.as_str(), u.path.as_str()), ("bucket", ""));
1086
        assert_eq!(u.plain(), "gs://bucket");
1087
        let u = StoreUrl::parse("az://acct/container/a/b/?endpoint=http%3A%2F%2F127.0.0.1%3A10000")
1088
            .unwrap();
1089
        assert_eq!(u.path, "container/a/b");
1090
        assert_eq!(u.param("endpoint"), Some("http://127.0.0.1:10000"));
1091
        assert!(StoreUrl::parse("s3://").is_err());
1092
        assert!(StoreUrl::parse("nonsense").is_err());
1093
    }
1094
1095
    #[test]
1096
    fn versions_carry_both_an_etag_and_a_generation() {
1097
        let v = CloudStore::version_of(Some("\"abc\"".into()), Some("17".into()));
1098
        let u = CloudStore::update_version(&v);
1099
        assert_eq!(u.e_tag.as_deref(), Some("\"abc\""));
1100
        assert_eq!(u.version.as_deref(), Some("17"));
1101
        let u = CloudStore::update_version(&CloudStore::version_of(None, Some("3".into())));
1102
        assert_eq!((u.e_tag, u.version.as_deref()), (None, Some("3")));
1103
    }
1104
}