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
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

//! Resource reference types for Cosmos DB resources.
//!
//! These types provide compile-time safe references to Cosmos DB resources.
//! Each reference enforces either all-names or all-RIDs addressing through
//! internal enums, preventing mixed addressing modes.

use crate::models::{
    resource_id::{ResourceId, ResourceIdentifier, ResourceName},
    AccountReference, PartitionKey, PartitionKeyDefinition,
};

use std::borrow::Cow;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
// =============================================================================
// DatabaseReference
// =============================================================================

/// A reference to a Cosmos DB database.
///
/// Contains either the name or resource identifier (RID) of the database,
/// along with a reference to its parent account. The addressing mode (name vs RID)
/// is enforced at compile time through internal enums.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct DatabaseReference {
    /// Reference to the parent account.
    account: AccountReference,
    /// The database identifier (by name or by RID).
    id: ResourceIdentifier,
}

impl DatabaseReference {
    /// Creates a new database reference by name.
    pub fn from_name(account: AccountReference, name: impl Into<Cow<'static, str>>) -> Self {
        Self {
            account,
            id: ResourceIdentifier::ByName(ResourceName::new(name)),
        }
    }

    /// Creates a new database reference by RID.
    pub fn from_rid(account: AccountReference, rid: impl Into<Cow<'static, str>>) -> Self {
        Self {
            account,
            id: ResourceIdentifier::ByRid(ResourceId::new(rid)),
        }
    }

    /// Returns a reference to the parent account.
    pub fn account(&self) -> &AccountReference {
        &self.account
    }

    /// Consumes this database reference and returns the parent account.
    pub fn into_account(self) -> AccountReference {
        self.account
    }

    /// Returns the database name, if this is a name-based reference.
    pub fn name(&self) -> Option<&str> {
        self.id.name()
    }

    /// Returns the database RID, if this is a RID-based reference.
    pub fn rid(&self) -> Option<&str> {
        self.id.rid()
    }

    /// Returns `true` if this is a name-based reference.
    pub fn is_by_name(&self) -> bool {
        matches!(self.id, ResourceIdentifier::ByName(_))
    }

    /// Returns `true` if this is a RID-based reference.
    pub fn is_by_rid(&self) -> bool {
        matches!(self.id, ResourceIdentifier::ByRid(_))
    }

    /// Returns the name-based relative path: `/dbs/{name}`
    ///
    /// Returns `None` if this is a RID-based reference.
    pub fn name_based_path(&self) -> Option<String> {
        self.id.name().map(|n| format!("/dbs/{}", n))
    }

    /// Returns the RID-based relative path: `/dbs/{rid}`
    ///
    /// Returns `None` if this is a name-based reference.
    pub fn rid_based_path(&self) -> Option<String> {
        self.id.rid().map(|r| format!("/dbs/{}", r))
    }
}

// =============================================================================
// ContainerReference
// =============================================================================

/// A resolved reference to a Cosmos DB container.
///
/// Always carries both the name-based and RID-based identifiers for the container
/// and its parent database, along with immutable container properties (partition key
/// definition and unique key policy). This guarantees that both addressing modes
/// are available without additional I/O.
///
/// Instances are created via async factory methods that resolve the container
/// metadata from the Cosmos DB service or cache.
///
/// ## Equality and Hashing
///
/// Two `ContainerReference` values are considered equal if they refer to the same
/// account, container RID, and container name. This detects both delete + recreate
/// (same name, different RID) and rename scenarios (same RID, different name).
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct ContainerReference {
    /// Reference to the parent account.
    account: AccountReference,
    /// The database user-provided name.
    db_name: ResourceName,
    /// The database internal RID.
    db_rid: ResourceId,
    /// The container user-provided name.
    container_name: ResourceName,
    /// The container internal RID.
    container_rid: ResourceId,
    /// Partition key definition for this container.
    partition_key_definition: PartitionKeyDefinition,
    /// Pre-computed name-based path: `/dbs/{db_name}/colls/{container_name}`.
    ///
    /// Stored as `Arc<str>` so cloning `ContainerReference` is cheap (atomic refcount).
    name_based_path: Arc<str>,
    /// Pre-computed RID-based path: `/dbs/{db_rid}/colls/{container_rid}`.
    rid_based_path: Arc<str>,
}

impl PartialEq for ContainerReference {
    fn eq(&self, other: &Self) -> bool {
        self.account == other.account
            && self.container_rid == other.container_rid
            && self.container_name == other.container_name
    }
}

impl Eq for ContainerReference {}

impl Hash for ContainerReference {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.account.hash(state);
        self.container_rid.hash(state);
        self.container_name.hash(state);
    }
}

impl ContainerReference {
    /// Creates a fully resolved container reference.
    ///
    /// All fields are required — the caller must have already resolved both
    /// name-based and RID-based identifiers (typically by reading the container
    /// from the Cosmos DB service).
    ///
    /// The immutable properties (partition key definition, unique key policy)
    /// are extracted from `container_properties` and stored internally.
    ///
    /// Not exposed publicly — use [`CosmosDriver::resolve_container()`](crate::driver::CosmosDriver::resolve_container)
    /// to obtain a resolved container reference.
    pub(crate) fn new(
        account: AccountReference,
        db_name: impl Into<ResourceName>,
        db_rid: impl Into<ResourceId>,
        container_name: impl Into<ResourceName>,
        container_rid: impl Into<ResourceId>,
        container_properties: &crate::models::ContainerProperties,
    ) -> Self {
        let db_name: ResourceName = db_name.into();
        let db_rid: ResourceId = db_rid.into();
        let container_name: ResourceName = container_name.into();
        let container_rid: ResourceId = container_rid.into();
        let name_based_path: Arc<str> = format!("/dbs/{}/colls/{}", db_name, container_name).into();
        let rid_based_path: Arc<str> = format!("/dbs/{}/colls/{}", db_rid, container_rid).into();
        Self {
            account,
            db_name,
            db_rid,
            container_name,
            container_rid,
            partition_key_definition: container_properties.partition_key.clone(),
            name_based_path,
            rid_based_path,
        }
    }

    /// Returns a reference to the parent account.
    pub fn account(&self) -> &AccountReference {
        &self.account
    }

    /// Returns the container name.
    pub fn name(&self) -> &str {
        self.container_name.as_str()
    }

    /// Returns the container RID.
    pub fn rid(&self) -> &str {
        self.container_rid.as_str()
    }

    /// Returns the database name.
    pub fn database_name(&self) -> &str {
        self.db_name.as_str()
    }

    /// Returns the database RID.
    pub fn database_rid(&self) -> &str {
        self.db_rid.as_str()
    }

    /// Returns the partition key definition for this container.
    pub fn partition_key_definition(&self) -> &crate::models::PartitionKeyDefinition {
        &self.partition_key_definition
    }

    /// Returns the name-based relative path: `/dbs/{db_name}/colls/{container_name}`
    pub fn name_based_path(&self) -> &str {
        &self.name_based_path
    }

    /// Returns the RID-based relative path: `/dbs/{db_rid}/colls/{container_rid}`
    pub fn rid_based_path(&self) -> &str {
        &self.rid_based_path
    }
}

// =============================================================================
// ItemReference
// =============================================================================

/// A reference to a Cosmos DB item (document).
///
/// Contains the container reference, partition key, and item identifier (name or RID).
/// The partition key is required because all item operations in Cosmos DB require it.
///
/// The resource link is pre-computed for efficiency.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct ItemReference {
    /// Reference to the parent container.
    container: ContainerReference,
    /// The partition key for the item.
    partition_key: PartitionKey,
    /// The item identifier (name or RID).
    item_identifier: ResourceIdentifier,
    /// Pre-computed resource link.
    resource_link: String,
}

impl ItemReference {
    /// Creates a new item reference by name.
    ///
    /// # Arguments
    ///
    /// * `container` - Reference to the parent container.
    /// * `partition_key` - The partition key for the item.
    /// * `item_name` - The document ID (name) of the item.
    pub fn from_name(
        container: &ContainerReference,
        partition_key: PartitionKey,
        item_name: impl Into<Cow<'static, str>>,
    ) -> Self {
        let name = ResourceName::new(item_name);
        let resource_link = format!("{}/docs/{}", container.name_based_path(), name);
        Self {
            container: container.clone(),
            partition_key,
            item_identifier: ResourceIdentifier::by_name(name),
            resource_link,
        }
    }

    /// Creates a new item reference by RID.
    ///
    /// # Arguments
    ///
    /// * `container` - Reference to the parent container.
    /// * `partition_key` - The partition key for the item.
    /// * `item_rid` - The internal RID of the item.
    pub fn from_rid(
        container: &ContainerReference,
        partition_key: PartitionKey,
        item_rid: impl Into<Cow<'static, str>>,
    ) -> Self {
        let rid = ResourceId::new(item_rid);
        let resource_link = format!("{}/docs/{}", container.rid_based_path(), rid);
        Self {
            container: container.clone(),
            partition_key,
            item_identifier: ResourceIdentifier::by_rid(rid),
            resource_link,
        }
    }

    /// Returns a reference to the parent container.
    pub fn container(&self) -> &ContainerReference {
        &self.container
    }

    /// Returns a reference to the parent account.
    pub fn account(&self) -> &AccountReference {
        self.container.account()
    }

    /// Returns a reference to the partition key.
    pub fn partition_key(&self) -> &PartitionKey {
        &self.partition_key
    }

    /// Returns the item name (document ID), if this is a name-based reference.
    pub fn name(&self) -> Option<&str> {
        self.item_identifier.name()
    }

    /// Returns the item RID, if this is a RID-based reference.
    pub fn rid(&self) -> Option<&str> {
        self.item_identifier.rid()
    }

    /// Returns `true` if this is a name-based reference.
    pub fn is_by_name(&self) -> bool {
        self.item_identifier.is_by_name()
    }

    /// Returns `true` if this is a RID-based reference.
    pub fn is_by_rid(&self) -> bool {
        self.item_identifier.is_by_rid()
    }

    /// Returns the pre-computed resource link for this item.
    ///
    /// For name-based references: `/dbs/{db}/colls/{coll}/docs/{item}`
    /// For RID-based references: `/dbs/{db_rid}/colls/{coll_rid}/docs/{item_rid}`
    pub fn resource_link(&self) -> &str {
        &self.resource_link
    }
}

// =============================================================================
// StoredProcedureReference
// =============================================================================

/// A reference to a Cosmos DB stored procedure.
///
/// Contains the parent container and either the name or RID of the stored procedure.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct StoredProcedureReference {
    /// Reference to the parent container.
    container: ContainerReference,
    /// The stored procedure identifier.
    stored_procedure_identifier: ResourceIdentifier,
    /// Pre-computed resource link.
    resource_link: String,
}

impl StoredProcedureReference {
    /// Creates a new stored procedure reference by name.
    pub fn from_name(
        container: &ContainerReference,
        stored_procedure_name: impl Into<Cow<'static, str>>,
    ) -> Self {
        let stored_procedure_name = ResourceName::new(stored_procedure_name);
        let resource_link = format!(
            "{}/sprocs/{}",
            container.name_based_path(),
            stored_procedure_name
        );
        Self {
            container: container.clone(),
            stored_procedure_identifier: ResourceIdentifier::by_name(stored_procedure_name),
            resource_link,
        }
    }

    /// Creates a new stored procedure reference by RID.
    pub fn from_rid(
        container: &ContainerReference,
        stored_procedure_rid: impl Into<Cow<'static, str>>,
    ) -> Self {
        let stored_procedure_rid = ResourceId::new(stored_procedure_rid);
        let resource_link = format!(
            "{}/sprocs/{}",
            container.rid_based_path(),
            stored_procedure_rid
        );
        Self {
            container: container.clone(),
            stored_procedure_identifier: ResourceIdentifier::by_rid(stored_procedure_rid),
            resource_link,
        }
    }

    /// Returns a reference to the parent container.
    pub fn container(&self) -> &ContainerReference {
        &self.container
    }

    /// Returns a reference to the parent account.
    pub fn account(&self) -> &AccountReference {
        self.container.account()
    }

    /// Returns the stored procedure name, if this is a name-based reference.
    pub fn name(&self) -> Option<&str> {
        self.stored_procedure_identifier.name()
    }

    /// Returns the stored procedure RID, if this is a RID-based reference.
    pub fn rid(&self) -> Option<&str> {
        self.stored_procedure_identifier.rid()
    }

    /// Returns `true` if this is a name-based reference.
    pub fn is_by_name(&self) -> bool {
        self.stored_procedure_identifier.is_by_name()
    }

    /// Returns `true` if this is a RID-based reference.
    pub fn is_by_rid(&self) -> bool {
        self.stored_procedure_identifier.is_by_rid()
    }

    /// Returns the pre-computed resource link for this stored procedure.
    ///
    /// For name-based references: `/dbs/{db}/colls/{coll}/sprocs/{name}`
    /// For RID-based references: `/dbs/{db_rid}/colls/{coll_rid}/sprocs/{rid}`
    pub fn resource_link(&self) -> &str {
        &self.resource_link
    }
}

// =============================================================================
// TriggerReference
// =============================================================================

/// A reference to a Cosmos DB trigger resource.
///
/// Contains the parent container and either the name or RID of the trigger.
/// This type is for referencing trigger definitions.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct TriggerReference {
    /// Reference to the parent container.
    container: ContainerReference,
    /// The trigger identifier.
    trigger_identifier: ResourceIdentifier,
    /// Pre-computed resource link.
    resource_link: String,
}

impl TriggerReference {
    /// Creates a new trigger reference by name.
    pub fn from_name(
        container: &ContainerReference,
        trigger_name: impl Into<Cow<'static, str>>,
    ) -> Self {
        let trigger_name = ResourceName::new(trigger_name);
        let resource_link = format!("{}/triggers/{}", container.name_based_path(), trigger_name);
        Self {
            container: container.clone(),
            trigger_identifier: ResourceIdentifier::by_name(trigger_name),
            resource_link,
        }
    }

    /// Creates a new trigger reference by RID.
    pub fn from_rid(
        container: &ContainerReference,
        trigger_rid: impl Into<Cow<'static, str>>,
    ) -> Self {
        let trigger_rid = ResourceId::new(trigger_rid);
        let resource_link = format!("{}/triggers/{}", container.rid_based_path(), trigger_rid);
        Self {
            container: container.clone(),
            trigger_identifier: ResourceIdentifier::by_rid(trigger_rid),
            resource_link,
        }
    }

    /// Returns a reference to the parent container.
    pub fn container(&self) -> &ContainerReference {
        &self.container
    }

    /// Returns a reference to the parent account.
    pub fn account(&self) -> &AccountReference {
        self.container.account()
    }

    /// Returns the trigger name, if this is a name-based reference.
    pub fn name(&self) -> Option<&str> {
        self.trigger_identifier.name()
    }

    /// Returns the trigger RID, if this is a RID-based reference.
    pub fn rid(&self) -> Option<&str> {
        self.trigger_identifier.rid()
    }

    /// Returns `true` if this is a name-based reference.
    pub fn is_by_name(&self) -> bool {
        self.trigger_identifier.is_by_name()
    }

    /// Returns `true` if this is a RID-based reference.
    pub fn is_by_rid(&self) -> bool {
        self.trigger_identifier.is_by_rid()
    }

    /// Returns the pre-computed resource link for this trigger.
    pub fn resource_link(&self) -> &str {
        &self.resource_link
    }
}

// =============================================================================
// UdfReference (User-Defined Function)
// =============================================================================

/// A reference to a Cosmos DB user-defined function (UDF).
///
/// Contains the parent container and either the name or RID of the UDF.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct UdfReference {
    /// Reference to the parent container.
    container: ContainerReference,
    /// The UDF identifier.
    udf_identifier: ResourceIdentifier,
    /// Pre-computed resource link.
    resource_link: String,
}

impl UdfReference {
    /// Creates a new UDF reference by name.
    pub fn from_name(
        container: &ContainerReference,
        udf_name: impl Into<Cow<'static, str>>,
    ) -> Self {
        let udf_name = ResourceName::new(udf_name);
        let resource_link = format!("{}/udfs/{}", container.name_based_path(), udf_name);
        Self {
            container: container.clone(),
            udf_identifier: ResourceIdentifier::by_name(udf_name),
            resource_link,
        }
    }

    /// Creates a new UDF reference by RID.
    pub fn from_rid(container: &ContainerReference, udf_rid: impl Into<Cow<'static, str>>) -> Self {
        let udf_rid = ResourceId::new(udf_rid);
        let resource_link = format!("{}/udfs/{}", container.rid_based_path(), udf_rid);
        Self {
            container: container.clone(),
            udf_identifier: ResourceIdentifier::by_rid(udf_rid),
            resource_link,
        }
    }

    /// Returns a reference to the parent container.
    pub fn container(&self) -> &ContainerReference {
        &self.container
    }

    /// Returns a reference to the parent account.
    pub fn account(&self) -> &AccountReference {
        self.container.account()
    }

    /// Returns the UDF name, if this is a name-based reference.
    pub fn name(&self) -> Option<&str> {
        self.udf_identifier.name()
    }

    /// Returns the UDF RID, if this is a RID-based reference.
    pub fn rid(&self) -> Option<&str> {
        self.udf_identifier.rid()
    }

    /// Returns `true` if this is a name-based reference.
    pub fn is_by_name(&self) -> bool {
        self.udf_identifier.is_by_name()
    }

    /// Returns `true` if this is a RID-based reference.
    pub fn is_by_rid(&self) -> bool {
        self.udf_identifier.is_by_rid()
    }

    /// Returns the pre-computed resource link for this UDF.
    pub fn resource_link(&self) -> &str {
        &self.resource_link
    }
}

// =============================================================================
// PartitionKeyRangeReference
// =============================================================================

/// A reference to a Cosmos DB partition key range.
///
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PartitionKeyRangeReference {
    /// Reference to the parent container.
    container: ContainerReference,
    /// The partition key range identifier.
    range_id: ResourceName,
}

impl PartitionKeyRangeReference {
    /// Creates a new partition key range reference from a range ID.
    pub fn from_range_id(
        container: &ContainerReference,
        range_id: impl Into<Cow<'static, str>>,
    ) -> Self {
        let range_id = ResourceName::new(range_id);
        Self {
            container: container.clone(),
            range_id,
        }
    }

    /// Returns a reference to the parent container.
    pub fn container(&self) -> &ContainerReference {
        &self.container
    }

    /// Returns a reference to the parent account.
    pub fn account(&self) -> &AccountReference {
        self.container.account()
    }

    /// Returns the partition key range ID.
    pub fn range_id(&self) -> &str {
        self.range_id.as_str()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::{ContainerProperties, PartitionKeyDefinition};
    use url::Url;

    fn make_container_reference() -> ContainerReference {
        let account = AccountReference::with_master_key(
            Url::parse("https://example.documents.azure.com:443/").unwrap(),
            "test-key",
        );
        let partition_key: PartitionKeyDefinition =
            serde_json::from_str(r#"{"paths":["/tenantId"]}"#).unwrap();
        let container_properties = ContainerProperties {
            id: "my-container".into(),
            partition_key,
            system_properties: Default::default(),
        };

        ContainerReference::new(
            account,
            "my-db",
            "db-rid",
            "my-container",
            "container-rid",
            &container_properties,
        )
    }

    #[test]
    fn container_partition_key_definition_is_available() {
        let container = make_container_reference();
        let partition_key_definition = container.partition_key_definition();

        assert_eq!(partition_key_definition.paths().len(), 1);
        assert_eq!(partition_key_definition.paths()[0].as_ref(), "/tenantId");
    }
}