azure_data_cosmos_driver 0.2.0

Core implementation layer for Azure Cosmos DB - provides transport, routing, and protocol handling for cross-language SDK reuse
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

//! Account reference and authentication types.

use azure_core::credentials::{Secret, TokenCredential};
use std::{hash::Hash, sync::Arc};
use url::Url;

/// An account endpoint URL used as a cache key.
///
/// This is a newtype wrapper around `Url` that implements `Hash` and `Eq`
/// based on the URL only (ignoring authentication). Used as a key in
/// account-scoped caches.
#[derive(Clone, Debug)]
pub(crate) struct AccountEndpoint(Url);

impl AccountEndpoint {
    /// Creates a new account endpoint from a URL.
    pub(crate) fn new(url: Url) -> Self {
        Self(url)
    }

    /// Returns the endpoint URL.
    pub(crate) fn url(&self) -> &Url {
        &self.0
    }

    /// Returns the host portion of the endpoint URL.
    ///
    /// Returns an empty string if the URL has no host (which shouldn't
    /// happen for valid Cosmos DB endpoints).
    pub(crate) fn host(&self) -> &str {
        self.0.host_str().unwrap_or("")
    }

    /// Joins a resource path to this endpoint to create a full request URL.
    ///
    /// The path should be the resource path (e.g., "/dbs/mydb/colls/mycoll").
    /// Leading slashes in the path are handled correctly.
    pub(crate) fn join_path(&self, path: &str) -> Url {
        let mut url = self.0.clone();
        // Set the path, handling leading slash
        let normalized_path = if path.starts_with('/') {
            path.to_string()
        } else if path.is_empty() {
            String::new()
        } else {
            format!("/{}", path)
        };
        url.set_path(&normalized_path);
        url
    }
}

impl PartialEq for AccountEndpoint {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl Eq for AccountEndpoint {}

impl std::fmt::Display for AccountEndpoint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.0.as_str())
    }
}

impl Hash for AccountEndpoint {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl From<Url> for AccountEndpoint {
    fn from(url: Url) -> Self {
        Self::new(url)
    }
}

impl TryFrom<&str> for AccountEndpoint {
    type Error = url::ParseError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Ok(Self::new(Url::parse(value)?))
    }
}

impl From<&AccountReference> for AccountEndpoint {
    fn from(account: &AccountReference) -> Self {
        account.endpoint.clone()
    }
}

impl<'de> serde::Deserialize<'de> for AccountEndpoint {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Url::parse(&s)
            .map(Self::new)
            .map_err(serde::de::Error::custom)
    }
}

/// Authentication options for connecting to a Cosmos DB account.
///
/// Either key-based authentication using a master key, or token-based
/// authentication using an Azure credential (e.g., managed identity, service principal).
#[derive(Clone)]
pub enum Credential {
    /// Key-based authentication using the account's primary or secondary master key.
    MasterKey(Secret),
    /// Token-based authentication using an Azure credential.
    TokenCredential(Arc<dyn TokenCredential>),
}

impl std::fmt::Debug for Credential {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MasterKey(_) => f.debug_tuple("MasterKey").field(&"***").finish(),
            Self::TokenCredential(_) => f.debug_tuple("TokenCredential").field(&"...").finish(),
        }
    }
}

impl From<Secret> for Credential {
    fn from(key: Secret) -> Self {
        Self::MasterKey(key)
    }
}

impl From<Arc<dyn TokenCredential>> for Credential {
    fn from(credential: Arc<dyn TokenCredential>) -> Self {
        Self::TokenCredential(credential)
    }
}

/// A reference to a Cosmos DB account.
///
/// Contains the service endpoint and authentication credentials. Authentication
/// is required - use [`AccountReferenceBuilder`] to construct an instance.
///
/// # Examples
///
/// ```
/// use azure_data_cosmos_driver::models::AccountReference;
/// use url::Url;
///
/// // With master key authentication
/// let account = AccountReference::builder(
///     Url::parse("https://myaccount.documents.azure.com:443/").unwrap(),
/// )
/// .master_key("my-master-key")
/// .build()
/// .unwrap();
///
/// // Using the shorthand constructor
/// let account = AccountReference::with_master_key(
///     Url::parse("https://myaccount.documents.azure.com:443/").unwrap(),
///     "my-master-key",
/// );
/// ```
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct AccountReference {
    /// The service endpoint URL (required).
    endpoint: AccountEndpoint,
    /// Authentication credentials (required).
    credential: Credential,
    /// Fallback endpoints tried when the primary endpoint is unavailable.
    backup_endpoints: Vec<Url>,
}

// Manual PartialEq implementation because Credential contains Arc<dyn TokenCredential>
// which doesn't implement PartialEq. We compare by endpoint only — credential and
// backup_endpoints are intentionally excluded. Backup endpoints are a bootstrap
// configuration concern, not an identity concern: the same account should reuse
// its driver regardless of how it was bootstrapped.
impl PartialEq for AccountReference {
    fn eq(&self, other: &Self) -> bool {
        self.endpoint == other.endpoint
    }
}

impl Eq for AccountReference {}

// Manual Hash implementation to match PartialEq (compares by endpoint only).
impl std::hash::Hash for AccountReference {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.endpoint.hash(state);
    }
}

impl AccountReference {
    /// Creates a new builder for an account reference.
    ///
    /// Use this to construct an `AccountReference` with the required authentication.
    pub fn builder(endpoint: Url) -> AccountReferenceBuilder {
        AccountReferenceBuilder::new(endpoint)
    }

    /// Creates a new account reference with master key authentication.
    ///
    /// This is a convenience method for the common case of key-based auth.
    pub fn with_master_key(endpoint: Url, key: impl Into<Secret>) -> Self {
        Self {
            endpoint: AccountEndpoint::from(endpoint),
            credential: Credential::MasterKey(key.into()),
            backup_endpoints: Vec::new(),
        }
    }

    /// Creates a new account reference with token credential authentication.
    ///
    /// This is a convenience method for token-based auth (e.g., managed identity).
    pub fn with_credential(endpoint: Url, credential: Arc<dyn TokenCredential>) -> Self {
        Self {
            endpoint: AccountEndpoint::from(endpoint),
            credential: Credential::TokenCredential(credential),
            backup_endpoints: Vec::new(),
        }
    }

    /// Returns the service endpoint URL.
    pub fn endpoint(&self) -> &Url {
        self.endpoint.url()
    }

    /// Returns the authentication options.
    ///
    /// Authentication is always present - it's required during construction.
    pub fn auth(&self) -> &Credential {
        &self.credential
    }

    /// Returns the backup endpoints.
    ///
    /// These are fallback endpoints tried when the primary endpoint is unavailable.
    pub fn backup_endpoints(&self) -> &[Url] {
        &self.backup_endpoints
    }

    /// Returns a new `AccountReference` with the given backup endpoints.
    ///
    /// This is a post-construction transformation for use when the account
    /// was created via a convenience constructor (`with_master_key`,
    /// `with_credential`) and backup endpoints need to be attached without
    /// going through the full builder.
    pub fn with_backup_endpoints(mut self, endpoints: Vec<Url>) -> Self {
        self.backup_endpoints = endpoints;
        self
    }
}

/// Builder for constructing an [`AccountReference`].
///
/// Authentication must be configured before calling `build()`.
///
/// # Example
///
/// ```
/// use azure_data_cosmos_driver::models::AccountReference;
/// use url::Url;
///
/// let account = AccountReference::builder(
///     Url::parse("https://myaccount.documents.azure.com:443/").unwrap(),
/// )
/// .master_key("my-master-key")
/// .build()
/// .unwrap();
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct AccountReferenceBuilder {
    endpoint: AccountEndpoint,
    credential: Option<Credential>,
    backup_endpoints: Vec<Url>,
}

impl AccountReferenceBuilder {
    /// Creates a new builder with the specified endpoint.
    pub fn new(endpoint: Url) -> Self {
        Self {
            endpoint: AccountEndpoint::from(endpoint),
            credential: None,
            backup_endpoints: Vec::new(),
        }
    }

    /// Sets the service endpoint URL.
    pub fn endpoint(mut self, endpoint: Url) -> Self {
        self.endpoint = AccountEndpoint::from(endpoint);
        self
    }

    /// Sets master key authentication.
    pub fn master_key(mut self, key: impl Into<Secret>) -> Self {
        self.credential = Some(Credential::MasterKey(key.into()));
        self
    }

    /// Sets token credential authentication.
    pub fn credential(mut self, credential: Arc<dyn TokenCredential>) -> Self {
        self.credential = Some(Credential::TokenCredential(credential));
        self
    }

    /// Sets authentication options directly.
    pub fn auth(mut self, credential: Credential) -> Self {
        self.credential = Some(credential);
        self
    }

    /// Sets backup endpoints for fallback when the primary endpoint is unavailable.
    pub fn with_backup_endpoints(mut self, endpoints: Vec<Url>) -> Self {
        self.backup_endpoints = endpoints;
        self
    }

    /// Builds the account reference.
    ///
    /// # Errors
    ///
    /// Returns an error if authentication has not been configured.
    pub fn build(self) -> azure_core::Result<AccountReference> {
        let credential = self.credential.ok_or_else(|| {
            azure_core::Error::with_message(
                azure_core::error::ErrorKind::Credential,
                "Authentication is required. Use master_key() or credential() to set credentials.",
            )
        })?;

        Ok(AccountReference {
            endpoint: self.endpoint,
            credential,
            backup_endpoints: self.backup_endpoints,
        })
    }
}

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

    #[test]
    fn account_endpoint_join_path_with_leading_slash() {
        let endpoint =
            AccountEndpoint::try_from("https://myaccount.documents.azure.com:443/").unwrap();
        let url = endpoint.join_path("/dbs/mydb/colls/mycoll");
        assert_eq!(url.path(), "/dbs/mydb/colls/mycoll");
        assert_eq!(url.host_str(), Some("myaccount.documents.azure.com"));
    }

    #[test]
    fn account_endpoint_join_path_without_leading_slash() {
        let endpoint =
            AccountEndpoint::try_from("https://myaccount.documents.azure.com:443/").unwrap();
        let url = endpoint.join_path("dbs/mydb/colls/mycoll");
        assert_eq!(url.path(), "/dbs/mydb/colls/mycoll");
    }

    #[test]
    fn account_endpoint_join_path_empty() {
        let endpoint =
            AccountEndpoint::try_from("https://myaccount.documents.azure.com:443/").unwrap();
        let url = endpoint.join_path("");
        // Empty path is normalized to "/" by the URL library
        assert_eq!(url.path(), "/");
    }

    #[test]
    fn account_endpoint_host() {
        let endpoint =
            AccountEndpoint::try_from("https://myaccount.documents.azure.com:443/").unwrap();
        assert_eq!(endpoint.host(), "myaccount.documents.azure.com");
    }

    #[test]
    fn builder_with_master_key() {
        let account =
            AccountReference::builder(Url::parse("https://test.documents.azure.com:443/").unwrap())
                .master_key("my-secret-key")
                .build()
                .unwrap();

        match account.auth() {
            Credential::MasterKey(key) => assert_eq!(key.secret(), "my-secret-key"),
            _ => panic!("Expected MasterKey auth"),
        }
    }

    #[test]
    fn builder_requires_auth() {
        let result =
            AccountReference::builder(Url::parse("https://test.documents.azure.com:443/").unwrap())
                .build();

        assert!(result.is_err());
    }

    #[test]
    fn builder_endpoint_setter_uses_url() {
        let account = AccountReference::builder(
            Url::parse("https://initial.documents.azure.com:443/").unwrap(),
        )
        .endpoint(Url::parse("https://override.documents.azure.com:443/").unwrap())
        .master_key("my-secret-key")
        .build()
        .unwrap();

        assert_eq!(
            account.endpoint().as_str(),
            "https://override.documents.azure.com/"
        );
    }

    #[test]
    fn shorthand_with_master_key() {
        let account = AccountReference::with_master_key(
            Url::parse("https://test.documents.azure.com:443/").unwrap(),
            "my-secret-key",
        );

        match account.auth() {
            Credential::MasterKey(key) => assert_eq!(key.secret(), "my-secret-key"),
            _ => panic!("Expected MasterKey auth"),
        }
    }

    #[test]
    fn account_endpoint_deserialize_valid_url() {
        let endpoint: AccountEndpoint =
            serde_json::from_str(r#""https://myaccount.documents.azure.com:443/""#).unwrap();
        assert_eq!(endpoint.host(), "myaccount.documents.azure.com");
    }

    #[test]
    fn account_endpoint_deserialize_invalid_url() {
        let result: serde_json::Result<AccountEndpoint> =
            serde_json::from_str(r#""not a valid url""#);
        assert!(result.is_err());
    }

    #[test]
    fn account_reference_equality_ignores_auth() {
        let account1 = AccountReference::with_master_key(
            Url::parse("https://test.documents.azure.com:443/").unwrap(),
            "key1",
        );

        let account2 = AccountReference::with_master_key(
            Url::parse("https://test.documents.azure.com:443/").unwrap(),
            "key2",
        );

        // Same endpoint, different keys - should be equal
        assert_eq!(account1, account2);
    }

    #[test]
    fn shorthand_has_empty_backup_endpoints() {
        let account = AccountReference::with_master_key(
            Url::parse("https://test.documents.azure.com:443/").unwrap(),
            "key",
        );
        assert!(account.backup_endpoints().is_empty());
    }

    #[test]
    fn builder_sets_backup_endpoints() {
        let backup = vec![
            Url::parse("https://backup1.documents.azure.com:443/").unwrap(),
            Url::parse("https://backup2.documents.azure.com:443/").unwrap(),
        ];
        let account =
            AccountReference::builder(Url::parse("https://test.documents.azure.com:443/").unwrap())
                .master_key("key")
                .with_backup_endpoints(backup.clone())
                .build()
                .unwrap();

        assert_eq!(account.backup_endpoints(), &backup);
    }

    #[test]
    fn builder_default_backup_endpoints_is_empty() {
        let account =
            AccountReference::builder(Url::parse("https://test.documents.azure.com:443/").unwrap())
                .master_key("key")
                .build()
                .unwrap();

        assert!(account.backup_endpoints().is_empty());
    }
}