cedarling 0.0.42

The Cedarling: a high-performance local authorization service powered by the Rust Cedar Engine.
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
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
// This software is available under the Apache-2.0 license.
// See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
//
// Copyright (c) 2024, Gluu, Inc.

use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::Duration as StdDuration;

use crate::sparkv::{Config as SparKVConfig, Error as SparKVError, HashMapSparKV};
use chrono::{Duration as ChronoDuration, Utc};
use serde_json::Value;

use crate::authz::metrics::MetricsCollector;

use super::config::{ConfigValidationError, DataStoreConfig};
use super::entry::DataEntry;
use super::error::DataError;

const RWLOCK_EXPECT_MESSAGE: &str = "DataStore storage lock should not be poisoned";

/// Effectively infinite TTL in seconds (approximately 10 years).
/// This is used when `None` is specified for TTL to mean "no automatic expiration".
/// We use 10 years instead of `i64::MAX` to avoid chrono Duration overflow issues.
const INFINITE_TTL_SECS: i64 = 315_360_000; // 10 years in seconds

/// Maximum safe seconds value for duration conversion.
/// `i64::MAX / 1000` ensures we can safely add nanoseconds without overflow.
/// This is approximately 9.2 quadrillion seconds (~292 billion years).
const MAX_SAFE_DURATION_SECS: u64 = (i64::MAX / 1000) as u64;

/// Thread-safe key-value data store with TTL support and capacity management.
///
/// Built on top of `SparKV` in-memory store for consistency with other Cedarling components.
/// Provides automatic expiration, capacity limits, and thread-safe concurrent access.
///
/// ## TTL Semantics
///
/// - `config.default_ttl = None` means entries without explicit TTL will effectively never expire (10 years)
/// - `config.max_ttl = None` means no upper limit on TTL values (10 years max)
/// - When both `ttl` parameter and `config.default_ttl` are `None`, entries use the infinite TTL
pub(crate) struct DataStore {
    storage: RwLock<HashMapSparKV<DataEntry>>,
    config: DataStoreConfig,
    metrics: Arc<MetricsCollector>,
}

impl DataStore {
    /// Create a new `DataStore` with the given configuration.
    ///
    /// ## TTL Defaults
    ///
    /// - If `config.max_ttl` is `None`, uses 10 years (effectively infinite)
    /// - If `config.default_ttl` is `None`, uses 10 years (effectively infinite)
    ///
    /// Returns `ConfigValidationError` if the configuration is invalid.
    pub(crate) fn new(
        config: DataStoreConfig,
        metrics: Arc<MetricsCollector>,
    ) -> Result<Self, ConfigValidationError> {
        // Validate configuration before creating the store
        config.validate()?;

        let sparkv_config = SparKVConfig {
            max_items: config.max_entries,
            max_item_size: config.max_entry_size,
            max_ttl: config.max_ttl.map_or_else(
                || ChronoDuration::seconds(INFINITE_TTL_SECS),
                std_duration_to_chrono_duration,
            ),
            default_ttl: config.default_ttl.map_or_else(
                || ChronoDuration::seconds(INFINITE_TTL_SECS),
                std_duration_to_chrono_duration,
            ),
            auto_clear_expired: true,
            earliest_expiration_eviction: false,
        };

        // Calculate size based on the serialized DataEntry
        let size_calculator: Option<fn(&DataEntry) -> usize> =
            Some(|entry| serde_json::to_string(entry).map_or(0, |s| s.len()));

        Ok(Self {
            storage: RwLock::new(HashMapSparKV::with_config_and_sizer(
                sparkv_config,
                size_calculator,
            )),
            config,
            metrics,
        })
    }

    /// Push a value into the store with an optional TTL.
    ///
    /// If the key already exists, the value will be replaced.
    /// If TTL is not provided, the default TTL from config will be used.
    /// If both are `None`, uses infinite TTL (10 years).
    ///
    /// # Errors
    ///
    /// Returns `DataError` if:
    /// - Key is empty
    /// - Value serialization fails
    /// - Value size exceeds `max_entry_size`
    /// - Storage capacity is exceeded
    /// - TTL exceeds `max_ttl`
    pub(crate) fn push(
        &self,
        key: &str,
        value: Value,
        ttl: Option<StdDuration>,
    ) -> Result<(), DataError> {
        // Validate key
        if key.is_empty() {
            let err = DataError::InvalidKey;
            self.metrics.record_error(&err);
            return Err(err);
        }

        // Validate explicit TTL against max_ttl before calculating effective TTL
        if let Some(explicit_ttl) = ttl
            && let Some(max_ttl) = self.config.max_ttl
            && explicit_ttl > max_ttl
        {
            let err = DataError::TTLExceeded {
                requested: explicit_ttl,
                max: max_ttl,
            };
            self.metrics.record_error(&err);
            return Err(err);
        }

        // Calculate effective TTL using the helper function
        let effective_ttl_chrono =
            get_effective_ttl(ttl, self.config.default_ttl, self.config.max_ttl);

        // Convert back to StdDuration for DataEntry::new, preserving sub-second precision
        let effective_ttl_std = effective_ttl_chrono.to_std().unwrap_or({
            // Handle negative or out-of-range durations by clamping to zero
            StdDuration::ZERO
        });

        // Create DataEntry with metadata using effective TTL
        let entry = DataEntry::new(key.to_string(), value, Some(effective_ttl_std));

        // Check entry size before storing (including metadata)
        let entry_size = serde_json::to_string(&entry)
            .map_err(|e| {
                let err = DataError::from(e);
                self.metrics.record_error(&err);
                err
            })?
            .len();

        if self.config.max_entry_size > 0 && entry_size > self.config.max_entry_size {
            let err = DataError::ValueTooLarge {
                size: entry_size,
                max: self.config.max_entry_size,
            };
            self.metrics.record_error(&err);
            return Err(err);
        }

        let chrono_ttl = effective_ttl_chrono;

        let mut storage = self.storage.write().expect(RWLOCK_EXPECT_MESSAGE);

        // Use empty index keys since we don't need indexing for data store
        storage
            .set_with_ttl(key, entry, chrono_ttl, &[])
            .map_err(|e| {
                let err = match e {
                    SparKVError::CapacityExceeded => DataError::StorageLimitExceeded {
                        max: self.config.max_entries,
                    },
                    SparKVError::ItemSizeExceeded => DataError::ValueTooLarge {
                        size: entry_size,
                        max: self.config.max_entry_size,
                    },
                    SparKVError::TTLTooLong => DataError::TTLExceeded {
                        requested: ttl.unwrap_or_default(),
                        max: self
                            .config
                            .max_ttl
                            .unwrap_or(StdDuration::from_secs(INFINITE_TTL_SECS as u64)),
                    },
                };
                self.metrics.record_error(&err);
                err
            })?;

        self.metrics.record_data_push();
        Ok(())
    }

    /// Get a value from the store by key.
    ///
    /// Returns `None` if the key doesn't exist or the entry has expired.
    /// If metrics are enabled, increments the access count for the entry.
    pub(crate) fn get(&self, key: &str) -> Option<Value> {
        self.get_entry(key).map(|entry| entry.value)
    }

    /// Get a data entry with full metadata by key.
    ///
    /// Returns `None` if the key doesn't exist or the entry has expired.
    /// If metrics are enabled, increments the access count for the entry.
    /// When metrics are enabled, uses write lock up-front to avoid TOCTOU issues.
    pub(crate) fn get_entry(&self, key: &str) -> Option<DataEntry> {
        if self.config.enable_metrics {
            // Acquire write lock up-front when metrics are enabled to avoid TOCTOU
            let mut storage = self.storage.write().expect(RWLOCK_EXPECT_MESSAGE);
            let mut entry = storage.get(key)?.clone();

            // Check if entry has expired
            let now = chrono::Utc::now();
            if let Some(expires_at) = entry.expires_at
                && now > expires_at
            {
                storage.pop(key);
                return None;
            }

            entry.increment_access();

            // Calculate remaining TTL to preserve expiration
            let remaining_ttl = if let Some(expires_at) = entry.expires_at {
                expires_at
                    .signed_duration_since(now)
                    .to_std()
                    .ok()
                    .map_or_else(
                        || {
                            // Entry has expired (negative duration), should not happen here
                            // but handle gracefully by returning zero TTL
                            std_duration_to_chrono_duration(StdDuration::ZERO)
                        },
                        std_duration_to_chrono_duration,
                    )
            } else {
                // No expiration, use effective TTL
                get_effective_ttl(None, self.config.default_ttl, self.config.max_ttl)
            };

            let _ = storage.set_with_ttl(key, entry.clone(), remaining_ttl, &[]);
            self.metrics.record_data_get();
            Some(entry)
        } else {
            // Fast path: use read lock when metrics are disabled
            let storage = self.storage.read().expect(RWLOCK_EXPECT_MESSAGE);
            let entry = storage.get(key)?.clone();

            // Check if entry has expired
            if let Some(expires_at) = entry.expires_at
                && chrono::Utc::now() > expires_at
            {
                return None;
            }

            self.metrics.record_data_get();
            Some(entry)
        }
    }

    /// Remove a value from the store by key.
    ///
    /// Returns `true` if the key existed and was removed, `false` otherwise.
    /// Uses write lock for exclusive access.
    pub(crate) fn remove(&self, key: &str) -> bool {
        let mut storage = self.storage.write().expect(RWLOCK_EXPECT_MESSAGE);
        let removed = storage.pop(key).is_some();
        if removed {
            self.metrics.record_data_remove();
        }
        removed
    }

    /// Clear all entries from the store.
    /// Uses write lock for exclusive access.
    pub(crate) fn clear(&self) {
        let mut storage = self.storage.write().expect(RWLOCK_EXPECT_MESSAGE);
        storage.clear();
    }

    /// Get the number of entries currently in the store.
    /// Uses read lock for concurrent access.
    /// Filters out expired entries to match `get_all()/list_entries()` behavior.
    pub(crate) fn count(&self) -> usize {
        let storage = self.storage.read().expect(RWLOCK_EXPECT_MESSAGE);
        let now = chrono::Utc::now();
        storage
            .iter()
            .filter(|(_, entry)| !entry.is_expired(now))
            .count()
    }

    /// Get all active (non-expired) entries as a `HashMap`.
    ///
    /// This is used for context injection during authorization.
    /// Returns only the values, not the metadata.
    /// Filters out expired entries to prevent leaking expired items into authorization contexts.
    pub(crate) fn get_all(&self) -> HashMap<String, Value> {
        let storage = self.storage.read().expect(RWLOCK_EXPECT_MESSAGE);

        // Early return if storage is empty
        if storage.is_empty() {
            return HashMap::new();
        }

        let now = chrono::Utc::now();
        // Collect with size hint to reduce reallocations
        // Note: We can't use with_capacity on the iterator, but collect() will
        // use the size_hint from the iterator chain
        storage
            .iter()
            .filter(|(_, entry)| !entry.is_expired(now))
            .map(|(k, entry)| (k.clone(), entry.value.clone()))
            .collect()
    }

    /// List all entries with their full metadata, excluding expired entries.
    pub(crate) fn list_entries(&self) -> Vec<DataEntry> {
        let storage = self.storage.read().expect(RWLOCK_EXPECT_MESSAGE);

        // Early return if storage is empty
        if storage.is_empty() {
            return Vec::new();
        }

        let now = Utc::now();
        // Use iterator chain - compiler optimizes this well
        storage
            .iter()
            .filter(|(_, entry)| !entry.is_expired(now))
            .map(|(_, entry)| entry.clone())
            .collect()
    }

    /// Get the configuration for this store.
    pub(crate) fn config(&self) -> &DataStoreConfig {
        &self.config
    }

    /// Calculate the total size of all entries in bytes.
    ///
    /// Size is computed based on JSON serialization of each entry.
    /// Filters out expired entries to match `get_all()/list_entries()` behavior.
    pub(crate) fn total_size(&self) -> usize {
        let storage = self.storage.read().expect(RWLOCK_EXPECT_MESSAGE);
        let now = chrono::Utc::now();
        storage
            .iter()
            .filter(|(_, entry)| !entry.is_expired(now))
            .map(|(_, entry)| serde_json::to_string(entry).map_or(0, |s| s.len()))
            .sum()
    }
}

/// Convert `std::time::Duration` to `chrono::Duration`.
///
/// Uses saturating conversion to prevent overflow for very large durations.
/// Durations exceeding `i64::MAX` seconds will be capped at a safe maximum.
pub(super) fn std_duration_to_chrono_duration(d: StdDuration) -> ChronoDuration {
    let secs = d.as_secs();
    let nanos = d.subsec_nanos();

    // Saturating conversion: cap at MAX_SAFE_DURATION_SECS to prevent chrono panics.
    // After capping, the value is guaranteed to fit in i64.
    let secs_capped = secs.min(MAX_SAFE_DURATION_SECS);

    // SAFETY: secs_capped <= MAX_SAFE_DURATION_SECS < i64::MAX, so this cast is safe
    #[allow(clippy::cast_possible_wrap)]
    let secs_i64 = secs_capped as i64;

    ChronoDuration::seconds(secs_i64) + ChronoDuration::nanoseconds(i64::from(nanos))
}

/// Get the effective TTL to use, respecting `max_ttl` constraints.
///
/// # TTL Resolution Logic
///
/// 1. If `ttl` is provided explicitly, use it (subject to `max_ttl` cap)
/// 2. Otherwise, use `default_ttl` from config (subject to `max_ttl` cap)
/// 3. If both are None, use effectively infinite duration (10 years)
/// 4. Always respect `max_ttl` if set, capping the result
///
/// This ensures that the effective TTL always respects `max_ttl` constraints,
/// even when using default or infinite TTLs.
fn get_effective_ttl(
    ttl: Option<StdDuration>,
    default_ttl: Option<StdDuration>,
    max_ttl: Option<StdDuration>,
) -> ChronoDuration {
    // Determine the requested TTL
    let requested_ttl = ttl.or(default_ttl);

    // If no TTL is specified, use effectively infinite duration (10 years)
    let effective = requested_ttl.unwrap_or(StdDuration::from_secs(INFINITE_TTL_SECS as u64));

    // Respect max_ttl if set, capping the result
    let capped = if let Some(max) = max_ttl {
        effective.min(max)
    } else {
        effective
    };

    std_duration_to_chrono_duration(capped)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    #[cfg(not(target_arch = "wasm32"))]
    use std::thread;
    use std::time::Duration as StdDuration;
    use test_utils::assert_eq;

    fn create_test_store() -> DataStore {
        let metrics = Arc::new(MetricsCollector::new(0));
        DataStore::new(DataStoreConfig::default(), metrics).expect("should create store")
    }

    #[test]
    fn test_push_and_get() {
        let store = create_test_store();

        // Push a simple value
        store
            .push("key1", json!("value1"), None)
            .expect("failed to push simple value");
        assert_eq!(store.get("key1"), Some(json!("value1")));

        // Push a complex value
        let complex_value = json!({
            "name": "test",
            "count": 42,
            "active": true
        });
        store
            .push("key2", complex_value.clone(), None)
            .expect("failed to push complex value");
        assert_eq!(store.get("key2"), Some(complex_value));
    }

    #[test]
    fn test_push_replace_existing_key() {
        let store = create_test_store();

        store
            .push("key1", json!("value1"), None)
            .expect("failed to push initial value");
        assert_eq!(store.get("key1"), Some(json!("value1")));

        // Replace with new value
        store
            .push("key1", json!("value2"), None)
            .expect("failed to replace value");
        assert_eq!(store.get("key1"), Some(json!("value2")));
    }

    #[test]
    fn test_push_empty_key() {
        let store = create_test_store();

        let result = store.push("", json!("value"), None);
        assert!(
            matches!(result, Err(DataError::InvalidKey)),
            "push with empty key should return DataError::InvalidKey"
        );
        assert!(matches!(result, Err(DataError::InvalidKey)));
    }

    #[test]
    fn test_get_nonexistent_key() {
        let store = create_test_store();

        assert_eq!(store.get("nonexistent"), None);
    }

    #[test]
    fn test_remove() {
        let store = create_test_store();

        store
            .push("key1", json!("value1"), None)
            .expect("failed to push value for remove test");
        assert_eq!(store.get("key1"), Some(json!("value1")));

        // Remove existing key
        assert!(store.remove("key1"));
        assert_eq!(store.get("key1"), None);

        // Remove non-existent key
        assert!(!store.remove("nonexistent"));
    }

    #[test]
    fn test_clear() {
        let store = create_test_store();

        store
            .push("key1", json!("value1"), None)
            .expect("failed to push key1 for clear test");
        store
            .push("key2", json!("value2"), None)
            .expect("failed to push key2 for clear test");
        assert_eq!(store.count(), 2);

        store.clear();
        assert_eq!(store.count(), 0);
        assert_eq!(store.get("key1"), None);
        assert_eq!(store.get("key2"), None);
    }

    #[test]
    fn test_count() {
        let store = create_test_store();

        assert_eq!(store.count(), 0);

        store
            .push("key1", json!("value1"), None)
            .expect("failed to push key1 for count test");
        assert_eq!(store.count(), 1);

        store
            .push("key2", json!("value2"), None)
            .expect("failed to push key2 for count test");
        assert_eq!(store.count(), 2);

        store.remove("key1");
        assert_eq!(store.count(), 1);
    }

    #[test]
    fn test_get_all() {
        let store = create_test_store();

        store
            .push("key1", json!("value1"), None)
            .expect("failed to push key1 for get_all test");
        store
            .push("key2", json!("value2"), None)
            .expect("failed to push key2 for get_all test");

        let all = store.get_all();
        assert_eq!(all.len(), 2);
        assert_eq!(all.get("key1"), Some(&json!("value1")));
        assert_eq!(all.get("key2"), Some(&json!("value2")));
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn test_ttl_expiration() {
        let store = create_test_store();

        // Push with very short TTL
        store
            .push("key1", json!("value1"), Some(StdDuration::from_millis(100)))
            .expect("failed to push value with TTL");
        assert_eq!(store.get("key1"), Some(json!("value1")));

        // Wait for expiration (add extra margin to account for timing)
        thread::sleep(StdDuration::from_millis(200));

        // Entry should be expired
        assert_eq!(store.get("key1"), None);
    }

    #[test]
    fn test_max_entries() {
        let config = DataStoreConfig {
            max_entries: 2,
            ..Default::default()
        };
        let store = DataStore::new(config, Arc::new(MetricsCollector::new(0)))
            .expect("should create store");

        store
            .push("key1", json!("value1"), None)
            .expect("failed to push key1 for max_entries test");
        store
            .push("key2", json!("value2"), None)
            .expect("failed to push key2 for max_entries test");

        // Third entry should fail
        let result = store.push("key3", json!("value3"), None);
        assert!(
            matches!(result, Err(DataError::StorageLimitExceeded { max: 2 })),
            "push with max_entries=2 should fail with StorageLimitExceeded when adding third entry"
        );
    }

    #[test]
    fn test_max_entry_size() {
        let config = DataStoreConfig {
            max_entry_size: 200,
            ..Default::default()
        };
        let store = DataStore::new(config, Arc::new(MetricsCollector::new(0)))
            .expect("should create store");

        // Small value should work (use a very short string to ensure it's under 200 bytes with metadata)
        store
            .push("key1", json!("x"), None)
            .expect("failed to push small value for max_entry_size test");

        // Large value should fail
        let large_value = json!(
            "this is a very long string that exceeds the limit and it needs to be even longer to exceed 200 bytes including metadata"
        );
        let result = store.push("key2", large_value, None);
        assert!(
            matches!(result, Err(DataError::ValueTooLarge { .. })),
            "push with value exceeding max_entry_size should fail with ValueTooLarge"
        );
    }

    #[test]
    fn test_max_ttl() {
        let config = DataStoreConfig {
            max_ttl: Some(StdDuration::from_secs(60)),
            ..Default::default()
        };
        let store = DataStore::new(config, Arc::new(MetricsCollector::new(0)))
            .expect("should create store");

        // TTL within limit should work
        store
            .push("key1", json!("value1"), Some(StdDuration::from_secs(30)))
            .expect("failed to push value with valid TTL");

        // TTL exceeding limit should fail
        let result = store.push("key2", json!("value2"), Some(StdDuration::from_secs(120)));
        assert!(
            matches!(result, Err(DataError::TTLExceeded { .. })),
            "push with TTL exceeding max_ttl should fail with TTLExceeded"
        );
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn test_default_ttl() {
        let config = DataStoreConfig {
            default_ttl: Some(StdDuration::from_millis(100)),
            ..Default::default()
        };
        let store = DataStore::new(config, Arc::new(MetricsCollector::new(0)))
            .expect("should create store");

        // Push without explicit TTL should use default
        store
            .push("key1", json!("value1"), None)
            .expect("failed to push value with default TTL");
        assert_eq!(store.get("key1"), Some(json!("value1")));

        // Wait for expiration (add extra margin to account for timing)
        thread::sleep(StdDuration::from_millis(200));

        // Entry should be expired
        assert_eq!(store.get("key1"), None);
    }

    #[test]
    fn test_various_json_types() {
        let store = create_test_store();

        // String
        store
            .push("str", json!("test"), None)
            .expect("failed to push string value");
        assert_eq!(store.get("str"), Some(json!("test")));

        // Number
        store
            .push("num", json!(42), None)
            .expect("failed to push number value");
        assert_eq!(store.get("num"), Some(json!(42)));

        // Boolean
        store
            .push("bool", json!(true), None)
            .expect("failed to push boolean value");
        assert_eq!(store.get("bool"), Some(json!(true)));

        // Array
        store
            .push("arr", json!([1, 2, 3]), None)
            .expect("failed to push array value");
        assert_eq!(store.get("arr"), Some(json!([1, 2, 3])));

        // Object
        let obj = json!({
            "a": 1,
            "b": "test",
            "c": [1, 2, 3]
        });
        store
            .push("obj", obj.clone(), None)
            .expect("failed to push object value");
        assert_eq!(store.get("obj"), Some(obj));
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn test_thread_safety() {
        let store = create_test_store();
        let store = std::sync::Arc::new(store);

        let mut handles = vec![];

        // Spawn multiple threads pushing values
        for i in 0..10 {
            let store_clone = store.clone();
            let handle = thread::spawn(move || {
                for j in 0..10 {
                    let key = format!("key_{i}_{j}");
                    store_clone
                        .push(&key, json!(format!("value_{}_{}", i, j)), None)
                        .expect("failed to push value in thread");
                }
            });
            handles.push(handle);
        }

        // Wait for all threads
        for handle in handles {
            handle.join().expect("thread panicked");
        }

        // Verify all entries are present
        assert_eq!(store.count(), 100);

        // Verify we can read from all threads
        let mut read_handles = vec![];
        for i in 0..10 {
            let store_clone = store.clone();
            let handle = thread::spawn(move || {
                for j in 0..10 {
                    let key = format!("key_{i}_{j}");
                    let expected = json!(format!("value_{}_{}", i, j));
                    assert_eq!(store_clone.get(&key), Some(expected));
                }
            });
            read_handles.push(handle);
        }

        for handle in read_handles {
            handle.join().expect("read thread panicked");
        }
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn test_concurrent_remove() {
        let store = create_test_store();
        let store = std::sync::Arc::new(store);

        // Populate store
        for i in 0..20 {
            let key = format!("key_{i}");
            store
                .push(&key, json!(i), None)
                .expect("failed to populate store for concurrent remove test");
        }

        let mut handles = vec![];

        // Spawn threads that remove entries
        for i in 0..10 {
            let store_clone = store.clone();
            let handle = thread::spawn(move || {
                store_clone.remove(&format!("key_{i}"));
            });
            handles.push(handle);
        }

        for handle in handles {
            handle.join().expect("remove thread panicked");
        }

        // Verify some entries were removed
        assert!(store.count() < 20);
    }

    #[test]
    fn test_get_entry_with_metadata() {
        let store = create_test_store();

        store
            .push("key1", json!("value1"), Some(StdDuration::from_secs(60)))
            .expect("failed to push value");

        let entry = store.get_entry("key1").expect("entry should exist");
        assert_eq!(entry.key, "key1");
        assert_eq!(entry.value, json!("value1"));
        assert_eq!(entry.data_type, crate::CedarType::String);
        assert_eq!(entry.access_count, 1); // Incremented by get_entry
        assert!(entry.expires_at.is_some());
    }

    #[test]
    fn test_metrics_tracking() {
        let config = DataStoreConfig {
            enable_metrics: true,
            ..Default::default()
        };
        let store = DataStore::new(config, Arc::new(MetricsCollector::new(0)))
            .expect("should create store");

        store
            .push("key1", json!("value1"), None)
            .expect("failed to push value");

        // First access
        let entry1 = store.get_entry("key1").expect("entry should exist");
        assert_eq!(entry1.access_count, 1);

        // Second access
        let entry2 = store.get_entry("key1").expect("entry should exist");
        assert_eq!(entry2.access_count, 2);

        // Third access
        let entry3 = store.get_entry("key1").expect("entry should exist");
        assert_eq!(entry3.access_count, 3);
    }

    #[test]
    fn test_metrics_disabled() {
        let config = DataStoreConfig {
            enable_metrics: false,
            ..Default::default()
        };
        let store = DataStore::new(config, Arc::new(MetricsCollector::new(0)))
            .expect("should create store");

        store
            .push("key1", json!("value1"), None)
            .expect("failed to push value");

        // Access multiple times
        let entry1 = store.get_entry("key1").expect("entry should exist");
        assert_eq!(entry1.access_count, 0); // Not incremented

        let entry2 = store.get_entry("key1").expect("entry should exist");
        assert_eq!(entry2.access_count, 0); // Still not incremented
    }

    #[test]
    fn test_cedar_type_inference() {
        use crate::CedarType;
        let store = create_test_store();

        store
            .push("string", json!("test"), None)
            .expect("failed to push string");
        store
            .push("number", json!(42), None)
            .expect("failed to push number");
        store
            .push("bool", json!(true), None)
            .expect("failed to push bool");
        store
            .push("array", json!([1, 2, 3]), None)
            .expect("failed to push array");
        store
            .push("object", json!({"key": "value"}), None)
            .expect("failed to push object");
        store
            .push("entity", json!({"type": "User", "id": "123"}), None)
            .expect("failed to push entity");

        assert_eq!(
            store.get_entry("string").unwrap().data_type,
            CedarType::String
        );
        assert_eq!(
            store.get_entry("number").unwrap().data_type,
            CedarType::Long
        );
        assert_eq!(store.get_entry("bool").unwrap().data_type, CedarType::Bool);
        assert_eq!(store.get_entry("array").unwrap().data_type, CedarType::Set);
        assert_eq!(
            store.get_entry("object").unwrap().data_type,
            CedarType::Record
        );
        assert_eq!(
            store.get_entry("entity").unwrap().data_type,
            CedarType::Entity
        );
    }

    #[test]
    fn test_config_validation() {
        // Valid config
        let valid_config = DataStoreConfig {
            default_ttl: Some(StdDuration::from_secs(300)),
            max_ttl: Some(StdDuration::from_secs(3600)),
            ..Default::default()
        };
        assert!(
            DataStore::new(valid_config, Arc::new(MetricsCollector::new(0))).is_ok(),
            "expected DataStore::new() to succeed with valid DataStoreConfig"
        );

        // Invalid config: default_ttl > max_ttl
        let invalid_config = DataStoreConfig {
            default_ttl: Some(StdDuration::from_secs(7200)),
            max_ttl: Some(StdDuration::from_secs(3600)),
            ..Default::default()
        };
        assert!(
            matches!(
                DataStore::new(invalid_config, Arc::new(MetricsCollector::new(0))),
                Err(ConfigValidationError::DefaultTtlExceedsMax { .. })
            ),
            "expected DataStore::new() to return ConfigValidationError when default_ttl exceeds max_ttl"
        );
    }

    // ==========================================================================
    // Additional store method tests
    // ==========================================================================

    #[test]
    fn test_list_entries() {
        let store = create_test_store();

        store
            .push("alpha", json!("a"), None)
            .expect("push should succeed");
        store
            .push("beta", json!("b"), None)
            .expect("push should succeed");

        let entries = store.list_entries();

        assert_eq!(entries.len(), 2);

        let keys: Vec<&str> = entries.iter().map(|e| e.key.as_str()).collect();
        assert!(keys.contains(&"alpha"));
        assert!(keys.contains(&"beta"));
    }

    #[test]
    fn test_config_accessor() {
        let config = DataStoreConfig {
            max_entries: 100,
            max_entry_size: 512,
            enable_metrics: true,
            ..Default::default()
        };
        let store = DataStore::new(config, Arc::new(MetricsCollector::new(0)))
            .expect("should create store");

        let retrieved_config = store.config();

        assert_eq!(retrieved_config.max_entries, 100);
        assert_eq!(retrieved_config.max_entry_size, 512);
        assert!(retrieved_config.enable_metrics);
    }

    // ==========================================================================
    // Context injection tests
    // ==========================================================================

    #[test]
    fn test_get_all_returns_all_values() {
        let store = create_test_store();

        store
            .push("user_role", json!("admin"), None)
            .expect("push should succeed");
        store
            .push(
                "feature_flags",
                json!({"dark_mode": true, "beta": false}),
                None,
            )
            .expect("push should succeed");
        store
            .push("rate_limit", json!(100), None)
            .expect("push should succeed");

        let all_data = store.get_all();

        assert_eq!(all_data.len(), 3);
        assert_eq!(all_data.get("user_role"), Some(&json!("admin")));
        assert_eq!(
            all_data.get("feature_flags"),
            Some(&json!({"dark_mode": true, "beta": false}))
        );
        assert_eq!(all_data.get("rate_limit"), Some(&json!(100)));
    }

    #[test]
    fn test_get_all_empty_store() {
        let store = create_test_store();
        let all_data = store.get_all();
        assert!(all_data.is_empty());
    }

    #[test]
    fn test_get_all_returns_values_not_metadata() {
        let store = create_test_store();

        store
            .push("key", json!({"nested": {"value": 42}}), None)
            .expect("push should succeed");

        let all_data = store.get_all();

        // get_all should return just the value, not the DataEntry wrapper
        let value = all_data.get("key").expect("key should exist");
        assert_eq!(value, &json!({"nested": {"value": 42}}));
    }

    #[test]
    fn test_get_all_suitable_for_context_injection() {
        let store = create_test_store();

        // Simulate typical context data
        store
            .push("device_type", json!("mobile"), None)
            .expect("push should succeed");
        store
            .push("geo", json!({"country": "US", "region": "CA"}), None)
            .expect("push should succeed");
        store
            .push("permissions", json!(["read", "write"]), None)
            .expect("push should succeed");

        let all_data = store.get_all();

        // Convert to JSON Value (as would be done in context building)
        let data_value: Value = Value::Object(all_data.into_iter().collect());

        // Verify structure is suitable for Cedar context
        assert!(data_value.is_object());
        let obj = data_value.as_object().unwrap();
        assert_eq!(obj.get("device_type"), Some(&json!("mobile")));
        assert_eq!(
            obj.get("geo"),
            Some(&json!({"country": "US", "region": "CA"}))
        );
        assert_eq!(obj.get("permissions"), Some(&json!(["read", "write"])));
    }

    #[test]
    fn test_total_size_calculation() {
        let store = create_test_store();

        // Empty store should have 0 size
        assert_eq!(store.total_size(), 0);

        // Add some entries
        store
            .push("key1", json!("short"), None)
            .expect("push should succeed");
        let size_after_one = store.total_size();
        assert!(
            size_after_one > 0,
            "size should be positive after adding entry"
        );

        store
            .push("key2", json!({"nested": {"data": "value"}}), None)
            .expect("push should succeed");
        let size_after_two = store.total_size();
        assert!(
            size_after_two > size_after_one,
            "size should increase after adding more entries"
        );

        // Remove an entry, size should decrease
        store.remove("key1");
        let size_after_remove = store.total_size();
        assert!(
            size_after_remove < size_after_two,
            "size should decrease after removing entry"
        );
    }

    #[test]
    fn test_memory_alert_threshold_validation() {
        // Valid threshold
        let config = DataStoreConfig {
            memory_alert_threshold: 80.0,
            ..Default::default()
        };
        assert!(config.validate().is_ok());

        // Edge case: 0%
        let config_zero = DataStoreConfig {
            memory_alert_threshold: 0.0,
            ..Default::default()
        };
        assert!(config_zero.validate().is_ok());

        // Edge case: 100%
        let config_hundred = DataStoreConfig {
            memory_alert_threshold: 100.0,
            ..Default::default()
        };
        assert!(config_hundred.validate().is_ok());

        // Invalid: negative
        let config_negative = DataStoreConfig {
            memory_alert_threshold: -1.0,
            ..Default::default()
        };
        assert!(
            config_negative.validate().is_err(),
            "memory_alert_threshold = -1.0 should fail validation"
        );

        // Invalid: over 100%
        let config_over = DataStoreConfig {
            memory_alert_threshold: 101.0,
            ..Default::default()
        };
        assert!(
            config_over.validate().is_err(),
            "memory_alert_threshold = 101.0 should fail validation"
        );
    }

    // ============================================================
    // Concurrent Access and Stress Tests
    // ============================================================

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn test_stress_concurrent_read_write() {
        use std::sync::Arc;
        use std::thread;

        let store = Arc::new(create_test_store());
        let mut handles = vec![];

        // 5 writer threads, each writing 100 entries
        for writer_id in 0..5 {
            let store_clone = store.clone();
            let handle = thread::spawn(move || {
                for i in 0..100 {
                    let key = format!("writer_{writer_id}_key_{i}");
                    store_clone
                        .push(&key, json!({"writer": writer_id, "value": i}), None)
                        .expect("concurrent push should succeed");
                }
            });
            handles.push(handle);
        }

        // 10 reader threads, each doing 200 reads
        for reader_id in 0..10 {
            let store_clone = store.clone();
            let handle = thread::spawn(move || {
                for i in 0..200 {
                    // Try to read various keys (some may exist, some may not)
                    let key = format!("writer_{}_key_{}", reader_id % 5, i % 100);
                    let _ = store_clone.get(&key);
                    // Also read count
                    let _ = store_clone.count();
                }
            });
            handles.push(handle);
        }

        // Wait for all threads
        for handle in handles {
            handle.join().expect("thread should not panic");
        }

        // Verify final state
        let count = store.count();
        assert_eq!(
            count, 500,
            "should have 5 writers * 100 entries = 500 entries"
        );
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn test_stress_concurrent_mixed_operations() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::thread;

        let store = Arc::new(create_test_store());
        let successful_pushes = Arc::new(AtomicUsize::new(0));
        let successful_removes = Arc::new(AtomicUsize::new(0));

        // Pre-populate with some data
        for i in 0..50 {
            store
                .push(&format!("pre_{i}"), json!(i), None)
                .expect("pre-populate should succeed");
        }

        let mut handles = vec![];

        // Writers
        for writer_id in 0..3 {
            let store_clone = store.clone();
            let pushes = successful_pushes.clone();
            let handle = thread::spawn(move || {
                for i in 0..50 {
                    let key = format!("writer_{writer_id}_item_{i}");
                    if store_clone.push(&key, json!({"id": i}), None).is_ok() {
                        pushes.fetch_add(1, Ordering::SeqCst);
                    }
                }
            });
            handles.push(handle);
        }

        // Removers
        for remover_id in 0..2 {
            let store_clone = store.clone();
            let removes = successful_removes.clone();
            let handle = thread::spawn(move || {
                for i in 0..25 {
                    // Try to remove pre-populated entries
                    let key = format!("pre_{}", remover_id * 25 + i);
                    if store_clone.remove(&key) {
                        removes.fetch_add(1, Ordering::SeqCst);
                    }
                }
            });
            handles.push(handle);
        }

        // Readers
        for _ in 0..5 {
            let store_clone = store.clone();
            let handle = thread::spawn(move || {
                for i in 0..100 {
                    let _ = store_clone.get(&format!("pre_{}", i % 50));
                    let _ = store_clone.get(&format!("writer_0_item_{}", i % 50));
                    let _ = store_clone.list_entries();
                }
            });
            handles.push(handle);
        }

        // Wait for all threads
        for handle in handles {
            handle.join().expect("thread should not panic");
        }

        // Log results (not strictly asserting due to race conditions in counts)
        let final_pushes = successful_pushes.load(Ordering::SeqCst);
        let final_removes = successful_removes.load(Ordering::SeqCst);
        let final_count = store.count();

        // Basic sanity check
        assert!(final_pushes > 0, "should have completed some pushes");
        assert!(final_removes > 0, "should have completed some removes");
        assert!(final_count > 0, "store should not be empty");
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn test_stress_rapid_clear_while_writing() {
        use std::sync::Arc;
        use std::thread;

        let store = Arc::new(create_test_store());
        let mut handles = vec![];

        // Writers continuously adding
        for writer_id in 0..3 {
            let store_clone = store.clone();
            let handle = thread::spawn(move || {
                for i in 0..200 {
                    let key = format!("key_{writer_id}_{i}");
                    let _ = store_clone.push(&key, json!(i), None);
                    // Small yield to allow interleaving
                    thread::yield_now();
                }
            });
            handles.push(handle);
        }

        // Clearer periodically clearing
        let store_clone = store.clone();
        let clear_handle = thread::spawn(move || {
            for _ in 0..10 {
                thread::sleep(StdDuration::from_micros(100));
                store_clone.clear();
            }
        });
        handles.push(clear_handle);

        // Wait for all threads
        for handle in handles {
            handle.join().expect("thread should not panic");
        }

        // Store may or may not be empty depending on timing - main test is no panics
    }

    #[test]
    #[cfg(not(target_arch = "wasm32"))]
    fn test_concurrent_get_all_for_context() {
        use std::sync::Arc;
        use std::thread;

        let store = Arc::new(create_test_store());

        // Pre-populate
        for i in 0..10 {
            store
                .push(&format!("data_{i}"), json!({"index": i}), None)
                .expect("pre-populate should succeed");
        }

        let mut handles = vec![];

        // Multiple threads calling get_all (simulating concurrent authorization requests)
        for _ in 0..10 {
            let store_clone = store.clone();
            let handle = thread::spawn(move || {
                for _ in 0..100 {
                    let data = store_clone.get_all();
                    // Verify data is consistent (has entries)
                    assert!(
                        !data.is_empty() || store_clone.count() == 0,
                        "get_all should return data or store is empty"
                    );
                }
            });
            handles.push(handle);
        }

        // One writer thread modifying data
        let store_clone = store.clone();
        let write_handle = thread::spawn(move || {
            for i in 0..50 {
                let key = format!("new_data_{i}");
                let _ = store_clone.push(&key, json!({"new_index": i}), None);
            }
        });
        handles.push(write_handle);

        // Wait for all threads
        for handle in handles {
            handle.join().expect("thread should not panic");
        }
    }
}