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
use crate::structs::PubKey;
use crate::structs::{Resource, ResourcePermission};
use ahash::RandomState;
use anyhow::anyhow;
use anyhow::Result;
use aruna_rust_api::api::storage::models::v2::{
    generic_resource::Resource as ApiResource, PermissionLevel,
};
use dashmap::{DashMap, DashSet};
use diesel_ulid::DieselUlid;

#[derive(Debug)]
pub struct Cache {
    // Graph cache contains From -> [all]
    pub graph_cache: DashMap<Resource, DashSet<Resource, RandomState>, RandomState>,
    pub name_cache: DashMap<String, DashSet<Resource, RandomState>, RandomState>,
    pub shared_id_cache: DashMap<DieselUlid, DieselUlid, RandomState>,
    pub object_cache: Option<DashMap<DieselUlid, ApiResource, RandomState>>,
    pub permissions:
        DashMap<DieselUlid, DashMap<ResourcePermission, PermissionLevel, RandomState>, RandomState>,
    pub pubkeys: DashSet<PubKey, RandomState>,
}

impl Default for Cache {
    fn default() -> Self {
        Self::new()
    }
}

impl Cache {
    pub fn new() -> Self {
        Cache {
            graph_cache: DashMap::with_hasher(RandomState::new()),
            name_cache: DashMap::with_hasher(RandomState::new()),
            shared_id_cache: DashMap::with_hasher(RandomState::new()),
            object_cache: None,
            permissions: DashMap::with_hasher(RandomState::new()),
            pubkeys: DashSet::with_hasher(RandomState::new()),
        }
    }

    pub fn traverse_graph(&self, from: &Resource) -> Result<Vec<(Resource, Resource)>> {
        let mut return_vec = Vec::new();
        let l1 = self
            .graph_cache
            .get(from)
            .ok_or_else(|| anyhow::anyhow!("Cannot find resource"))?;
        for l1_item in l1.iter() {
            let l1_cloned = l1_item.clone();
            if let Some(l2) = self.graph_cache.get(&l1_cloned) {
                for l2_item in l2.iter() {
                    let l2_cloned = l2_item.clone();
                    if let Some(l3) = self.graph_cache.get(&l2_cloned) {
                        for l3_item in l3.iter() {
                            let l3_cloned = l3_item.clone();
                            return_vec.push((l2_cloned.clone(), l3_cloned))
                        }
                    }
                    return_vec.push((l1_cloned.clone(), l2_cloned))
                }
            }
            return_vec.push((from.clone(), l1_cloned))
        }
        return_vec.reverse();
        Ok(return_vec)
    }

    pub fn get_parents_with_targets(&self, from: &Resource, targets: Vec<Resource>) -> Result<()> {
        match &from {
            Resource::Project(_) => return Err(anyhow!("Project does not have a parent")),
            Resource::Collection(_) => {
                for ref_val in self.graph_cache.iter() {
                    if ref_val.value().contains(from) && targets.contains(ref_val.key()) {
                        return Ok(());
                    }
                }
            }
            Resource::Dataset(_) => {
                for ref1_val in self.graph_cache.iter() {
                    if ref1_val.value().contains(from) {
                        if targets.contains(ref1_val.key()) {
                            return Ok(());
                        }
                        for ref2_val in self.graph_cache.iter() {
                            if ref2_val.value().contains(ref1_val.key())
                                && targets.contains(ref2_val.key())
                            {
                                return Ok(());
                            }
                        }
                    }
                }
            }
            Resource::Object(_) => {
                for ref1_val in self.graph_cache.iter() {
                    if ref1_val.value().contains(from) {
                        if targets.contains(ref1_val.key()) {
                            return Ok(());
                        }
                        for ref2_val in self.graph_cache.iter() {
                            if ref2_val.value().contains(ref1_val.key()) {
                                if targets.contains(ref2_val.key()) {
                                    return Ok(());
                                }
                                for ref3_val in self.graph_cache.iter() {
                                    if ref3_val.value().contains(ref2_val.key())
                                        && targets.contains(ref3_val.key())
                                    {
                                        return Ok(());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        Err(anyhow!("Cannot find from resource: {:#?}", &from))
    }

    // Gets a list of parent -> child connections, always from parent to child
    pub fn get_parents(&self, from: &Resource) -> Result<Vec<(Resource, Resource)>> {
        // TODO: This will only match one possible traversal path
        let mut return_vec = Vec::new();
        match &from {
            Resource::Project(_) => return Err(anyhow!("Project does not have a parent")),
            Resource::Collection(_) => {
                for ref_val in self.graph_cache.iter() {
                    if ref_val.value().contains(from) {
                        return_vec.push((ref_val.key().clone(), from.clone()));
                        break;
                    }
                }
                if return_vec.is_empty() {
                    return Err(anyhow!("Cannot find from resource: {:#?}", &from));
                }
            }
            Resource::Dataset(_) => {
                for ref1_val in self.graph_cache.iter() {
                    if ref1_val.value().contains(from) {
                        for ref2_val in self.graph_cache.iter() {
                            if ref2_val.value().contains(ref1_val.key()) {
                                return_vec.push((ref2_val.key().clone(), ref1_val.key().clone()));
                                break;
                            }
                        }
                        return_vec.push((ref1_val.key().clone(), from.clone()));
                        break;
                    }
                }
                if return_vec.is_empty() {
                    return Err(anyhow!("Cannot find from resource: {:#?}", &from));
                }
            }
            Resource::Object(_) => {
                for ref1_val in self.graph_cache.iter() {
                    if ref1_val.value().contains(from) {
                        for ref2_val in self.graph_cache.iter() {
                            if ref2_val.value().contains(ref1_val.key()) {
                                for ref3_val in self.graph_cache.iter() {
                                    if ref3_val.value().contains(ref2_val.key()) {
                                        return_vec
                                            .push((ref3_val.key().clone(), ref2_val.key().clone()));
                                        break;
                                    }
                                }
                                return_vec.push((ref2_val.key().clone(), ref1_val.key().clone()));
                                break;
                            }
                        }
                        return_vec.push((ref1_val.key().clone(), from.clone()));
                        break;
                    }
                }

                if return_vec.is_empty() {
                    return Err(anyhow!("Cannot find from resource: {:#?}", &from));
                }
            }
        }
        Ok(return_vec)
    }

    pub fn remove_all_res(&self, res: Resource) {
        self.graph_cache.remove(&res);
        for x in self.graph_cache.iter_mut() {
            x.value().remove(&res);
        }
    }

    pub fn add_name(&self, res: Resource, name: String) {
        self.name_cache.entry(name).or_default().insert(res);
    }

    pub fn remove_name(&self, res: Resource, name: Option<String>) {
        if let Some(name) = name {
            self.name_cache.entry(name).or_default().remove(&res);
        } else {
            for ent in self.name_cache.iter() {
                if ent.value().contains(&res) {
                    ent.value().remove(&res);
                }
            }
        }
    }

    pub fn add_link(&self, from: Resource, to: Resource) -> Result<()> {
        match (&from, &to) {
            (&Resource::Project(_), &Resource::Collection(_)) => (),
            (&Resource::Project(_), &Resource::Dataset(_)) => (),
            (&Resource::Project(_), &Resource::Object(_)) => (),
            (&Resource::Collection(_), &Resource::Dataset(_)) => (),
            (&Resource::Collection(_), &Resource::Object(_)) => (),
            (&Resource::Dataset(_), &Resource::Object(_)) => (),
            (_, _) => return Err(anyhow!("Invalid pair from: {:#?}, to: {:#?}", from, to)),
        }
        let entry = self.graph_cache.entry(from).or_default();
        entry.insert(to);
        Ok(())
    }

    pub fn remove_link(&self, from: Resource, to: Resource) {
        let entry = self.graph_cache.entry(from).or_default();
        entry.remove(&to);
    }

    // Shared id cache functions !

    // Exchanges Shared -> Persistent or vice-versa
    pub fn get_associated_id(&self, input: &DieselUlid) -> Option<DieselUlid> {
        self.shared_id_cache.get(input).map(|e| *e)
    }

    pub fn add_shared(&self, shared: DieselUlid, persistent: DieselUlid) {
        self.shared_id_cache.insert(shared, persistent);
        self.shared_id_cache.insert(persistent, shared);
    }

    pub fn update_shared(&self, shared: DieselUlid, new_persistent: DieselUlid) {
        let old = self.shared_id_cache.insert(shared, new_persistent);
        if let Some(o) = old {
            self.shared_id_cache.remove(&o);
        }
        self.shared_id_cache.insert(new_persistent, shared);
    }

    pub fn add_or_update_permission(
        &self,
        id: DieselUlid,
        perm: (ResourcePermission, PermissionLevel),
    ) {
        let entry = self.permissions.entry(id).or_default();
        entry.insert(perm.0, perm.1);
    }

    pub fn remove_permission(
        &self,
        id: DieselUlid,
        res: Option<ResourcePermission>,
        full_entry: bool,
    ) {
        if full_entry {
            self.permissions.remove(&id);
        } else if let Some(e) = self.permissions.get_mut(&id) {
            if let Some(p) = res {
                e.remove(&p);
            }
        }
    }

    pub fn get_permissions(
        &self,
        id: &DieselUlid,
    ) -> Option<Vec<(ResourcePermission, PermissionLevel)>> {
        let perms = self.permissions.get(id)?;
        let mut return_vec = Vec::new();
        for x in perms.value() {
            return_vec.push((x.key().clone(), *x.value()))
        }
        Some(return_vec)
    }

    pub fn add_pubkey(&self, pk: PubKey) {
        self.pubkeys.insert(pk);
    }

    pub fn remove_pubkey(&self, pk: PubKey) {
        self.pubkeys.remove(&pk);
    }

    pub fn get_pubkeys(&self) -> Vec<PubKey> {
        self.pubkeys.clone().into_iter().collect()
    }
}

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

    #[test]
    fn test_new() {
        let cache = Cache::new();

        let cache2 = Cache {
            graph_cache: DashMap::with_hasher(RandomState::new()),
            name_cache: DashMap::with_hasher(RandomState::new()),
            shared_id_cache: DashMap::with_hasher(RandomState::new()),
            object_cache: None,
            permissions: DashMap::with_hasher(RandomState::new()),
            pubkeys: DashSet::with_hasher(RandomState::new()),
        };

        assert_eq!(format!("{:#?}", cache), format!("{:#?}", cache2))
    }

    #[test]
    fn test_traverse_fail() {
        let cache = Cache::new();

        assert!(cache
            .traverse_graph(&Resource::Collection(DieselUlid::generate()))
            .is_err());
    }

    #[test]
    fn test_shared() {
        let cache = Cache::new();

        let shared_1 = DieselUlid::generate();
        let persistent_1 = DieselUlid::generate();
        let persistent_2 = DieselUlid::generate();

        cache.add_shared(shared_1, persistent_1);

        assert_eq!(cache.get_associated_id(&shared_1).unwrap(), persistent_1);
        assert_eq!(cache.get_associated_id(&persistent_1).unwrap(), shared_1);
        assert_eq!(cache.shared_id_cache.len(), 2);

        cache.update_shared(shared_1, persistent_2);
        assert_eq!(cache.get_associated_id(&shared_1).unwrap(), persistent_2);
        assert_eq!(cache.get_associated_id(&persistent_2).unwrap(), shared_1);
        assert_eq!(cache.shared_id_cache.len(), 2);
    }

    #[test]
    fn test_graph() {
        let cache = Cache::new();

        let project_1 = Project(DieselUlid::generate());
        let collection_1 = Collection(DieselUlid::generate());
        let _collection_2 = Collection(DieselUlid::generate());
        let _dataset_1 = Dataset(DieselUlid::generate());
        let _dataset_2 = Dataset(DieselUlid::generate());
        let _dataset_3 = Dataset(DieselUlid::generate());
        let _object_1 = Object(DieselUlid::generate());
        let _object_2 = Object(DieselUlid::generate());
        let _object_3 = Object(DieselUlid::generate());
        let _object_4 = Object(DieselUlid::generate());

        cache
            .add_link(project_1.clone(), collection_1.clone())
            .unwrap();
        assert_eq!(
            cache.get_parents(&collection_1).unwrap(),
            vec![(project_1.clone(), collection_1.clone())]
        );
        assert_eq!(
            cache.traverse_graph(&project_1).unwrap(),
            vec![(project_1.clone(), collection_1.clone())]
        );
        cache
            .add_link(project_1.clone(), collection_1.clone())
            .unwrap();
    }

    #[test]
    fn test_traverse_graph() {
        let cache = Cache::new();
        let resource_a = Resource::Project(DieselUlid::generate());
        let resource_b = Resource::Collection(DieselUlid::generate());
        let resource_c = Resource::Dataset(DieselUlid::generate());
        let resource_d = Resource::Object(DieselUlid::generate());

        // Add entries to the graph cache
        cache
            .add_link(resource_a.clone(), resource_b.clone())
            .unwrap();
        cache
            .add_link(resource_b.clone(), resource_c.clone())
            .unwrap();
        cache
            .add_link(resource_c.clone(), resource_d.clone())
            .unwrap();

        // Test the traverse_graph function
        let result = cache.traverse_graph(&resource_a).unwrap();
        let expected = vec![
            (resource_a.clone(), resource_b.clone()),
            (resource_b.clone(), resource_c.clone()),
            (resource_c.clone(), resource_d.clone()),
        ];
        assert_eq!(result, expected);
    }

    #[test]
    fn test_get_parents() {
        let cache = Cache::new();
        let resource_a = Resource::Project(DieselUlid::generate());
        let resource_b = Resource::Collection(DieselUlid::generate());
        let resource_c = Resource::Dataset(DieselUlid::generate());
        let resource_d = Resource::Object(DieselUlid::generate());

        // Add entries to the graph cache
        cache
            .add_link(resource_a.clone(), resource_b.clone())
            .unwrap();
        cache
            .add_link(resource_b.clone(), resource_c.clone())
            .unwrap();
        cache
            .add_link(resource_c.clone(), resource_d.clone())
            .unwrap();

        // Test the get_parents function
        let result = cache.get_parents(&resource_d).unwrap();
        let expected = vec![
            (resource_a.clone(), resource_b.clone()),
            (resource_b.clone(), resource_c.clone()),
            (resource_c.clone(), resource_d.clone()),
        ];
        assert_eq!(result, expected);

        // Test the get_parents function
        let result = cache.get_parents(&resource_c).unwrap();
        let expected = vec![
            (resource_a.clone(), resource_b.clone()),
            (resource_b.clone(), resource_c.clone()),
        ];
        assert_eq!(result, expected);

        // Test the get_parents function
        let result = cache.get_parents(&resource_b).unwrap();
        let expected = vec![(resource_a.clone(), resource_b.clone())];
        assert_eq!(result, expected);
    }

    #[test]
    fn test_add_name() {
        let cache = Cache::new();
        let resource_a = Resource::Project(DieselUlid::generate());
        let name = "NameA".to_owned();

        // Test adding a name
        cache.add_name(resource_a.clone(), name.clone());

        // Check if the name is present in the cache
        let result = cache
            .name_cache
            .get(&name)
            .map(|entry| entry.clone().into_iter().collect::<Vec<_>>())
            .unwrap_or_default();
        let expected = vec![resource_a.clone()];
        assert_eq!(result, expected);
    }

    #[test]
    fn test_remove_name() {
        let cache = Cache::new();
        let resource_a = Resource::Project(DieselUlid::generate());
        let resource_b = Resource::Project(DieselUlid::generate());
        let name = "NameA".to_owned();

        // Add names to the cache
        cache.add_name(resource_a.clone(), name.clone());
        cache.add_name(resource_b.clone(), name.clone());

        // Test removing a specific name
        cache.remove_name(resource_a.clone(), Some(name.clone()));

        // Check if the name is removed for the specific resource
        let result = cache
            .name_cache
            .get(&name)
            .map(|entry| entry.clone().into_iter().collect::<Vec<_>>())
            .unwrap_or_default();
        let expected = vec![resource_b.clone()];
        assert_eq!(result, expected);

        // Test removing all names associated with a resource
        cache.remove_name(resource_b.clone(), None);

        // Check if all names associated with the resource are removed
        assert!(cache.name_cache.get(&name).unwrap().is_empty());
    }

    #[test]
    fn test_add_link() {
        let cache = Cache::new();
        let resource_a = Resource::Project(DieselUlid::generate());
        let resource_b = Resource::Collection(DieselUlid::generate());

        // Test adding a valid link
        let result = cache.add_link(resource_a.clone(), resource_b.clone());
        assert!(result.is_ok());

        // Test adding an invalid link
        let resource_c = Resource::Dataset(DieselUlid::generate());
        let result = cache.add_link(resource_c.clone(), resource_a.clone());
        assert!(result.is_err());
    }

    #[test]
    fn test_remove_link() {
        let cache = Cache::new();
        let resource_a = Resource::Project(DieselUlid::generate());
        let resource_b = Resource::Collection(DieselUlid::generate());

        // Add a link to the cache
        cache
            .add_link(resource_a.clone(), resource_b.clone())
            .unwrap();

        // Test removing the link
        cache.remove_link(resource_a.clone(), resource_b.clone());

        // Check if the link is removed
        assert!(cache.graph_cache.get(&resource_a).unwrap().is_empty());
    }

    #[test]
    fn test_get_associated_id() {
        let cache = Cache::new();
        let shared_id = DieselUlid::generate();
        let persistent_id = DieselUlid::generate();

        // Add an entry to the shared id cache
        cache.add_shared(shared_id.clone(), persistent_id.clone());

        // Test getting the associated persistent id
        let result = cache.get_associated_id(&shared_id);
        assert_eq!(result, Some(persistent_id));

        // Test getting the associated shared id
        let result = cache.get_associated_id(&persistent_id);
        assert_eq!(result, Some(shared_id));

        // Test getting an associated id that doesn't exist
        let invalid_id = DieselUlid::generate();
        let result = cache.get_associated_id(&invalid_id);
        assert_eq!(result, None);
    }

    #[test]
    fn test_add_or_update_permission() {
        let cache = Cache::new();
        let resource_id = DieselUlid::generate();
        let permission = (
            ResourcePermission::Resource(Resource::Project(DieselUlid::generate())),
            PermissionLevel::Read,
        );

        // Test adding a permission
        cache.add_or_update_permission(resource_id.clone(), permission.clone());

        // Check if the permission is added
        let result = cache
            .permissions
            .get(&resource_id)
            .map(|entry| entry.clone().into_iter().collect::<Vec<_>>())
            .unwrap_or_default();
        let expected = vec![(permission.clone().0, permission.clone().1)];
        assert_eq!(result, expected);

        // Test updating a permission
        let updated_permission = (ResourcePermission::GlobalAdmin, PermissionLevel::Write);
        cache.add_or_update_permission(resource_id.clone(), updated_permission.clone());

        // Check if the permission is updated
        let result = cache
            .permissions
            .get(&resource_id)
            .map(|entry| entry.clone().into_iter().collect::<Vec<_>>())
            .unwrap_or_default();
        let expected = vec![permission, (updated_permission.0, updated_permission.1)];
        assert!(result.iter().all(|item| expected.contains(item)));
    }

    #[test]
    fn test_remove_permission() {
        let cache = Cache::new();
        let resource_id = DieselUlid::generate();
        let permission = (
            ResourcePermission::Resource(Resource::Project(DieselUlid::generate())),
            PermissionLevel::Read,
        );

        // Add a permission to the cache
        cache.add_or_update_permission(resource_id.clone(), permission.clone());

        // Test removing a specific permission
        cache.remove_permission(resource_id.clone(), Some(permission.0), true);

        // Check if the permission is removed for the specific resource
        assert!(!cache.permissions.contains_key(&resource_id));

        let permission = (
            ResourcePermission::Resource(Resource::Project(DieselUlid::generate())),
            PermissionLevel::Read,
        );
        cache.add_or_update_permission(resource_id.clone(), permission.clone());
        cache.remove_permission(resource_id.clone(), Some(permission.0), false);
        assert!(cache.permissions.get(&resource_id).unwrap().is_empty());
    }

    #[test]
    fn test_get_permissions() {
        let cache = Cache::new();
        let resource_id = DieselUlid::generate();
        let permission_1 = (
            ResourcePermission::Resource(Resource::Project(DieselUlid::generate())),
            PermissionLevel::Read,
        );
        let permission_2 = (ResourcePermission::GlobalAdmin, PermissionLevel::Write);

        // Add permissions to the cache
        cache.add_or_update_permission(resource_id.clone(), permission_1.clone());
        cache.add_or_update_permission(resource_id.clone(), permission_2.clone());

        // Test getting permissions
        let result = cache
            .get_permissions(&resource_id)
            .map(|perms| perms.into_iter().collect::<Vec<_>>())
            .unwrap();
        let expected = vec![permission_1.clone(), permission_2.clone()];
        assert!(result.iter().all(|item| expected.contains(item)));
    }

    #[test]
    fn test_add_pubkey() {
        let cache = Cache::new();
        let pubkey = PubKey::DataProxy("pubkey".to_owned());

        // Test adding a pubkey
        cache.add_pubkey(pubkey.clone());

        // Check if the pubkey is present in the cache
        assert!(cache.pubkeys.contains(&pubkey));
    }

    #[test]
    fn test_remove_pubkey() {
        let cache = Cache::new();
        let pubkey_a = PubKey::DataProxy("pubkey_a".to_owned());
        let pubkey_b = PubKey::DataProxy("pubkey_b".to_owned());

        // Add pubkeys to the cache
        cache.add_pubkey(pubkey_a.clone());
        cache.add_pubkey(pubkey_b.clone());

        // Test removing a pubkey
        cache.remove_pubkey(pubkey_a.clone());

        // Check if the pubkey is removed from the cache
        assert!(!cache.pubkeys.contains(&pubkey_a));
    }

    #[test]
    fn test_get_pubkeys() {
        let cache = Cache::new();
        let pubkey = PubKey::DataProxy("pubkey".to_owned());

        // Test adding a pubkey
        cache.add_pubkey(pubkey.clone());

        // Check if the pubkey is present in the cache
        assert!(cache.pubkeys.contains(&pubkey));

        assert_eq!(cache.get_pubkeys().len(), 1);
    }

    #[test]
    fn test_update_shared() {
        let cache = Cache::new();
        let shared_id = DieselUlid::generate();
        let new_persistent_id = DieselUlid::generate();

        // Test updating a shared id
        cache.update_shared(shared_id.clone(), new_persistent_id.clone());

        // Check if the shared id is updated
        cache.shared_id_cache.get(&shared_id);

        // Check if the new persistent id is associated with the shared id
        let result = cache.get_associated_id(&shared_id);
        assert_eq!(result, Some(new_persistent_id));
    }

    #[test]
    fn test_get_parents_with_target() {
        let cache = Cache::new();

        let project_a = Resource::Project(DieselUlid::generate());
        let project_b = Resource::Project(DieselUlid::generate());

        let collection_a = Resource::Collection(DieselUlid::generate());
        let collection_b = Resource::Collection(DieselUlid::generate());
        let collection_c = Resource::Collection(DieselUlid::generate());
        let collection_d = Resource::Collection(DieselUlid::generate());

        let dataset_a = Resource::Dataset(DieselUlid::generate());
        let object_a = Resource::Object(DieselUlid::generate());

        // Add entries to the graph cache
        cache
            .add_link(project_a.clone(), collection_a.clone())
            .unwrap();
        cache
            .add_link(project_a.clone(), collection_b.clone())
            .unwrap();
        cache
            .add_link(project_a.clone(), collection_c.clone())
            .unwrap();
        cache
            .add_link(project_a.clone(), collection_d.clone())
            .unwrap();
        cache
            .add_link(collection_a.clone(), dataset_a.clone())
            .unwrap();
        cache
            .add_link(collection_b.clone(), dataset_a.clone())
            .unwrap();
        cache
            .add_link(collection_c.clone(), dataset_a.clone())
            .unwrap();
        cache
            .add_link(collection_d.clone(), dataset_a.clone())
            .unwrap();
        cache.add_link(dataset_a.clone(), object_a.clone()).unwrap();

        assert!(cache.get_parents_with_targets(&object_a, vec![project_a.clone()]).is_ok());
        assert!(cache.get_parents_with_targets(&object_a, vec![collection_d.clone()]).is_ok());
        assert!(cache.get_parents_with_targets(&object_a, vec![dataset_a.clone()]).is_ok());
        assert!(cache.get_parents_with_targets(&object_a, vec![project_b.clone()]).is_err());
    }
}