azure_data_cosmos_driver 0.5.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

//! Feed range type for the Cosmos DB driver.
//!
//! A [`FeedRange`] represents a contiguous range of the effective partition key (EPK) space.
//! It is used by the dataflow pipeline to target operations at one or more physical partitions.
//!
//! Feed ranges can also be serialized to base64-encoded JSON for cross-SDK storage and transport.

use azure_core::fmt::SafeDebug;
use base64::Engine;
use serde::{Deserialize, Serialize};
use std::{fmt, str::FromStr};

use crate::models::{effective_partition_key::EffectivePartitionKey, ItemReference, PartitionKey};
use crate::models::{partition_key_range::PartitionKeyRange, PartitionKeyDefinition};

/// A contiguous range of the effective partition key space.
///
/// Defined by `[min_inclusive, max_exclusive)` EPK boundaries. A `FeedRange` may
/// map to one or several physical partitions depending on the current partition
/// topology.
///
/// Use [`FeedRange::full()`] for the entire key space (`""..FF`).
#[derive(Clone, SafeDebug, PartialEq, Eq, Hash)]
#[safe(true)]
pub struct FeedRange(FeedRangeRepr);

#[derive(Clone, SafeDebug, PartialEq, Eq, Hash)]
#[safe(true)]
enum FeedRangeRepr {
    /// The range represents a logical partition key prefix.
    ///
    /// If the number of keys in [`FeedRangeRepr::LogicalPartition::partition_key`]
    /// is less than the number of levels in the container's partition key definition,
    /// the feed range represents all logical partitions that share that prefix.
    /// Otherwise, if the number of keys matches the number of levels, the feed range represents exactly one logical partition.
    ///
    /// This variant exists to preserve the logical partition key semantics for feed ranges that target a single logical partition or prefix, which is important for certain operations.
    LogicalPartition {
        partition_key: PartitionKey,
        effective_partition_key: EffectivePartitionKey,
    },

    /// The range is defined by explicit EPK bounds.
    Range {
        min_inclusive: EffectivePartitionKey,
        max_exclusive: EffectivePartitionKey,
    },
}

#[derive(Serialize, Deserialize)]
struct FeedRangeJson {
    #[serde(rename = "Range")]
    range: RangeJson,
}

#[derive(Serialize, Deserialize)]
struct RangeJson {
    min: String,
    max: String,
    #[serde(rename = "isMinInclusive")]
    is_min_inclusive: bool,
    #[serde(rename = "isMaxInclusive")]
    is_max_inclusive: bool,
}

impl FeedRange {
    /// Creates a feed range from explicit EPK bounds.
    pub fn new(
        min_inclusive: EffectivePartitionKey,
        max_exclusive: EffectivePartitionKey,
    ) -> crate::error::Result<Self> {
        if min_inclusive > max_exclusive {
            return Err(crate::error::CosmosError::builder()
                .with_status(crate::error::CosmosStatus::new(
                    azure_core::http::StatusCode::BadRequest,
                ))
                .with_message(
                    "feed range min_inclusive must be less than or equal to max_exclusive",
                )
                .build());
        }

        Ok(Self(FeedRangeRepr::Range {
            min_inclusive,
            max_exclusive,
        }))
    }

    /// Creates a feed range covering the entire partition key space (`""..FF`).
    pub fn full() -> Self {
        Self(FeedRangeRepr::Range {
            min_inclusive: EffectivePartitionKey::MIN.clone(),
            max_exclusive: EffectivePartitionKey::MAX.clone(),
        })
    }

    /// Creates a feed range for the logical partition key of the given item.
    pub(crate) fn for_item(item: &ItemReference) -> Self {
        Self::for_partition(
            item.partition_key().clone(),
            item.container().partition_key_definition(),
        )
    }

    /// Creates a feed range for the given logical partition key or prefix.
    ///
    /// Because the version of the partition hashing scheme must be known to compute the effective partition key,
    /// the caller must provide a reference to the partition key definition.
    pub fn for_partition(partition_key: PartitionKey, definition: &PartitionKeyDefinition) -> Self {
        let effective_partition_key = EffectivePartitionKey::compute(
            partition_key.values(),
            definition.kind,
            definition.version,
        );
        Self(FeedRangeRepr::LogicalPartition {
            partition_key,
            effective_partition_key,
        })
    }

    /// Returns the logical partition key if this feed range represents a single logical partition or prefix.
    ///
    /// It is the caller's responsibility to determine whether the returned partition key represents a full logical partition (i.e. has values for all levels of the hierarchy)
    /// or a prefix that covers multiple logical partitions (i.e. has values for only a subset of the levels).
    pub(crate) fn partition_key(&self) -> Option<&PartitionKey> {
        match &self.0 {
            FeedRangeRepr::LogicalPartition { partition_key, .. } => Some(partition_key),
            FeedRangeRepr::Range { .. } => None,
        }
    }

    /// Returns `true` if this feed range represents a single logical partition (or
    /// a hierarchical-partition-key prefix), as opposed to an explicit `[min, max)`
    /// EPK range.
    ///
    /// Logical-partition feed ranges have implicit single-partition targeting semantics
    /// that are lost when combined with arbitrary EPK ranges, so callers that wish to
    /// merge feed ranges (for example, session-token coalescing) typically exclude this
    /// variant before doing so.
    pub fn is_logical_partition(&self) -> bool {
        matches!(self.0, FeedRangeRepr::LogicalPartition { .. })
    }

    /// Returns the inclusive lower bound of this range.
    pub fn min_inclusive(&self) -> &EffectivePartitionKey {
        match &self.0 {
            FeedRangeRepr::LogicalPartition {
                effective_partition_key,
                ..
            } => effective_partition_key,
            FeedRangeRepr::Range { min_inclusive, .. } => min_inclusive,
        }
    }

    /// Returns the exclusive upper bound of this range.
    ///
    /// NOTE: The [`min_inclusive`](FeedRange::min_inclusive) value overrides this limit. Thus, a range with
    /// `min_inclusive == max_exclusive` is valid and represents exactly one EPK value, not an empty range.
    pub fn max_exclusive(&self) -> &EffectivePartitionKey {
        match &self.0 {
            FeedRangeRepr::LogicalPartition {
                effective_partition_key,
                ..
            } => effective_partition_key,
            FeedRangeRepr::Range { max_exclusive, .. } => max_exclusive,
        }
    }

    /// Returns `true` if this feed range is entirely contained within `other`.
    pub fn is_subset_of(&self, other: &FeedRange) -> bool {
        other.min_inclusive() <= self.min_inclusive()
            && other.max_exclusive() >= self.max_exclusive()
    }

    /// Returns `true` if this feed range and `other` share any portion of the EPK space.
    ///
    /// Two feed ranges overlap when one starts before the other ends and vice versa.
    pub fn overlaps(&self, other: &FeedRange) -> bool {
        self.min_inclusive() < other.max_exclusive() && other.min_inclusive() < self.max_exclusive()
    }

    fn to_json(&self) -> FeedRangeJson {
        FeedRangeJson {
            range: RangeJson {
                min: self.min_inclusive().as_str().to_owned(),
                max: self.max_exclusive().as_str().to_owned(),
                is_min_inclusive: true,
                is_max_inclusive: false,
            },
        }
    }

    fn from_json(json: FeedRangeJson) -> crate::error::Result<Self> {
        if !json.range.is_min_inclusive || json.range.is_max_inclusive {
            return Err(crate::error::CosmosError::builder().with_status(crate::error::CosmosStatus::new(azure_core::http::StatusCode::BadRequest)).with_message("feed range must have [min, max) semantics (isMinInclusive=true, isMaxInclusive=false)").build());
        }

        let min = EffectivePartitionKey::from(json.range.min);
        let max = EffectivePartitionKey::from(json.range.max);

        if min > max {
            return Err(crate::error::CosmosError::builder()
                .with_status(crate::error::CosmosStatus::new(
                    azure_core::http::StatusCode::BadRequest,
                ))
                .with_message("feed range min must be less than or equal to max")
                .build());
        }

        Ok(Self(FeedRangeRepr::Range {
            min_inclusive: min,
            max_exclusive: max,
        }))
    }
}

impl TryFrom<&PartitionKeyRange> for FeedRange {
    type Error = crate::error::CosmosError;

    /// Creates a `FeedRange` from a driver `PartitionKeyRange`.
    ///
    /// Partition key ranges from the service always use `[min, max)` semantics
    /// (min inclusive, max exclusive). Returns an error if the range is inverted.
    fn try_from(pkr: &PartitionKeyRange) -> Result<Self, Self::Error> {
        if pkr.min_inclusive > pkr.max_exclusive {
            return Err(crate::error::CosmosError::builder()
                .with_status(crate::error::CosmosStatus::new(
                    azure_core::http::StatusCode::BadRequest,
                ))
                .with_message("partition key range min_inclusive must be <= max_exclusive")
                .build());
        }

        Ok(Self(FeedRangeRepr::Range {
            min_inclusive: EffectivePartitionKey::from(pkr.min_inclusive.as_str()),
            max_exclusive: EffectivePartitionKey::from(pkr.max_exclusive.as_str()),
        }))
    }
}

impl fmt::Display for FeedRange {
    /// Formats this feed range as a base64-encoded JSON string.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let json_str = serde_json::to_string(&self.to_json()).map_err(|_| fmt::Error)?;
        let encoded = base64::engine::general_purpose::STANDARD.encode(json_str.as_bytes());
        f.write_str(&encoded)
    }
}

impl FromStr for FeedRange {
    type Err = crate::error::CosmosError;

    /// Parses a feed range from a base64-encoded JSON string.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let decoded_bytes = base64::engine::general_purpose::STANDARD
            .decode(s)
            .map_err(|e| {
                crate::error::CosmosError::builder()
                    .with_status(crate::error::CosmosStatus::new(
                        azure_core::http::StatusCode::BadRequest,
                    ))
                    .with_message("feed range is not valid base64")
                    .with_source(e)
                    .build()
            })?;

        let json: FeedRangeJson = serde_json::from_slice(&decoded_bytes).map_err(|e| {
            crate::error::CosmosError::builder()
                .with_status(crate::error::CosmosStatus::SERIALIZATION_RESPONSE_BODY_INVALID)
                .with_message("feed range JSON is invalid")
                .with_source(e)
                .build()
        })?;

        Self::from_json(json)
    }
}

impl Serialize for FeedRange {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.to_json().serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for FeedRange {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let json = FeedRangeJson::deserialize(deserializer)?;
        Self::from_json(json).map_err(|e| serde::de::Error::custom(e.to_string()))
    }
}

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

    #[test]
    fn full_range() {
        let full = FeedRange::full();
        assert_eq!(full.min_inclusive().as_str(), "");
        assert_eq!(full.max_exclusive().as_str(), "FF");
    }

    #[test]
    fn is_subset_of_full() {
        let full = FeedRange::full();
        let sub = FeedRange::new(
            EffectivePartitionKey::from("00"),
            EffectivePartitionKey::from("80"),
        )
        .unwrap();
        assert!(sub.is_subset_of(&full));
        assert!(!full.is_subset_of(&sub));
    }

    #[test]
    fn is_subset_of_self() {
        let range = FeedRange::new(
            EffectivePartitionKey::from("20"),
            EffectivePartitionKey::from("80"),
        )
        .unwrap();
        assert!(range.is_subset_of(&range));
    }

    #[test]
    fn overlaps_basic() {
        let a = FeedRange::new(
            EffectivePartitionKey::from("00"),
            EffectivePartitionKey::from("50"),
        )
        .unwrap();
        let b = FeedRange::new(
            EffectivePartitionKey::from("30"),
            EffectivePartitionKey::from("80"),
        )
        .unwrap();
        assert!(a.overlaps(&b));
        assert!(b.overlaps(&a));
    }

    #[test]
    fn overlaps_adjacent_no_overlap() {
        let a = FeedRange::new(
            EffectivePartitionKey::from("00"),
            EffectivePartitionKey::from("50"),
        )
        .unwrap();
        let b = FeedRange::new(
            EffectivePartitionKey::from("50"),
            EffectivePartitionKey::from("FF"),
        )
        .unwrap();
        assert!(!a.overlaps(&b));
        assert!(!b.overlaps(&a));
    }

    #[test]
    fn overlaps_disjoint() {
        let a = FeedRange::new(
            EffectivePartitionKey::from("00"),
            EffectivePartitionKey::from("30"),
        )
        .unwrap();
        let b = FeedRange::new(
            EffectivePartitionKey::from("50"),
            EffectivePartitionKey::from("FF"),
        )
        .unwrap();
        assert!(!a.overlaps(&b));
        assert!(!b.overlaps(&a));
    }

    #[test]
    fn display_round_trip() {
        let range = FeedRange::new(
            EffectivePartitionKey::from("3FFFFFFFFFFF"),
            EffectivePartitionKey::from("7FFFFFFFFFFF"),
        )
        .unwrap();

        let serialized = range.to_string();
        let parsed: FeedRange = serialized.parse().unwrap();

        assert_eq!(parsed, range);
    }

    #[test]
    fn serde_json_round_trip() {
        let range = FeedRange::new(
            EffectivePartitionKey::from(""),
            EffectivePartitionKey::from("FF"),
        )
        .unwrap();

        let json = serde_json::to_string(&range).unwrap();
        let parsed: FeedRange = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed, range);
    }

    #[test]
    fn try_from_partition_key_range() {
        let pkr = PartitionKeyRange::new("0".to_string(), "".to_string(), "FF".to_string());
        let feed_range = FeedRange::try_from(&pkr).unwrap();

        assert_eq!(feed_range.min_inclusive().as_str(), "");
        assert_eq!(feed_range.max_exclusive().as_str(), "FF");
    }

    #[test]
    fn from_str_invalid_base64() {
        assert!("not-valid-base64!!!".parse::<FeedRange>().is_err());
    }

    #[test]
    fn from_str_invalid_json() {
        let encoded = base64::engine::general_purpose::STANDARD.encode(b"not json");
        assert!(encoded.parse::<FeedRange>().is_err());
    }

    #[test]
    fn from_str_rejects_max_inclusive() {
        let json = r#"{"Range":{"min":"","max":"FF","isMinInclusive":true,"isMaxInclusive":true}}"#;
        let encoded = base64::engine::general_purpose::STANDARD.encode(json.as_bytes());
        assert!(encoded.parse::<FeedRange>().is_err());
    }

    #[test]
    fn serde_rejects_min_not_inclusive() {
        let json =
            r#"{"Range":{"min":"","max":"FF","isMinInclusive":false,"isMaxInclusive":false}}"#;
        assert!(serde_json::from_str::<FeedRange>(json).is_err());
    }

    #[test]
    fn from_str_rejects_inverted_range() {
        let json =
            r#"{"Range":{"min":"FF","max":"","isMinInclusive":true,"isMaxInclusive":false}}"#;
        let encoded = base64::engine::general_purpose::STANDARD.encode(json.as_bytes());
        assert!(encoded.parse::<FeedRange>().is_err());
    }

    #[test]
    fn serde_rejects_inverted_range() {
        let json =
            r#"{"Range":{"min":"FF","max":"","isMinInclusive":true,"isMaxInclusive":false}}"#;
        assert!(serde_json::from_str::<FeedRange>(json).is_err());
    }
}