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
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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

//! Partition key range cache for resolving effective partition keys to range IDs.
//!
//! Uses the driver's operation pipeline to fetch `/pkranges` from the service
//! and caches the resulting [`ContainerRoutingMap`] per container RID.

use std::sync::Arc;

use crate::models::{
    effective_partition_key::EffectivePartitionKey, partition_key_range::PkRangesResponse,
    ContainerReference, PartitionKey,
};

use super::{container_routing_map::ContainerRoutingMap, AsyncCache};

/// Maximum number of change feed iterations to prevent infinite loops.
///
/// In practice the loop completes in 1–2 iterations: the service returns all
/// partition key ranges in a single unbounded page, then 304 Not Modified on the
/// next call. This cap is a safety net, not an expected limit.
const MAX_FETCH_ITERATIONS: usize = 10;

/// Result of a single partition key range fetch from the service.
///
/// Callers construct this from the HTTP response: parsing the body for ranges,
/// extracting the `etag` header as `continuation`, and checking for HTTP 304 (Not Modified).
#[derive(Debug)]
pub(crate) struct PkRangeFetchResult {
    /// The partition key ranges returned in this page (empty if `not_modified` is true).
    pub ranges: Vec<crate::models::partition_key_range::PartitionKeyRange>,
    /// The continuation token (from the `etag` response header) for the next fetch.
    pub continuation: Option<String>,
    /// True if the server returned HTTP 304 Not Modified.
    pub not_modified: bool,
}

/// Cache that maps container RIDs to their partition key routing maps.
///
/// When a partition key range ID is needed (for partition-level failover),
/// this cache computes the effective partition key (EPK) from the partition key
/// values and looks up the corresponding range ID in the routing map.
///
/// The routing map is fetched lazily from the service the first time a
/// container is queried, then cached until invalidated.
#[derive(Debug)]
pub(crate) struct PartitionKeyRangeCache {
    /// Keyed by [`ContainerReference`], which provides the container RID
    /// needed for the `x-ms-expected-rid` header on pkrange changefeed calls.
    cache: AsyncCache<ContainerReference, ContainerRoutingMap>,
}

impl PartitionKeyRangeCache {
    /// Creates a new empty cache.
    pub fn new() -> Self {
        Self {
            cache: AsyncCache::new(),
        }
    }

    /// Resolves the partition key range ID for a given container and partition key.
    ///
    /// 1. Computes the effective partition key (EPK) from the partition key values.
    /// 2. Looks up the EPK in the cached routing map.
    /// 3. If no routing map is cached, fetches it from the service first.
    ///
    /// Returns `None` if the partition key is empty (cross-partition) or if
    /// the routing map cannot be resolved.
    pub async fn resolve_partition_key_range_id<F, Fut>(
        &self,
        container: &ContainerReference,
        partition_key: &PartitionKey,
        force_refresh: bool,
        fetch_pk_ranges: F,
    ) -> Option<String>
    where
        F: Fn(ContainerReference, Option<String>) -> Fut,
        Fut: std::future::Future<Output = Option<PkRangeFetchResult>>,
    {
        if partition_key.is_empty() {
            return None;
        }

        let pk_def = container.partition_key_definition();
        let kind = pk_def.kind();
        let version = pk_def.version();

        let epk = EffectivePartitionKey::compute(partition_key.values(), kind, version);

        let routing_map = self
            .try_lookup(container, force_refresh, fetch_pk_ranges)
            .await?;

        routing_map
            .get_range_by_effective_partition_key(&epk)
            .map(|r| r.id.clone())
    }

    /// Resolves partition key range IDs for a given container and partition key,
    /// supporting both full and prefix (hierarchical) partition keys.
    ///
    /// For full partition keys (component count == definition path count), returns
    /// a single range ID (same as [`resolve_partition_key_range_id`](Self::resolve_partition_key_range_id)).
    ///
    /// For prefix partition keys on MultiHash containers (fewer components than
    /// the definition), computes the prefix EPK range and returns all overlapping
    /// partition key range IDs, enabling fan-out queries across multiple physical
    /// partitions.
    ///
    /// Returns `None` if the partition key is empty or the routing map cannot be resolved.
    pub async fn resolve_partition_key_range_ids<F, Fut>(
        &self,
        container: &ContainerReference,
        partition_key: &PartitionKey,
        force_refresh: bool,
        fetch_pk_ranges: F,
    ) -> Option<Vec<String>>
    where
        F: Fn(ContainerReference, Option<String>) -> Fut,
        Fut: std::future::Future<Output = Option<PkRangeFetchResult>>,
    {
        if partition_key.is_empty() {
            return None;
        }

        let pk_def = container.partition_key_definition();
        let epk_range =
            EffectivePartitionKey::compute_range(partition_key.values(), pk_def).ok()?;

        if epk_range.start == epk_range.end {
            // Full key — point lookup
            let routing_map = self
                .try_lookup(container, force_refresh, fetch_pk_ranges)
                .await?;
            routing_map
                .get_range_by_effective_partition_key(&epk_range.start)
                .map(|r| vec![r.id.clone()])
        } else {
            // Prefix key — overlapping range lookup
            self.resolve_overlapping_ranges(
                container,
                &epk_range.start..&epk_range.end,
                force_refresh,
                fetch_pk_ranges,
            )
            .await
            .map(|ranges| ranges.into_iter().map(|r| r.id).collect())
        }
    }

    /// Resolves all partition key ranges that overlap with the given EPK range.
    ///
    /// Returns `None` if the routing map cannot be resolved.
    /// When `force_refresh` is true, the cached routing map is refreshed before lookup.
    pub async fn resolve_overlapping_ranges<F, Fut>(
        &self,
        container: &ContainerReference,
        epk_range: std::ops::Range<&EffectivePartitionKey>,
        force_refresh: bool,
        fetch_pk_ranges: F,
    ) -> Option<Vec<crate::models::partition_key_range::PartitionKeyRange>>
    where
        F: Fn(ContainerReference, Option<String>) -> Fut,
        Fut: std::future::Future<Output = Option<PkRangeFetchResult>>,
    {
        let routing_map = self
            .try_lookup(container, force_refresh, fetch_pk_ranges)
            .await?;

        Some(
            routing_map
                .get_overlapping_ranges(epk_range)
                .into_iter()
                .cloned()
                .collect(),
        )
    }

    /// Resolves the ID of the single partition key range that owns the given
    /// EPK range, or `None` when the range maps to zero or more than one
    /// physical partition (or the routing map cannot be resolved).
    ///
    /// Unlike [`resolve_overlapping_ranges`](Self::resolve_overlapping_ranges),
    /// this clones at most a single range ID rather than every overlapping
    /// range, making it the cheaper choice for callers that only need
    /// single-owner attribution (e.g. PPCB/PPAF first-attempt seeding).
    /// When `force_refresh` is true, the cached routing map is refreshed before lookup.
    pub async fn resolve_single_overlapping_range_id<F, Fut>(
        &self,
        container: &ContainerReference,
        epk_range: std::ops::Range<&EffectivePartitionKey>,
        force_refresh: bool,
        fetch_pk_ranges: F,
    ) -> Option<String>
    where
        F: Fn(ContainerReference, Option<String>) -> Fut,
        Fut: std::future::Future<Output = Option<PkRangeFetchResult>>,
    {
        let routing_map = self
            .try_lookup(container, force_refresh, fetch_pk_ranges)
            .await?;

        routing_map.single_overlapping_range_id(epk_range)
    }

    /// Resolves a partition key range by its ID.
    ///
    /// Returns `None` if the routing map cannot be resolved or the ID is not found.
    /// When `force_refresh` is true, the cached routing map is refreshed before lookup.
    pub async fn resolve_partition_key_range_by_id<F, Fut>(
        &self,
        container: &ContainerReference,
        partition_key_range_id: &str,
        force_refresh: bool,
        fetch_pk_ranges: F,
    ) -> Option<crate::models::partition_key_range::PartitionKeyRange>
    where
        F: Fn(ContainerReference, Option<String>) -> Fut,
        Fut: std::future::Future<Output = Option<PkRangeFetchResult>>,
    {
        let routing_map = self
            .try_lookup(container, force_refresh, fetch_pk_ranges)
            .await?;

        routing_map.range(partition_key_range_id).cloned()
    }

    /// Looks up or fetches the routing map for a container.
    ///
    /// When `force_refresh` is true, the previous routing map's change-feed
    /// continuation token is used for an incremental fetch. If the service
    /// returns 304 Not Modified, the existing map is returned as-is.
    /// Otherwise, the new ranges are merged via [`ContainerRoutingMap::try_combine`].
    ///
    /// Returns a routing map for the container. If the initial fetch fails or
    /// returns invalid ranges, the previously cached routing map is preserved
    /// when one exists; only when there is no previous map to fall back to is
    /// an empty routing map cached and returned.
    pub(crate) async fn try_lookup<F, Fut>(
        &self,
        container: &ContainerReference,
        force_refresh: bool,
        fetch_pk_ranges: F,
    ) -> Option<Arc<ContainerRoutingMap>>
    where
        F: Fn(ContainerReference, Option<String>) -> Fut,
        Fut: std::future::Future<Output = Option<PkRangeFetchResult>>,
    {
        let key = container.clone();

        if force_refresh {
            // Retrieve the existing routing map for incremental refresh.
            let previous = self.cache.get(&key).await;
            let prev_continuation = previous
                .as_ref()
                .and_then(|m| m.change_feed_next_if_none_match.clone());

            self.cache
                .get_or_refresh_with(
                    key.clone(),
                    |existing| {
                        // If there's no existing entry, we must fetch to populate the cache.
                        if existing.is_none() {
                            return true;
                        }
                        // Only refresh if the cached value hasn't been updated
                        // by another concurrent request since we last saw it.
                        existing.map(|m| &m.change_feed_next_if_none_match)
                            == Some(&prev_continuation)
                    },
                    || fetch_and_build_routing_map(key.clone(), previous, fetch_pk_ranges),
                )
                .await
        } else {
            Some(
                self.cache
                    .get_or_insert_with(key.clone(), || {
                        fetch_and_build_routing_map(key.clone(), None, fetch_pk_ranges)
                    })
                    .await,
            )
        }
    }

    /// Invalidates the cached routing map for a container.
    ///
    /// Call this when a partition split is detected (e.g., 410/1002 Gone response).
    pub async fn invalidate(&self, container: &ContainerReference) {
        self.cache.invalidate(container).await;
    }
}

/// Fetches partition key ranges via change-feed loop and builds a routing map.
///
/// This mirrors the SDK's routing-map-for-container pattern:
///
/// 1. Start from the previous map's continuation token (or `None` for fresh fetch).
/// 2. Loop calling `fetch_pk_ranges(container, continuation)` until the
///    service returns 304 Not Modified or `MAX_FETCH_ITERATIONS` is reached.
/// 3. Accumulate all fetched ranges.
/// 4. If a previous map exists, merge via [`ContainerRoutingMap::try_combine`];
///    otherwise create a fresh routing map.
async fn fetch_and_build_routing_map<F, Fut>(
    container: ContainerReference,
    previous_routing_map: Option<Arc<ContainerRoutingMap>>,
    fetch_pk_ranges: F,
) -> ContainerRoutingMap
where
    F: Fn(ContainerReference, Option<String>) -> Fut,
    Fut: std::future::Future<Output = Option<PkRangeFetchResult>>,
{
    let mut all_ranges = Vec::new();
    let mut continuation = previous_routing_map
        .as_ref()
        .and_then(|m| m.change_feed_next_if_none_match.clone());

    let mut received_not_modified = false;
    let mut iterations_completed = 0;
    for iteration in 0..MAX_FETCH_ITERATIONS {
        iterations_completed = iteration + 1;

        tracing::trace!(
            iteration,
            has_continuation = continuation.is_some(),
            "Fetching partition key ranges"
        );

        let result = match fetch_pk_ranges(container.clone(), continuation.clone()).await {
            Some(r) => r,
            None => {
                // Falling back to the previously cached map (when one exists)
                // mirrors the merge branch below and avoids regressing the
                // cache to empty on a single transient fetch failure.
                tracing::warn!(
                    "Failed to fetch partition key ranges from service (iteration {}); \
                     falling back to previous routing map if available",
                    iteration
                );
                return previous_routing_map
                    .map(|p| (*p).clone())
                    .unwrap_or_else(ContainerRoutingMap::empty);
            }
        };

        continuation = result.continuation;

        if result.not_modified {
            tracing::trace!(iteration, "Service returned 304 Not Modified");
            received_not_modified = true;
            break;
        }

        tracing::trace!(
            iteration,
            range_count = result.ranges.len(),
            "Received partition key ranges"
        );
        all_ranges.extend(result.ranges);
    }

    tracing::debug!(
        iterations = iterations_completed,
        total_ranges = all_ranges.len(),
        not_modified = received_not_modified,
        "Partition key range fetch loop completed"
    );

    if !received_not_modified && !all_ranges.is_empty() {
        tracing::warn!(
            "Partition key range fetch loop reached MAX_FETCH_ITERATIONS ({}) without \
             receiving Not Modified; routing map may be built from partial data",
            MAX_FETCH_ITERATIONS
        );
    }

    // Incremental refresh: merge new ranges into the previous routing map.
    if let Some(prev) = previous_routing_map {
        if all_ranges.is_empty() {
            // No changes since last fetch (304 on first iteration).
            return (*prev).clone();
        }
        return match prev.try_combine(all_ranges, continuation) {
            Ok(Some(map)) => map,
            Ok(None) => {
                tracing::warn!(
                    "Incremental routing map merge incomplete; falling back to previous map"
                );
                (*prev).clone()
            }
            Err(e) => {
                tracing::warn!(
                    "Incremental routing map merge failed: {}; falling back to previous map",
                    e
                );
                (*prev).clone()
            }
        };
    }

    // Full (non-incremental) creation.
    match ContainerRoutingMap::try_create(all_ranges, None, continuation) {
        Ok(Some(map)) => map,
        Ok(None) => {
            tracing::warn!("Partition key range fetch returned empty set");
            ContainerRoutingMap::empty()
        }
        Err(e) => {
            tracing::warn!("Partition key ranges invalid: {}", e);
            ContainerRoutingMap::empty()
        }
    }
}

/// Parses a pkranges REST response body into partition key ranges.
pub(crate) fn parse_pk_ranges_response(
    body: &[u8],
) -> Option<Vec<crate::models::partition_key_range::PartitionKeyRange>> {
    let response: PkRangesResponse = serde_json::from_slice(body).ok()?;
    Some(response.partition_key_ranges)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::partition_key_range::PartitionKeyRange as PkRange;

    fn test_ranges() -> Vec<PkRange> {
        vec![PkRange::new("0".into(), "", "FF")]
    }

    /// Simulates a single-page change feed fetch:
    /// - First call (no continuation): returns all ranges + continuation token.
    /// - Subsequent calls (with continuation): returns 304 Not Modified.
    async fn test_fetch(
        _container: ContainerReference,
        continuation: Option<String>,
    ) -> Option<PkRangeFetchResult> {
        if continuation.is_some() {
            Some(PkRangeFetchResult {
                ranges: vec![],
                continuation,
                not_modified: true,
            })
        } else {
            Some(PkRangeFetchResult {
                ranges: test_ranges(),
                continuation: Some("test-etag".to_string()),
                not_modified: false,
            })
        }
    }

    #[tokio::test]
    async fn resolve_returns_range_id() {
        let cache = PartitionKeyRangeCache::new();
        let account = crate::models::AccountReference::with_master_key(
            url::Url::parse("https://test.documents.azure.com:443/").unwrap(),
            "key",
        );
        let container_props = crate::models::ContainerProperties {
            id: "testcontainer".into(),
            partition_key: serde_json::from_str(r#"{"paths":["/pk"],"version":2}"#).unwrap(),
            system_properties: Default::default(),
        };
        let container = ContainerReference::new(
            account,
            "testdb",
            "testdb_rid",
            "testcontainer",
            "testcontainer_rid",
            &container_props,
        );
        let pk = PartitionKey::from("hello");

        let range_id = cache
            .resolve_partition_key_range_id(&container, &pk, false, test_fetch)
            .await;

        assert!(range_id.is_some());
        assert_eq!(range_id.unwrap(), "0");
    }

    #[tokio::test]
    async fn empty_pk_returns_none() {
        let cache = PartitionKeyRangeCache::new();
        let account = crate::models::AccountReference::with_master_key(
            url::Url::parse("https://test.documents.azure.com:443/").unwrap(),
            "key",
        );
        let container_props = crate::models::ContainerProperties {
            id: "testcontainer".into(),
            partition_key: serde_json::from_str(r#"{"paths":["/pk"],"version":2}"#).unwrap(),
            system_properties: Default::default(),
        };
        let container = ContainerReference::new(
            account,
            "testdb",
            "testdb_rid",
            "testcontainer",
            "testcontainer_rid",
            &container_props,
        );
        let pk = PartitionKey::EMPTY;

        let range_id = cache
            .resolve_partition_key_range_id(&container, &pk, false, test_fetch)
            .await;

        assert!(range_id.is_none());
    }

    #[tokio::test]
    async fn force_refresh_uses_incremental_merge() {
        let cache = PartitionKeyRangeCache::new();
        let account = crate::models::AccountReference::with_master_key(
            url::Url::parse("https://test.documents.azure.com:443/").unwrap(),
            "key",
        );
        let container_props = crate::models::ContainerProperties {
            id: "testcontainer".into(),
            partition_key: serde_json::from_str(r#"{"paths":["/pk"],"version":2}"#).unwrap(),
            system_properties: Default::default(),
        };
        let container = ContainerReference::new(
            account,
            "testdb",
            "testdb_rid",
            "testcontainer",
            "testcontainer_rid",
            &container_props,
        );
        let pk = PartitionKey::from("hello");

        // First call: populates the cache.
        let range_id = cache
            .resolve_partition_key_range_id(&container, &pk, false, test_fetch)
            .await;
        assert_eq!(range_id.as_deref(), Some("0"));

        // Second call with force_refresh: the test_fetch callback sees the continuation
        // from the cached map and returns 304 (not_modified), so the existing map is reused.
        let range_id = cache
            .resolve_partition_key_range_id(&container, &pk, true, test_fetch)
            .await;
        assert_eq!(range_id.as_deref(), Some("0"));
    }

    #[test]
    fn parse_pk_ranges_response_test() {
        let body = br#"{
            "PartitionKeyRanges": [
                {"id": "0", "_rid": "rid0", "minInclusive": "", "maxExclusive": "FF"}
            ]
        }"#;
        let ranges = parse_pk_ranges_response(body).unwrap();
        assert_eq!(ranges.len(), 1);
        assert_eq!(ranges[0].id, "0");
    }

    // =========================================================================
    // Tests for resolve_partition_key_range_ids (MultiHash / prefix HPK)
    // =========================================================================

    fn make_container(pk_json: &str) -> ContainerReference {
        let account = crate::models::AccountReference::with_master_key(
            url::Url::parse("https://test.documents.azure.com:443/").unwrap(),
            "key",
        );
        let container_props = crate::models::ContainerProperties {
            id: "testcontainer".into(),
            partition_key: serde_json::from_str(pk_json).unwrap(),
            system_properties: Default::default(),
        };
        ContainerReference::new(
            account,
            "testdb",
            "testdb_rid",
            "testcontainer",
            "testcontainer_rid",
            &container_props,
        )
    }

    /// A fetch function returning two partition key ranges split at the midpoint "80".
    /// Range "0": ["", "80"), Range "1": ["80", "FF")
    async fn two_range_fetch(
        _container: ContainerReference,
        continuation: Option<String>,
    ) -> Option<PkRangeFetchResult> {
        if continuation.is_some() {
            Some(PkRangeFetchResult {
                ranges: vec![],
                continuation,
                not_modified: true,
            })
        } else {
            Some(PkRangeFetchResult {
                ranges: vec![
                    PkRange::new("0".into(), "", "80"),
                    PkRange::new("1".into(), "80", "FF"),
                ],
                continuation: Some("test-etag".to_string()),
                not_modified: false,
            })
        }
    }

    #[tokio::test]
    async fn resolve_ids_empty_pk_returns_none() {
        let cache = PartitionKeyRangeCache::new();
        let container = make_container(
            r#"{"paths":["/tenantId","/userId","/sessionId"],"kind":"MultiHash","version":2}"#,
        );

        let result = cache
            .resolve_partition_key_range_ids(&container, &PartitionKey::EMPTY, false, test_fetch)
            .await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn resolve_ids_full_multihash_returns_single_id() {
        let cache = PartitionKeyRangeCache::new();
        let container =
            make_container(r#"{"paths":["/tenantId","/userId"],"kind":"MultiHash","version":2}"#);
        let pk = PartitionKey::from(("tenant1", "user1"));

        let result = cache
            .resolve_partition_key_range_ids(&container, &pk, false, test_fetch)
            .await;

        assert!(result.is_some());
        let ids = result.unwrap();
        assert_eq!(ids.len(), 1);
        assert_eq!(ids[0], "0"); // single range ["", "FF") contains everything
    }

    #[tokio::test]
    async fn resolve_ids_prefix_multihash_returns_multiple_ids() {
        let cache = PartitionKeyRangeCache::new();
        // 3-path MultiHash container
        let container = make_container(
            r#"{"paths":["/tenantId","/userId","/sessionId"],"kind":"MultiHash","version":2}"#,
        );
        // Prefix key: only 1 of 3 components → prefix EPK range spans multiple ranges
        let pk = PartitionKey::from("tenant1");

        let result = cache
            .resolve_partition_key_range_ids(&container, &pk, false, two_range_fetch)
            .await;

        assert!(result.is_some());
        let ids = result.unwrap();
        // The prefix EPK for "tenant1" is a 32-char hex string starting with a digit 0-3
        // (due to 0x3F mask). With ranges split at "80", the prefix range [epk, epk+"FF")
        // falls entirely within range "0" (["", "80")). So we expect 1 ID.
        // This validates the prefix path is exercised (via resolve_overlapping_ranges).
        assert_eq!(ids, vec!["0".to_string()]);
    }

    #[tokio::test]
    async fn resolve_ids_non_multihash_returns_single_id() {
        let cache = PartitionKeyRangeCache::new();
        // Single-hash container (non-MultiHash)
        let container = make_container(r#"{"paths":["/pk"],"version":2}"#);
        let pk = PartitionKey::from("hello");

        let result = cache
            .resolve_partition_key_range_ids(&container, &pk, false, test_fetch)
            .await;

        assert!(result.is_some());
        let ids = result.unwrap();
        assert_eq!(ids, vec!["0".to_string()]);
    }

    #[tokio::test]
    async fn resolve_ids_matches_single_resolve() {
        // Full MultiHash key via resolve_partition_key_range_ids should produce the
        // same result as resolve_partition_key_range_id.
        let cache = PartitionKeyRangeCache::new();
        let container =
            make_container(r#"{"paths":["/tenantId","/userId"],"kind":"MultiHash","version":2}"#);
        let pk = PartitionKey::from(("tenant1", "user1"));

        let single = cache
            .resolve_partition_key_range_id(&container, &pk, false, test_fetch)
            .await;
        let plural = cache
            .resolve_partition_key_range_ids(&container, &pk, false, test_fetch)
            .await;

        assert_eq!(single.as_deref(), Some("0"));
        assert_eq!(plural.as_deref(), Some(vec!["0".to_string()].as_slice()));
    }

    // =========================================================================
    // Tests for resolve_all_partition_key_ranges / resolve_partition_key_ranges_for_key
    // (scenarios matching CosmosDriver public methods)
    // =========================================================================

    #[tokio::test]
    async fn try_lookup_returns_all_ranges() {
        let cache = PartitionKeyRangeCache::new();
        let container = make_container(r#"{"paths":["/pk"],"version":2}"#);

        let routing_map = cache.try_lookup(&container, false, two_range_fetch).await;

        assert!(routing_map.is_some());
        let ranges = routing_map.unwrap().ranges().to_vec();
        assert_eq!(ranges.len(), 2);
        assert_eq!(ranges[0].id, "0");
        assert_eq!(ranges[1].id, "1");
    }

    #[tokio::test]
    async fn try_lookup_empty_routing_map_returns_empty_ranges() {
        let cache = PartitionKeyRangeCache::new();
        let container = make_container(r#"{"paths":["/pk"],"version":2}"#);

        /// Simulates a service failure: returns no ranges and no continuation.
        async fn empty_fetch(
            _container: ContainerReference,
            _continuation: Option<String>,
        ) -> Option<PkRangeFetchResult> {
            Some(PkRangeFetchResult {
                ranges: vec![],
                continuation: None,
                not_modified: false,
            })
        }

        let routing_map = cache.try_lookup(&container, false, empty_fetch).await;

        // Cache returns an empty routing map (not None) — the CosmosDriver public
        // methods check for empty ranges and convert to None.
        assert!(routing_map.is_some());
        assert!(routing_map.unwrap().ranges().is_empty());
    }

    #[tokio::test]
    async fn try_lookup_fetch_failure_returns_none() {
        let cache = PartitionKeyRangeCache::new();
        let container = make_container(r#"{"paths":["/pk"],"version":2}"#);

        /// Simulates a complete fetch failure (e.g., network error).
        async fn failing_fetch(
            _container: ContainerReference,
            _continuation: Option<String>,
        ) -> Option<PkRangeFetchResult> {
            None
        }

        let routing_map = cache.try_lookup(&container, false, failing_fetch).await;

        // Complete fetch failure returns None from try_lookup.
        assert!(routing_map.is_some()); // empty map is cached as fallback
    }

    #[tokio::test]
    async fn resolve_overlapping_ranges_full_key_returns_single_range() {
        let cache = PartitionKeyRangeCache::new();
        let container = make_container(r#"{"paths":["/pk"],"version":2}"#);
        let pk = PartitionKey::from("hello");

        let pk_def = container.partition_key_definition();
        let epk_range = EffectivePartitionKey::compute_range(pk.values(), pk_def).unwrap();

        // Full key: start == end, so this is a point lookup via get_range_by_effective_partition_key.
        assert_eq!(epk_range.start, epk_range.end);

        // Use try_lookup + manual point lookup (mirrors CosmosDriver::resolve_partition_key_ranges_for_key)
        let routing_map = cache
            .try_lookup(&container, false, test_fetch)
            .await
            .unwrap();
        let range = routing_map.get_range_by_effective_partition_key(&epk_range.start);

        assert!(range.is_some());
        assert_eq!(range.unwrap().id, "0");
    }

    #[tokio::test]
    async fn resolve_overlapping_ranges_prefix_key_returns_multiple() {
        let cache = PartitionKeyRangeCache::new();
        // 3-path MultiHash container with two ranges split at "80"
        let container = make_container(
            r#"{"paths":["/tenantId","/userId","/sessionId"],"kind":"MultiHash","version":2}"#,
        );
        // Prefix key with only 2 of 3 components
        let pk = PartitionKey::from(("tenant1", "user1"));

        let pk_def = container.partition_key_definition();
        let epk_range = EffectivePartitionKey::compute_range(pk.values(), pk_def).unwrap();

        // Prefix key: start != end
        assert_ne!(epk_range.start, epk_range.end);

        let ranges = cache
            .resolve_overlapping_ranges(
                &container,
                &epk_range.start..&epk_range.end,
                false,
                two_range_fetch,
            )
            .await;

        assert!(ranges.is_some());
        // Prefix EPK range may overlap one or both physical ranges depending on hash
        let ranges = ranges.unwrap();
        assert!(!ranges.is_empty());
        // All returned ranges should have valid IDs
        for r in &ranges {
            assert!(!r.id.is_empty());
        }
    }

    #[tokio::test]
    async fn resolve_overlapping_ranges_empty_map_returns_empty_vec() {
        let cache = PartitionKeyRangeCache::new();
        let container = make_container(
            r#"{"paths":["/tenantId","/userId","/sessionId"],"kind":"MultiHash","version":2}"#,
        );
        let pk = PartitionKey::from("tenant1");

        let pk_def = container.partition_key_definition();
        let epk_range = EffectivePartitionKey::compute_range(pk.values(), pk_def).unwrap();

        /// Returns an empty routing map.
        async fn empty_fetch(
            _container: ContainerReference,
            _continuation: Option<String>,
        ) -> Option<PkRangeFetchResult> {
            Some(PkRangeFetchResult {
                ranges: vec![],
                continuation: None,
                not_modified: false,
            })
        }

        let ranges = cache
            .resolve_overlapping_ranges(
                &container,
                &epk_range.start..&epk_range.end,
                false,
                empty_fetch,
            )
            .await;

        // Empty routing map → resolve_overlapping_ranges returns Some(vec![])
        // (CosmosDriver public method normalizes this to None)
        assert!(ranges.is_some());
        assert!(ranges.unwrap().is_empty());
    }

    #[tokio::test]
    async fn force_refresh_repopulates_after_empty_cache() {
        use std::sync::{
            atomic::{AtomicUsize, Ordering},
            Arc,
        };

        let cache = PartitionKeyRangeCache::new();
        let container = make_container(r#"{"paths":["/pk"],"version":2}"#);

        let call_count = Arc::new(AtomicUsize::new(0));

        // First fetch: returns empty (simulates transient failure)
        let count = call_count.clone();
        let empty_fetch = move |_container: ContainerReference, _continuation: Option<String>| {
            let count = count.clone();
            async move {
                count.fetch_add(1, Ordering::SeqCst);
                Some(PkRangeFetchResult {
                    ranges: vec![],
                    continuation: None,
                    not_modified: false,
                })
            }
        };

        // First lookup: gets empty routing map
        let map1 = cache
            .try_lookup(&container, false, empty_fetch)
            .await
            .unwrap();
        assert!(map1.ranges().is_empty());

        // Force refresh with a fetch that returns valid ranges
        let recovering_fetch = |_container: ContainerReference, _continuation: Option<String>| async {
            Some(PkRangeFetchResult {
                ranges: vec![PkRange::new("0".into(), "", "FF")],
                continuation: Some("etag-2".to_string()),
                not_modified: false,
            })
        };

        let map2 = cache
            .try_lookup(&container, true, recovering_fetch)
            .await
            .unwrap();
        assert_eq!(map2.ranges().len(), 1);
        assert_eq!(map2.ranges()[0].id, "0");
    }

    #[tokio::test]
    async fn force_refresh_with_transient_fetch_failure_preserves_previous_map() {
        // A force-refresh that hits a transient fetch failure on iteration 0
        // must NOT regress the cached routing map to empty: the cached map is
        // the only thing keeping routing decisions working until the next
        // successful refresh.
        use std::sync::{
            atomic::{AtomicUsize, Ordering},
            Arc,
        };

        let cache = PartitionKeyRangeCache::new();
        let container = make_container(r#"{"paths":["/pk"],"version":2}"#);

        // Seed the cache with two ranges via a successful initial lookup.
        let seeded = cache
            .try_lookup(&container, false, two_range_fetch)
            .await
            .unwrap();
        assert_eq!(seeded.ranges().len(), 2);

        // Force-refresh with a fetcher that fails on the first call.
        let call_count = Arc::new(AtomicUsize::new(0));
        let count = call_count.clone();
        let failing_fetch = move |_container: ContainerReference, _continuation: Option<String>| {
            let count = count.clone();
            async move {
                count.fetch_add(1, Ordering::SeqCst);
                None
            }
        };

        let refreshed = cache
            .try_lookup(&container, true, failing_fetch)
            .await
            .unwrap();

        assert_eq!(
            call_count.load(Ordering::SeqCst),
            1,
            "failing fetcher should be invoked exactly once before fallback"
        );
        assert_eq!(
            refreshed.ranges().len(),
            2,
            "force-refresh on transient failure must preserve the previously cached map"
        );
        assert_eq!(refreshed.ranges()[0].id, "0");
        assert_eq!(refreshed.ranges()[1].id, "1");

        // The cached entry observed by a subsequent non-refresh lookup must
        // also be the preserved map, not the empty placeholder that would
        // result from the previous bug.
        let after = cache
            .try_lookup(&container, false, |_, _| async {
                panic!("non-refresh lookup must hit cache, not call fetcher")
            })
            .await
            .unwrap();
        assert_eq!(after.ranges().len(), 2);
    }
}