objectstore-client 0.2.1

Client SDK for Objectstore, the Sentry object storage platform
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
use std::io;
use std::sync::Arc;
use std::time::Duration;

use bytes::Bytes;
use futures_util::stream::BoxStream;
use objectstore_types::metadata::{Compression, ExpirationPolicy};
use objectstore_types::scope;
use reqwest::RequestBuilder;
use url::Url;

use crate::IntoTokenProvider;
use crate::auth::TokenProvider;

const USER_AGENT: &str = concat!("objectstore-client/", env!("CARGO_PKG_VERSION"));

#[derive(Debug)]
struct ClientBuilderInner {
    service_url: Url,
    propagate_traces: bool,
    reqwest_builder: reqwest::ClientBuilder,
    token: Option<TokenProvider>,
}

impl ClientBuilderInner {
    /// Applies defaults that cannot be overridden by the caller.
    fn apply_defaults(mut self) -> Self {
        self.reqwest_builder = self
            .reqwest_builder
            // hickory-dns: Controlled by the `reqwest/hickory-dns` feature flag
            // we are dealing with de/compression ourselves:
            .no_brotli()
            .no_deflate()
            .no_gzip()
            .no_zstd();
        self
    }
}

/// Builder to create a [`Client`].
#[must_use = "call .build() on this ClientBuilder to create a Client"]
#[derive(Debug)]
pub struct ClientBuilder(crate::Result<ClientBuilderInner>);

impl ClientBuilder {
    /// Creates a new [`ClientBuilder`], configured with the given `service_url`.
    ///
    /// To perform CRUD operations, one has to create a [`Client`], and then scope it to a [`Usecase`]
    /// and Scope in order to create a [`Session`].
    pub fn new(service_url: impl reqwest::IntoUrl) -> Self {
        let service_url = match service_url.into_url() {
            Ok(url) => url,
            Err(err) => return Self(Err(err.into())),
        };
        if service_url.cannot_be_a_base() {
            return ClientBuilder(Err(crate::Error::InvalidUrl {
                message: "service_url cannot be a base".to_owned(),
            }));
        }

        let reqwest_builder = reqwest::Client::builder()
            // We define just a connection timeout by default but do not limit reads. A connect
            // timeout of 100ms is still very conservative, but should provide a sensible upper
            // bound to expected request latencies.
            .connect_timeout(Duration::from_millis(100))
            .user_agent(USER_AGENT);

        Self(Ok(ClientBuilderInner {
            service_url,
            propagate_traces: false,
            reqwest_builder,
            token: None,
        }))
    }

    /// Changes whether the `sentry-trace` header will be sent to Objectstore
    /// to take advantage of Sentry's distributed tracing.
    ///
    /// By default, tracing headers will not be propagated.
    pub fn propagate_traces(mut self, propagate_traces: bool) -> Self {
        if let Ok(ref mut inner) = self.0 {
            inner.propagate_traces = propagate_traces;
        }
        self
    }

    /// Defines a read timeout for the [`reqwest::Client`].
    ///
    /// The read timeout is defined to be "between consecutive read operations", for example between
    /// chunks of a streaming response. For more fine-grained configuration of this and other
    /// timeouts, use [`Self::configure_reqwest`].
    ///
    /// By default, no read timeout and a connect timeout of 100ms is set.
    pub fn timeout(self, timeout: Duration) -> Self {
        let Ok(mut inner) = self.0 else { return self };
        inner.reqwest_builder = inner.reqwest_builder.read_timeout(timeout);
        Self(Ok(inner))
    }

    /// Calls the closure with the underlying [`reqwest::ClientBuilder`].
    ///
    /// By default, the ClientBuilder is configured to create a reqwest Client with a connect and read timeout of 500ms and a user agent identifying this library.
    pub fn configure_reqwest<F>(self, closure: F) -> Self
    where
        F: FnOnce(reqwest::ClientBuilder) -> reqwest::ClientBuilder,
    {
        let Ok(mut inner) = self.0 else { return self };
        inner.reqwest_builder = closure(inner.reqwest_builder);
        Self(Ok(inner))
    }

    /// Sets the authentication token to use for requests to Objectstore.
    ///
    /// Accepts anything that implements [`IntoTokenProvider`]:
    /// - A [`TokenGenerator`](crate::TokenGenerator) — for internal services that have access to
    ///   an EdDSA keypair. The generator signs a fresh JWT for each request.
    /// - A `String` or `&str` — a pre-signed JWT, used as-is for every request.
    /// - An `Option` of any of the above — a `None` leaves the client unauthenticated, which is
    ///   convenient when authentication is configured conditionally.
    pub fn token(self, token: impl IntoTokenProvider) -> Self {
        let Ok(mut inner) = self.0 else { return self };
        inner.token = token.into_token_provider();
        Self(Ok(inner))
    }

    /// Returns a [`Client`] that uses this [`ClientBuilder`] configuration.
    ///
    /// # Errors
    ///
    /// This method fails if:
    /// - the given `service_url` is invalid or cannot be used as a base URL
    /// - the [`reqwest::Client`] fails to build. Refer to [`reqwest::ClientBuilder::build`] for
    ///   more information on when this can happen.
    pub fn build(self) -> crate::Result<Client> {
        let inner = self.0?.apply_defaults();

        Ok(Client {
            inner: Arc::new(ClientInner {
                reqwest: inner.reqwest_builder.build()?,
                service_url: inner.service_url,
                propagate_traces: inner.propagate_traces,
                token: inner.token,
            }),
        })
    }
}

/// An identifier for a workload in Objectstore, along with defaults to use for all
/// operations within that Usecase.
///
/// Usecases need to be statically defined in Objectstore's configuration server-side.
/// Objectstore can make decisions based on the Usecase. For example, choosing the most
/// suitable storage backend.
#[derive(Debug, Clone)]
pub struct Usecase {
    name: Arc<str>,
    compression: Option<Compression>,
    expiration_policy: ExpirationPolicy,
}

impl Usecase {
    /// Creates a new Usecase.
    pub fn new(name: &str) -> Self {
        Self {
            name: name.into(),
            compression: Some(Compression::Zstd),
            expiration_policy: ExpirationPolicy::default(),
        }
    }

    /// Returns the name of this usecase.
    #[inline]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the compression algorithm to use for operations within this usecase.
    #[inline]
    pub fn compression(&self) -> Option<Compression> {
        self.compression
    }

    /// Sets the compression algorithm to use for operations within this usecase.
    ///
    /// It's still possible to override this default on each operation's builder.
    ///
    /// By default, [`Compression::Zstd`] is used. Pass [`None`] to disable compression.
    pub fn with_compression(self, compression: impl Into<Option<Compression>>) -> Self {
        Self {
            compression: compression.into(),
            ..self
        }
    }

    /// Returns the expiration policy to use by default for operations within this usecase.
    #[inline]
    pub fn expiration_policy(&self) -> ExpirationPolicy {
        self.expiration_policy
    }

    /// Sets the expiration policy to use for operations within this usecase.
    ///
    /// It's still possible to override this default on each operation's builder.
    ///
    /// By default, [`ExpirationPolicy::Manual`] is used, meaning that objects won't automatically
    /// expire.
    pub fn with_expiration_policy(self, expiration_policy: ExpirationPolicy) -> Self {
        Self {
            expiration_policy,
            ..self
        }
    }

    /// Creates a new custom [`Scope`].
    ///
    /// Add parts to it using [`Scope::push`].
    ///
    /// Generally, [`Usecase::for_organization`] and [`Usecase::for_project`] should fit most usecases,
    /// so prefer using those methods rather than creating your own custom [`Scope`].
    pub fn scope(&self) -> Scope {
        Scope::new(self.clone())
    }

    /// Creates a new [`Scope`] tied to the given organization.
    pub fn for_organization(&self, organization: u64) -> Scope {
        Scope::for_organization(self.clone(), organization)
    }

    /// Creates a new [`Scope`] tied to the given organization and project.
    pub fn for_project(&self, organization: u64, project: u64) -> Scope {
        Scope::for_project(self.clone(), organization, project)
    }
}

#[derive(Debug)]
pub(crate) struct ScopeInner {
    usecase: Usecase,
    scopes: scope::Scopes,
}

impl ScopeInner {
    #[inline]
    pub(crate) fn usecase(&self) -> &Usecase {
        &self.usecase
    }

    #[inline]
    pub(crate) fn scopes(&self) -> &scope::Scopes {
        &self.scopes
    }
}

/// A [`Scope`] is a sequence of key-value pairs that defines a (possibly nested) namespace within a
/// [`Usecase`].
///
/// To construct a [`Scope`], use [`Usecase::for_organization`], [`Usecase::for_project`], or
/// [`Usecase::scope`] for custom scopes.
#[derive(Debug)]
pub struct Scope(pub(crate) crate::Result<ScopeInner>);

impl Scope {
    /// Creates a new root-level Scope for the given usecase.
    ///
    /// Using a custom Scope is discouraged, prefer using [`Usecase::for_organization`] or [`Usecase::for_project`] instead.
    pub fn new(usecase: Usecase) -> Self {
        Self(Ok(ScopeInner {
            usecase,
            scopes: scope::Scopes::empty(),
        }))
    }

    fn for_organization(usecase: Usecase, organization: u64) -> Self {
        Self::new(usecase).push("org", organization)
    }

    fn for_project(usecase: Usecase, organization: u64, project: u64) -> Self {
        Self::for_organization(usecase, organization).push("project", project)
    }

    /// Extends this Scope by creating a new sub-scope nested within it.
    pub fn push<V>(self, key: &str, value: V) -> Self
    where
        V: std::fmt::Display,
    {
        let result = self.0.and_then(|mut inner| {
            inner.scopes.push(key, value)?;
            Ok(inner)
        });

        Self(result)
    }

    /// Creates a session for this scope using the given client.
    ///
    /// # Errors
    ///
    /// Returns an error if the scope is invalid (e.g. it contains invalid characters).
    pub fn session(self, client: &Client) -> crate::Result<Session> {
        client.session(self)
    }
}

#[derive(Debug)]
pub(crate) struct ClientInner {
    reqwest: reqwest::Client,
    service_url: Url,
    propagate_traces: bool,
    token: Option<TokenProvider>,
}

/// A client for Objectstore. Use [`Client::builder`] to configure and construct a Client.
///
/// To perform CRUD operations, one has to create a Client, and then scope it to a [`Usecase`]
/// and Scope in order to create a [`Session`].
///
/// If your Objectstore instance enforces authorization checks, you must provide
/// authentication via [`ClientBuilder::token`]. It accepts anything that converts
/// into a [`TokenProvider`]:
///
/// - **[`TokenGenerator`](crate::TokenGenerator)** — for internal services that have access to
///   an EdDSA keypair. The generator signs a fresh JWT for each request, scoped to the
///   specific usecase and scope being accessed.
/// - **`String` / `&str`** — a pre-signed JWT, used as-is for every request.
///   Use this for external services that receive a token from another source.
///
/// # Examples
///
/// Internal service with a keypair:
///
/// ```no_run
/// use std::time::Duration;
/// use objectstore_client::{Client, SecretKey, TokenGenerator, Usecase};
/// use objectstore_types::auth::Permission;
///
/// # async fn example() -> objectstore_client::Result<()> {
/// let token_generator = TokenGenerator::new(SecretKey {
///         secret_key: "<safely inject secret key>".into(),
///         kid: "my-service".into(),
///     })?
///     .expiry_seconds(30)
///     .permissions(&[Permission::ObjectRead]);
///
/// let client = Client::builder("http://localhost:8888/")
///     .timeout(Duration::from_secs(1))
///     .propagate_traces(true)
///     .token(token_generator)
///     .build()?;
/// # Ok(())
/// # }
/// ```
///
/// External service with a pre-signed JWT (obtained via
/// [`TokenGenerator::sign`](crate::TokenGenerator::sign)):
///
/// ```no_run
/// use objectstore_client::{Client, SecretKey, TokenGenerator, Usecase};
///
/// # fn example() -> objectstore_client::Result<()> {
/// let scope = Usecase::new("my_app").for_project(42, 1337);
/// let token = TokenGenerator::new(SecretKey {
///     secret_key: "<private key>".into(),
///     kid: "my-service".into(),
/// })?.sign(&scope)?;
///
/// let client = Client::builder("http://localhost:8888/")
///     .token(token)
///     .build()?;
/// # Ok(())
/// # }
/// ```
///
/// Optional authentication — pass an `Option` straight through, leaving the client
/// unauthenticated when it is `None`:
///
/// ```no_run
/// use objectstore_client::Client;
///
/// # fn example() -> objectstore_client::Result<()> {
/// // Authenticate only if a token is present in the environment.
/// let token_opt = std::env::var("OBJECTSTORE_TOKEN").ok();
///
/// let client = Client::builder("http://localhost:8888/")
///     .token(token_opt)
///     .build()?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Client {
    inner: Arc<ClientInner>,
}

impl Client {
    /// Creates a new [`Client`], configured with the given `service_url` and default
    /// configuration.
    ///
    /// Use [`Client::builder`] for more fine-grained configuration.
    ///
    /// # Errors
    ///
    /// This method fails if [`ClientBuilder::build`] fails.
    pub fn new(service_url: impl reqwest::IntoUrl) -> crate::Result<Client> {
        ClientBuilder::new(service_url).build()
    }

    /// Convenience function to create a [`ClientBuilder`].
    pub fn builder(service_url: impl reqwest::IntoUrl) -> ClientBuilder {
        ClientBuilder::new(service_url)
    }

    /// Creates a session for the given scope using this client.
    ///
    /// # Errors
    ///
    /// Returns an error if the scope is invalid (e.g. it contains invalid characters).
    pub fn session(&self, scope: Scope) -> crate::Result<Session> {
        scope.0.map(|inner| Session {
            scope: inner.into(),
            client: self.inner.clone(),
        })
    }
}

/// Represents a session with Objectstore, tied to a specific Usecase and Scope within it.
///
/// Create a Session using [`Client::session`] or [`Scope::session`].
#[derive(Debug, Clone)]
pub struct Session {
    pub(crate) scope: Arc<ScopeInner>,
    pub(crate) client: Arc<ClientInner>,
}

/// The type of [`Stream`](futures_util::Stream) to be used for a PUT request.
pub type ClientStream = BoxStream<'static, io::Result<Bytes>>;

impl Session {
    /// Generates a GET url to the object with the given `key`.
    ///
    /// This can then be used by downstream services to fetch the given object.
    /// NOTE however that the service does not strictly follow HTTP semantics,
    /// in particular in relation to `Accept-Encoding`.
    pub fn object_url(&self, object_key: &str) -> Url {
        let mut url = self.client.service_url.clone();

        // `path_segments_mut` can only error if the url is cannot-be-a-base,
        // and we check that in `ClientBuilder::new`, therefore this will never panic.
        let mut segments = url.path_segments_mut().unwrap();
        segments
            .push("v1")
            .push("objects")
            .push(&self.scope.usecase.name)
            .push(&self.scope.scopes.as_api_path().to_string())
            .extend(object_key.split('/'));
        drop(segments);

        url
    }

    /// Returns a signed token if a token or generator was provided or `None` otherwise
    pub fn mint_token(&self) -> crate::Result<Option<String>> {
        match &self.client.token {
            Some(TokenProvider::Generator(generator)) => {
                Ok(Some(generator.sign_for_scope(&self.scope)?))
            }
            Some(TokenProvider::Static(token)) => Ok(Some(token.clone())),
            None => Ok(None),
        }
    }

    fn batch_url(&self) -> Url {
        let mut url = self.client.service_url.clone();

        // `path_segments_mut` can only error if the url is cannot-be-a-base,
        // and we check that in `ClientBuilder::new`, therefore this will never panic.
        let mut segments = url.path_segments_mut().unwrap();
        segments
            .push("v1")
            .push("objects:batch")
            .push(self.scope.usecase().name())
            .push(&self.scope.scopes.as_api_path().to_string())
            .push(""); // trailing slash
        drop(segments);

        url
    }

    #[cfg(feature = "multipart")]
    fn multipart_url(
        &self,
        suffix: Option<&'static str>,
        object_key: Option<&str>,
        query_pairs: Option<Vec<(&str, String)>>,
    ) -> Url {
        let mut url = self.client.service_url.clone();

        // `path_segments_mut` can only error if the url is cannot-be-a-base,
        // and we check that in `ClientBuilder::new`, therefore this will never panic.
        let mut segments = url.path_segments_mut().unwrap();
        segments
            .push("v1")
            .push(match suffix {
                Some("parts") => "objects:multipart:parts",
                Some("complete") => "objects:multipart:complete",
                _ => "objects:multipart",
            })
            .push(&self.scope.usecase.name)
            .push(&self.scope.scopes.as_api_path().to_string());
        if let Some(object_key) = object_key.filter(|key| !key.is_empty()) {
            segments.extend(object_key.split('/'));
        }
        drop(segments);
        if let Some(query_pairs) = query_pairs {
            let mut pairs = url.query_pairs_mut();
            for (key, value) in query_pairs {
                pairs.append_pair(key, &value);
            }
        }

        url
    }

    fn prepare_builder(&self, mut builder: RequestBuilder) -> crate::Result<RequestBuilder> {
        if let Some(token) = self.mint_token()? {
            builder = builder.header("x-os-auth", format!("Bearer {token}"));
        }
        if self.client.propagate_traces {
            let trace_headers =
                sentry_core::configure_scope(|scope| Some(scope.iter_trace_propagation_headers()));
            for (header_name, value) in trace_headers.into_iter().flatten() {
                builder = builder.header(header_name, value);
            }
        }
        Ok(builder)
    }

    pub(crate) fn request(
        &self,
        method: reqwest::Method,
        object_key: &str,
    ) -> crate::Result<RequestBuilder> {
        let url = self.object_url(object_key);
        let builder = self.client.reqwest.request(method, url);
        self.prepare_builder(builder)
    }

    pub(crate) fn batch_request(&self) -> crate::Result<RequestBuilder> {
        let url = self.batch_url();
        let builder = self.client.reqwest.post(url);
        self.prepare_builder(builder)
    }

    #[cfg(feature = "multipart")]
    pub(crate) fn multipart_request(
        &self,
        method: reqwest::Method,
        action: Option<&'static str>,
        object_key: Option<&str>,
        query_pairs: Option<Vec<(&str, String)>>,
    ) -> crate::Result<RequestBuilder> {
        let url = self.multipart_url(action, object_key, query_pairs);
        let builder = self.client.reqwest.request(method, url);
        self.prepare_builder(builder)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_object_url() {
        let client = Client::new("http://127.0.0.1:8888/").unwrap();
        let usecase = Usecase::new("testing");
        let scope = usecase
            .for_project(12345, 1337)
            .push("app_slug", "email_app");
        let session = client.session(scope).unwrap();

        assert_eq!(
            session.object_url("foo/bar").to_string(),
            "http://127.0.0.1:8888/v1/objects/testing/org=12345;project=1337;app_slug=email_app/foo/bar"
        )
    }

    #[test]
    fn test_object_url_with_base_path() {
        let client = Client::new("http://127.0.0.1:8888/api/prefix").unwrap();
        let usecase = Usecase::new("testing");
        let scope = usecase.for_project(12345, 1337);
        let session = client.session(scope).unwrap();

        assert_eq!(
            session.object_url("foo/bar").to_string(),
            "http://127.0.0.1:8888/api/prefix/v1/objects/testing/org=12345;project=1337/foo/bar"
        )
    }
}