ratio-metadata 0.2.2

Ratio's metadata model.
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
//! # Main metadata store module
//!
//! This module contains the main data store containing the different field stores, as well as
//! types and builders to perform transactions to the underlying store.
//!
//! ## License
//!
//! This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
//! If a copy of the MPL was not distributed with this file,
//! You can obtain one at <https://mozilla.org/MPL/2.0/>.
//!
//! **Code examples both in the docstrings and rendered documentation are free to use.**

use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Debug;

use slotmap::{Key, new_key_type};
use snafu::prelude::*;
use uuid::Uuid;

use crate::aggregate::Aggregate;
use crate::category::Category;
use crate::interner::{DenseSlottedBTreeInterner, Interner, ValueAlreadyExistsSnafu};
use crate::metadata::{AnnotationValue, Field, Metadata, MetadataRef, WeightValue};
use crate::transaction::{Transaction, TransactionMode};

/// Metadata store error.
#[derive(Clone, Debug, Snafu)]
#[snafu(visibility(pub))]
pub enum Error {
    /// Field name interner error.
    InternerError { source: crate::interner::Error },
}

new_key_type! {
    /// Unique object key type.
    pub struct ObjectKey;

    /// Unique name key type.
    pub struct NameKey;

    /// Unique kind key type.
    pub struct KindKey;

    /// Unique label key type.
    pub struct LabelKey;

    /// Unique weight key type.
    pub struct WeightKey;

    /// Unique annotation key type.
    pub struct AnnotationKey;
}

/// Store type for names.
pub type NameStore<ObjKey, Name> = Category<ObjKey, NameKey, NameKey, Name>;

/// Store type for kinds.
pub type KindStore<ObjKey, Kind> = Category<ObjKey, KindKey, KindKey, Kind>;

/// Store type for label sets.
pub type LabelStore<ObjKey, Label> = Category<ObjKey, BTreeSet<LabelKey>, LabelKey, Label>;

/// Store type for weight mappings.
pub type WeightStore<ObjKey, Weight, Value> =
    Category<ObjKey, BTreeMap<WeightKey, Value>, WeightKey, Weight>;

/// Store type for annotation mappings.
pub type AnnotationStore<ObjKey, Annotation, SubValue> =
    Category<ObjKey, BTreeMap<AnnotationKey, SubValue>, AnnotationKey, Annotation>;

/// Metadata store for simplified metadata.
pub type SimpleStore =
    MetadataStore<ObjectKey, String, String, String, String, f64, String, serde_json::Value>;

/// Metadata store that holds metadata for externally defined objects.
#[derive(Clone, Debug, bon::Builder)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(default, rename_all = "camelCase")
)]
#[cfg_attr(feature = "reactive", derive(reactive_stores::Store))]
pub struct MetadataStore<ObjKey, N, K, L, W, WV, A, AV>
where
    ObjKey: Key,
    N: Field,
    K: Field,
    L: Field,
    W: Field,
    WV: WeightValue,
    A: Field,
    AV: AnnotationValue,
{
    /// ID mapping for external object identification.
    ids: DenseSlottedBTreeInterner<ObjKey, Uuid>,

    /// Name metadata store.
    names: NameStore<ObjKey, N>,

    /// Kind metadata store.
    kinds: KindStore<ObjKey, K>,

    /// Label metadata store.
    labels: LabelStore<ObjKey, L>,

    /// Weight metadata store.
    weights: WeightStore<ObjKey, W, WV>,

    /// Annotation metadata store.
    annotations: AnnotationStore<ObjKey, A, AV>,
}

impl<ObjKey, N, K, L, W, WV, A, AV> Default for MetadataStore<ObjKey, N, K, L, W, WV, A, AV>
where
    ObjKey: Key,
    N: Field,
    K: Field,
    L: Field,
    W: Field,
    WV: WeightValue,
    A: Field,
    AV: AnnotationValue,
{
    fn default() -> Self {
        Self {
            ids: Default::default(),
            names: Default::default(),
            kinds: Default::default(),
            labels: Default::default(),
            weights: Default::default(),
            annotations: Default::default(),
        }
    }
}

impl<ObjKey, N, K, L, W, WV, A, AV> MetadataStore<ObjKey, N, K, L, W, WV, A, AV>
where
    ObjKey: Key,
    N: Field,
    K: Field,
    L: Field,
    W: Field,
    WV: WeightValue,
    A: Field,
    AV: AnnotationValue,
{
    /// Create a new metadata store.
    pub fn new() -> Self {
        Self::default()
    }

    /// The number of objects in store.
    pub fn len(&self) -> usize {
        self.ids.len()
    }

    /// Whether this store is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Add an object to the store by registering an ID for it.
    /// Returns the internally used key as well as the ID itself.
    pub fn add(&mut self) -> (ObjKey, Uuid) {
        let id = Uuid::new_v4();
        (self.intern_id(Cow::Borrowed(&id)), id)
    }

    /// Add a specific ID to the store.
    pub fn intern_id(&mut self, id: Cow<'_, Uuid>) -> ObjKey {
        self.ids.intern(id)
    }

    /// Try to insert a metadata object, returns an error if the ID already exists.
    pub fn try_insert(&mut self, meta: Metadata<N, K, L, W, WV, A, AV>) -> Result<ObjKey, Error> {
        let obj = self
            .ids
            .try_intern(Cow::Borrowed(&meta.id))
            .context(InternerSnafu)?;

        self.insert(meta);

        Ok(obj)
    }

    /// Insert a metadata object. Overrides any existing metadata.
    pub fn insert(&mut self, meta: Metadata<N, K, L, W, WV, A, AV>) -> ObjKey {
        let id = self.ids.intern_borrowed(&meta.id);

        let mut tx = meta.as_replace_transaction();
        tx.strip_id();

        self.apply(id, tx);

        id
    }

    /// Apply a transaction to an object using named metadata fields.
    /// Raises an error if the ID does not exist and when the new ID as supplied in the transaction
    /// already exists for another object.
    pub fn try_apply<Id: AsRef<Uuid>>(
        &mut self,
        id: Id,
        tx: Transaction<N, K, L, W, WV, A, AV>,
    ) -> Result<(), Error> {
        let obj = self.ids.try_get_key(id.as_ref()).context(InternerSnafu)?;

        if let Some(new_id) = tx.id.as_ref()
            && self.ids.get_key(new_id).as_ref() != Some(&obj)
        {
            ValueAlreadyExistsSnafu.fail().context(InternerSnafu)?;
        }

        self.apply(obj, tx);

        Ok(())
    }

    /// Apply a transaction to an object using named metadata fields.
    /// Assumes any potential ID update is valid.
    pub fn apply(&mut self, obj: ObjKey, tx: Transaction<N, K, L, W, WV, A, AV>) {
        let Transaction {
            mode,
            id: new_id,
            name,
            kind,
            labels,
            weights,
            annotations,
        } = tx;

        if let Some(new_id) = new_id
            && self.ids.get_key(&new_id).as_ref() != Some(&obj)
        {
            self.ids.remove_key(obj);
            self.ids.intern_owned(new_id);
        }

        // stored as option values internally
        if name.is_some() {
            self.names
                .set_value_name_of_object(obj, name.map(Cow::Owned));
        }

        // stored as option values internally
        if kind.is_some() {
            self.kinds
                .set_value_name_of_object(obj, kind.map(Cow::Owned));
        }

        if let Some(labels) = labels {
            if matches!(mode, TransactionMode::Replace) {
                self.labels.remove_object(obj);
            }
            labels.into_iter().for_each(|label| {
                self.labels
                    .insert_field_name_for_object(obj, Cow::Owned(label));
            });
        }

        if let Some(weights) = weights {
            if matches!(mode, TransactionMode::Replace) {
                self.weights.remove_object(obj);
            }
            weights.into_iter().for_each(|(k, v)| {
                self.weights
                    .insert_field_name_value_for_object(obj, Cow::Owned(k), v);
            });
        }

        if let Some(annotations) = annotations {
            if matches!(mode, TransactionMode::Replace) {
                self.annotations.remove_object(obj);
            }
            annotations.into_iter().for_each(|(k, v)| {
                self.annotations
                    .insert_field_name_value_for_object(obj, Cow::Owned(k), v);
            });
        };
    }

    /// Apply a transaction to an object based on internal keys representing metadata fields.
    /// Raises an error if a potential new ID as supplied in the transaction already exists
    /// for another object.
    pub fn try_apply_keyed(
        &mut self,
        obj: ObjKey,
        tx: Transaction<NameKey, KindKey, LabelKey, WeightKey, WV, AnnotationKey, AV>,
    ) -> Result<(), Error> {
        if let Some(new_id) = tx.id.as_ref()
            && self.ids.get_key(new_id).as_ref() != Some(&obj)
        {
            ValueAlreadyExistsSnafu.fail().context(InternerSnafu)?;
        }

        self.apply_keyed(obj, tx);

        Ok(())
    }

    /// Apply a transaction to an object based on internal keys representing metadata field.
    /// Assumes any potential ID update is valid.
    pub fn apply_keyed(
        &mut self,
        obj: ObjKey,
        tx: Transaction<NameKey, KindKey, LabelKey, WeightKey, WV, AnnotationKey, AV>,
    ) {
        let Transaction {
            mode,
            id: new_id,
            name,
            kind,
            labels,
            weights,
            annotations,
        } = tx;

        if let Some(new_id) = new_id
            && self.ids.get_key(&new_id).as_ref() != Some(&obj)
        {
            self.ids.remove_key(obj);
            self.ids.intern_owned(new_id);
        }

        // stored as option values internally
        if let Some(name) = name {
            self.set_object_name_key(obj, name);
        }

        // stored as option values internally
        if let Some(kind) = kind {
            self.set_object_kind_key(obj, kind);
        }

        if let Some(labels) = labels {
            if matches!(mode, TransactionMode::Replace) {
                self.labels.remove_object(obj);
            }
            labels.into_iter().for_each(|label| {
                self.set_object_label_key(obj, label);
            });
        }

        if let Some(weights) = weights {
            if matches!(mode, TransactionMode::Replace) {
                self.weights.remove_object(obj);
            }
            weights.into_iter().for_each(|(k, v)| {
                self.set_object_weight_key(obj, k, v);
            });
        }

        if let Some(annotations) = annotations {
            if matches!(mode, TransactionMode::Replace) {
                self.annotations.remove_object(obj);
            }
            annotations.into_iter().for_each(|(k, v)| {
                self.set_object_annotation_key(obj, k, v);
            });
        };
    }

    /// Intern a name. Returns the internally used key for that name.
    pub fn intern_name(&mut self, name: Cow<'_, N>) -> NameKey {
        self.names.field_key(name)
    }

    /// Forget a name entirely. Removes it from any object it was attached to.
    pub fn forget_name(&mut self, name: &N) -> Option<NameKey> {
        self.names.remove_field_name(name)
    }

    /// Forget a name entirely (by key). Removes it from any object it was attached to.
    pub fn forget_name_key(&mut self, name: NameKey) -> Option<N> {
        self.names.remove_field(name)
    }

    /// Apply a name to an object.
    pub fn set_object_name<Id: AsRef<Uuid>>(&mut self, id: Id, name: &N) {
        let obj = self.intern_id(Cow::Borrowed(id.as_ref()));
        let value = self.intern_name(Cow::Borrowed(name));
        self.set_object_name_key(obj, value);
    }

    /// Apply a name to an object using internally used keys.
    pub fn set_object_name_key(&mut self, obj: ObjKey, name: NameKey) {
        self.names.insert_object_value(obj, name);
    }

    /// Strip an objects name value.
    pub fn remove_object_name<Id: AsRef<Uuid>>(&mut self, id: Id) -> Option<&N> {
        let obj = self.ids.get_key(id.as_ref())?;
        self.remove_object_name_key(obj)
            .and_then(|key| self.names.field_name(key))
    }

    /// Strip an objects name value by means of the internally used keys.
    pub fn remove_object_name_key(&mut self, obj: ObjKey) -> Option<NameKey> {
        self.names.remove_object(obj)
    }

    /// Intern a kind. Returns the internally used key for that kind.
    pub fn intern_kind(&mut self, kind: Cow<K>) -> KindKey {
        self.kinds.field_key(kind)
    }

    /// Forget a kind entirely. Removes it from any object it was attached to.
    pub fn forget_kind(&mut self, kind: &K) -> Option<KindKey> {
        self.kinds.remove_field_name(kind)
    }

    /// Forget a kind entirely (by key). Removes it from any object it was attached to.
    pub fn forget_kind_key(&mut self, kind: KindKey) -> Option<K> {
        self.kinds.remove_field(kind)
    }

    /// Apply a kind to an object.
    pub fn set_object_kind<Id: AsRef<Uuid>>(&mut self, id: Id, kind: &K) {
        let obj = self.intern_id(Cow::Borrowed(id.as_ref()));
        let value = self.intern_kind(Cow::Borrowed(kind));
        self.set_object_kind_key(obj, value);
    }

    /// Apply a kind to an object using internally used keys.
    pub fn set_object_kind_key(&mut self, obj: ObjKey, kind: KindKey) {
        self.kinds.insert_object_value(obj, kind);
    }

    /// Strip an object's kind value.
    pub fn remove_object_kind<Id: AsRef<Uuid>>(&mut self, id: Id) -> Option<&K> {
        let obj = self.ids.get_key(id.as_ref())?;
        self.remove_object_kind_key(obj)
            .and_then(|key| self.kinds.field_name(key))
    }

    /// Strip an object's kind value by means of the internally used keys.
    pub fn remove_object_kind_key(&mut self, obj: ObjKey) -> Option<KindKey> {
        self.kinds.remove_object(obj)
    }

    /// Intern a label. Returns the internally used key for that label.
    pub fn intern_label(&mut self, label: Cow<L>) -> LabelKey {
        self.labels.field_key(label)
    }

    /// Forget a label entirely. Removes it from any object it was attached to.
    pub fn forget_label(&mut self, label: &L) -> Option<LabelKey> {
        self.labels.remove_field_name(label)
    }

    /// Forget a label entirely (by key). Removes it from any object it was attached to.
    pub fn forget_label_key(&mut self, label: LabelKey) -> Option<L> {
        self.labels.remove_field(label)
    }

    /// Apply a label to an object.
    pub fn set_object_label<Id: AsRef<Uuid>>(&mut self, id: Id, label: &L) {
        let obj = self.intern_id(Cow::Borrowed(id.as_ref()));
        self.labels
            .insert_field_name_for_object(obj, Cow::Borrowed(label));
    }

    /// Apply a label to an object by using internally used keys.
    pub fn set_object_label_key(&mut self, obj: ObjKey, label: LabelKey) {
        self.labels.insert_field_for_object(obj, label);
    }

    /// Strip a label from an object.
    pub fn remove_object_label<Id: AsRef<Uuid>>(&mut self, id: Id, label: &L) {
        if let Some(obj) = self.ids.get_key(id.as_ref()) {
            self.labels.remove_field_name_from_object(obj, label);
        }
    }

    /// Strip a label from an object by using internally used keys.
    pub fn strip_label_key(&mut self, obj: ObjKey, label: LabelKey) {
        self.labels.remove_field_from_object(obj, label);
    }

    /// Intern a weight. Returns the internally used key.
    pub fn intern_weight(&mut self, weight: Cow<W>) -> WeightKey {
        self.weights.field_key(weight)
    }

    /// Forget a weight field entirely. Removes it from any object it was attached to.
    /// Returns forgotten object-value pairs.
    pub fn forget_weight(&mut self, weight: &W) -> Option<WeightKey> {
        self.weights.remove_field_name_values(weight)
    }

    /// Forget a weight field entirely (by key). Removes it from any object it was attached to.
    /// Returns forgotten object-value pairs.
    pub fn forget_weight_key(&mut self, weight: WeightKey) -> Option<W> {
        self.weights.remove_field_values(weight)
    }

    /// Apply a weight value to an object.
    /// Returns the previous value if any.
    pub fn set_object_weight<Id: AsRef<Uuid>>(
        &mut self,
        id: Id,
        weight: &W,
        value: WV,
    ) -> Option<WV> {
        let obj = self.intern_id(Cow::Borrowed(id.as_ref()));
        self.weights
            .insert_field_name_value_for_object(obj, Cow::Borrowed(weight), value)
    }

    /// Apply a weight value to an object using internally used keys.
    /// Returns the previous value if any.
    pub fn set_object_weight_key(&mut self, obj: ObjKey, key: WeightKey, value: WV) -> Option<WV> {
        self.weights.insert_field_value_for_object(obj, key, value)
    }

    /// Strip a weight value from an object.
    pub fn remove_object_weight<Id: AsRef<Uuid>>(&mut self, id: Id, weight: &W) -> Option<WV> {
        self.ids.get_key(id.as_ref()).and_then(|obj| {
            self.weights
                .remove_field_name_value_from_object(obj, weight)
        })
    }

    /// Strip a weight value from an object using internally used keys.
    pub fn remove_object_weight_key(&mut self, obj: ObjKey, weight: WeightKey) -> Option<WV> {
        self.weights.remove_field_value_from_object(obj, weight)
    }

    /// Intern an annotation. Returns the internally used key.
    pub fn intern_annotation(&mut self, annotation: Cow<A>) -> AnnotationKey {
        self.annotations.field_key(annotation)
    }

    /// Forget an annotation field entirely. Removes it from any object it was attached to.
    /// Returns forgotten object-value pairs.
    pub fn forget_annotation(&mut self, annotation: &A) -> Option<AnnotationKey> {
        self.annotations.remove_field_name_values(annotation)
    }

    /// Forget an annotation field entirely. Removes it from any object it was attached to.
    /// Returns forgotten object-value pairs.
    pub fn forget_annotation_key(&mut self, key: AnnotationKey) -> Option<A> {
        self.annotations.remove_field_values(key)
    }

    /// Apply an annotation value to an object.
    /// Returns the previous value if any.
    pub fn set_object_annotation<Id: AsRef<Uuid>>(
        &mut self,
        id: Id,
        annotation: &A,
        value: AV,
    ) -> Option<AV> {
        let obj = self.intern_id(Cow::Borrowed(id.as_ref()));
        self.annotations
            .insert_field_name_value_for_object(obj, Cow::Borrowed(annotation), value)
    }

    /// Apply a annotation value to an object using internally used keys.
    /// Returns the previous value if any.
    pub fn set_object_annotation_key(
        &mut self,
        obj: ObjKey,
        key: AnnotationKey,
        value: AV,
    ) -> Option<AV> {
        self.annotations
            .insert_field_value_for_object(obj, key, value)
    }

    /// Strip an annotation value from an object.
    pub fn remove_object_annotation<Id: AsRef<Uuid>>(
        &mut self,
        id: Id,
        annotation: &A,
    ) -> Option<AV> {
        self.ids.get_key(id.as_ref()).and_then(|obj| {
            self.annotations
                .remove_field_name_value_from_object(obj, annotation)
        })
    }

    /// Strip an annotation value from an object using internally used keys.
    pub fn remove_object_annotation_key(
        &mut self,
        obj: ObjKey,
        annotation: AnnotationKey,
    ) -> Option<AV> {
        self.annotations
            .remove_field_value_from_object(obj, annotation)
    }

    /// Remove an object from the store by its ID.
    /// Returns if any metadata was held apart from its ID.
    pub fn remove_object<Id: AsRef<Uuid>>(&mut self, id: Id) -> bool {
        match self.ids.remove_value(id.as_ref()) {
            Some(obj) => self.remove_object_key(obj),
            None => false,
        }
    }

    /// Remove an object from the store by its key.  Returns if it was removed.
    pub fn remove_object_key(&mut self, obj: ObjKey) -> bool {
        self.ids.remove_key(obj);
        let did_name = self.names.remove_object(obj).is_some();
        let did_kind = self.kinds.remove_object(obj).is_some();
        let did_labels = self.labels.remove_object(obj).is_some();
        let did_weights = self.weights.remove_object(obj).is_some();
        let did_annotations = self.annotations.remove_object(obj).is_some();
        did_name | did_kind | did_labels | did_weights | did_annotations
    }

    /// Clean-up all interned field names that are no longer in use.
    pub fn clean(&mut self) {
        self.names.clean();
        self.kinds.clean();
        self.labels.clean();
        self.weights.clean();
        self.annotations.clean();
    }

    /// Get a metadata object with references to the field names.
    pub fn object_meta_named<'a, Id: AsRef<Uuid>>(
        &'a self,
        id: Id,
    ) -> Option<MetadataRef<'a, N, K, L, W, WV, A, AV>> {
        let id = *id.as_ref();
        self.ids.get_key(&id).map(|obj| {
            MetadataRef::builder()
                .id(id)
                .maybe_name(self.names.value_name_of_object(obj))
                .maybe_kind(self.kinds.value_name_of_object(obj))
                .labels(self.labels.named_value_of_object(obj))
                .weights(self.weights.named_value_of_object(obj))
                .annotations(self.annotations.named_value_of_object(obj))
                .build()
        })
    }

    /// Get a metadata object expressed as internal field keys.
    pub fn object_meta_keyed(
        &self,
        obj: ObjKey,
    ) -> Option<Metadata<NameKey, KindKey, LabelKey, WeightKey, WV, AnnotationKey, AV>> {
        self.object_id(obj).map(|id| {
            Metadata::builder()
                .id(id)
                .maybe_name(self.object_name_key(obj))
                .maybe_kind(self.object_kind_key(obj))
                .maybe_labels(self.object_label_keys(obj).cloned())
                .maybe_weights(self.object_weights_keyed(obj).cloned())
                .maybe_annotations(self.object_annotations_keyed(obj).cloned())
                .build()
        })
    }

    /// All object keys in store.
    pub fn object_keys(&self) -> impl Iterator<Item = ObjKey> {
        self.ids.keys()
    }

    /// All object IDs in store.
    pub fn object_ids(&self) -> impl Iterator<Item = &Uuid> {
        self.ids.values()
    }

    /// Iterator over all object key-ID pairs.
    pub fn object_key_id_pairs(&self) -> impl Iterator<Item = (ObjKey, &Uuid)> {
        self.ids.items()
    }

    /// Get the ID of an object.
    pub fn object_id(&self, obj: ObjKey) -> Option<Uuid> {
        self.ids.get_value(obj).copied()
    }

    /// Get the key of an object from its ID.
    pub fn object_key<Id: AsRef<Uuid>>(&self, id: Id) -> Option<ObjKey> {
        self.ids.get_key(id.as_ref())
    }

    /// Read-only access to the name interner.
    pub fn name_store(&self) -> &NameStore<ObjKey, N> {
        &self.names
    }

    /// Get all interned name field values.
    pub fn name_field_names(&self) -> impl Iterator<Item = &N> {
        self.names.field_names()
    }

    /// Get all interned name field keys.
    pub fn name_field_keys(&self) -> impl Iterator<Item = NameKey> {
        self.names.field_keys()
    }

    /// Get all interned name field key-name pairs.
    pub fn name_field_items(&self) -> impl Iterator<Item = (NameKey, &N)> {
        self.names.field_items()
    }

    /// Get all objects with the given name and return their ID.
    pub fn objects_with_name(&self, name: &N) -> impl Iterator<Item = Uuid> {
        self.names
            .objects_with_field_name(name)
            .into_iter()
            .flatten()
            .flat_map(|&obj| self.object_id(obj))
    }

    /// Get all objects with the given internal name key and return their internal key.
    pub fn objects_with_name_key(&self, name: NameKey) -> impl Iterator<Item = ObjKey> {
        self.names
            .objects_with_field(name)
            .into_iter()
            .flatten()
            .copied()
    }

    /// Get the name of an object by ID.
    pub fn object_name<Id: AsRef<Uuid>>(&self, id: Id) -> Option<&N> {
        self.object_key(id)
            .and_then(|obj| self.names.value_name_of_object(obj))
    }

    /// Get the interned name key of an object by internal key.
    pub fn object_name_key(&self, obj: ObjKey) -> Option<NameKey> {
        self.names.object_value(obj).copied()
    }

    /// Read-only access to the kind store.
    pub fn kind_store(&self) -> &KindStore<ObjKey, K> {
        &self.kinds
    }

    /// Get all interned kind field names.
    pub fn kind_field_names(&self) -> impl Iterator<Item = &K> {
        self.kinds.field_names()
    }

    /// Get all interned kind field keys.
    pub fn kind_field_keys(&self) -> impl Iterator<Item = KindKey> {
        self.kinds.field_keys()
    }

    /// Get all interned kind field key-name pairs.
    pub fn kind_field_items(&self) -> impl Iterator<Item = (KindKey, &K)> {
        self.kinds.field_items()
    }

    /// Get the kind of an object by ID.
    pub fn object_kind<Id: AsRef<Uuid>>(&self, id: Id) -> Option<&K> {
        self.object_key(id)
            .and_then(|obj| self.kinds.value_name_of_object(obj))
    }

    /// Get the interned kind key of an object by internal key.
    pub fn object_kind_key(&self, obj: ObjKey) -> Option<KindKey> {
        self.kinds.object_value(obj).copied()
    }

    /// Read-only access to the label store.
    pub fn label_store(&self) -> &LabelStore<ObjKey, L> {
        &self.labels
    }

    /// Get all interned label field names.
    pub fn label_field_names(&self) -> impl Iterator<Item = &L> {
        self.labels.field_names()
    }

    /// Get all interned label field keys.
    pub fn label_field_keys(&self) -> impl Iterator<Item = LabelKey> {
        self.labels.field_keys()
    }

    /// Get all interned label field key-name pairs.
    pub fn label_field_items(&self) -> impl Iterator<Item = (LabelKey, &L)> {
        self.labels.field_items()
    }

    /// Get the labels of an object.
    pub fn object_labels<Id: AsRef<Uuid>>(&self, id: Id) -> impl Iterator<Item = &L> {
        self.object_key(id)
            .into_iter()
            .flat_map(|obj| self.labels.object_field_names(obj))
    }

    /// Get the set of interned label keys for an object.
    pub fn object_label_keys(&self, obj: ObjKey) -> Option<&BTreeSet<LabelKey>> {
        self.labels.object_value(obj)
    }

    /// Read-only access to the weight store.
    pub fn weight_store(&self) -> &WeightStore<ObjKey, W, WV> {
        &self.weights
    }

    /// Get all interned weight field names.
    pub fn weight_field_names(&self) -> impl Iterator<Item = &W> {
        self.weights.field_names()
    }

    /// Get all interned weight field keys.
    pub fn weight_field_keys(&self) -> impl Iterator<Item = WeightKey> {
        self.weights.field_keys()
    }

    /// Get all interned weight field key-name pairs.
    pub fn weight_field_items(&self) -> impl Iterator<Item = (WeightKey, &W)> {
        self.weights.field_items()
    }

    /// Get all weight values of an object.
    pub fn object_weights<Id: AsRef<Uuid>>(&self, id: Id) -> BTreeMap<&W, &WV> {
        self.object_key(id)
            .map(|obj| self.weights.named_value_of_object(obj))
            .unwrap_or_default()
    }

    /// Get the mapping of weights by internal field keys for an object.
    pub fn object_weights_keyed(&self, obj: ObjKey) -> Option<&BTreeMap<WeightKey, WV>> {
        self.weights.object_value(obj)
    }

    /// Get a specific weight of an object via its name.
    pub fn object_weight<Id: AsRef<Uuid>>(&self, id: Id, weight: &W) -> Option<&WV> {
        self.object_key(id)
            .and_then(|obj| self.weights.field_name_value_for_object(obj, weight))
    }

    /// Get a specific weight of an object via its internal key.
    pub fn object_weight_by_key(&self, obj: ObjKey, weight: WeightKey) -> Option<&WV> {
        self.weights.field_value_for_object(obj, weight)
    }

    /// Read-only access to the annotation store.
    pub fn annotation_store(&self) -> &AnnotationStore<ObjKey, A, AV> {
        &self.annotations
    }

    /// Get all interned annotation field names.
    pub fn annotation_field_names(&self) -> impl Iterator<Item = &A> {
        self.annotations.field_names()
    }

    /// Get all interned annotation field keys.
    pub fn annotation_field_keys(&self) -> impl Iterator<Item = AnnotationKey> {
        self.annotations.field_keys()
    }

    /// Get all interned annotation field key-name pairs.
    pub fn annotation_field_items(&self) -> impl Iterator<Item = (AnnotationKey, &A)> {
        self.annotations.field_items()
    }

    /// Get all annotation values of an object.
    pub fn object_annotations<Id: AsRef<Uuid>>(&self, id: Id) -> BTreeMap<&A, &AV> {
        self.object_key(id)
            .map(|obj| self.annotations.named_value_of_object(obj))
            .unwrap_or_default()
    }

    /// Get the annotations mapping by internal field keys for an object.
    pub fn object_annotations_keyed(&self, obj: ObjKey) -> Option<&BTreeMap<AnnotationKey, AV>> {
        self.annotations.object_value(obj)
    }

    /// Get a specific annotation of an object via its name.
    pub fn object_annotation<Id: AsRef<Uuid>>(&self, id: Id, annotation: &A) -> Option<&AV> {
        self.object_key(id).and_then(|obj| {
            self.annotations
                .field_name_value_for_object(obj, annotation)
        })
    }

    /// Get a specific annotation of an object via its internal key.
    pub fn object_annotation_by_key(&self, obj: ObjKey, annotation: AnnotationKey) -> Option<&AV> {
        self.annotations.field_value_for_object(obj, annotation)
    }

    /// Iterate over the interned metadata in terms of field names
    pub fn iter_meta_named<'a>(
        &'a self,
    ) -> impl Iterator<Item = MetadataRef<'a, N, K, L, W, WV, A, AV>> {
        self.object_ids().map(|id| {
            self.object_meta_named(id).expect(
                "Object key and UUID pairs should always result in a metadata ref instance.",
            )
        })
    }

    /// Iterate over all interned metadata items in terms of internal keys.
    pub fn iter_meta_keyed(
        &self,
    ) -> impl Iterator<Item = Metadata<NameKey, KindKey, LabelKey, WeightKey, WV, AnnotationKey, AV>>
    {
        self.object_keys().map(|key| {
            self.object_meta_keyed(key).expect(
                "Object key and UUID pairs should always result in a metadata ref instance.",
            )
        })
    }

    /// Calculate the aggregate for this store.
    pub fn aggregate(&self) -> Aggregate<N, K, L, W, WV, A> {
        self.iter_meta_named()
            .fold(Aggregate::new(), |mut agg, meta| {
                agg.add(&meta);
                agg
            })
    }
}

#[cfg(test)]
pub mod tests {
    #[allow(unused_imports)]
    use pretty_assertions::{assert_eq, assert_ne, assert_str_eq};

    #[allow(unused_imports)]
    use super::*;
    pub use crate::metadata::tests::*;

    pub type TestStore = MetadataStore<ObjectKey, N, K, L, W, f64, A, serde_json::Value>;

    impl TestStore {
        pub fn foobarbazquux() -> Self {
            let mut store = Self::new();

            TestMeta::foobarbazquux().into_iter().for_each(|meta| {
                store.insert(meta);
            });

            store
        }
    }

    #[test]
    fn test_helper_store_empty() {
        let mut store = TestStore::new();

        assert_eq!(store.len(), 0);
        assert!(store.is_empty());

        let (key, id) = store.add();
        assert_eq!(store.object_key(id), Some(key));
        assert_eq!(store.object_id(key), Some(id));
        assert_eq!(store.len(), 1);
        assert!(!store.is_empty());
    }

    #[test]
    fn test_helper_store_reads() {
        let store = TestStore::foobarbazquux();

        assert_eq!(store.len(), 4);
        assert_eq!(store.object_keys().collect::<BTreeSet<_>>().len(), 4);
        assert_eq!(store.object_ids().collect::<BTreeSet<_>>().len(), 4);
        assert_eq!(store.object_key_id_pairs().collect::<Vec<_>>().len(), 4);

        let foo_id = store.objects_with_name(&N::Foo).next().expect("foo id");
        let foo_key = store.object_key(foo_id).expect("foo key");

        let meta_named = store.object_meta_named(foo_id).expect("metadata ref");
        assert_eq!(meta_named.name, Some(&N::Foo));
        assert_eq!(meta_named.kind, Some(&K::A));
        assert_eq!(meta_named.labels, bon::set![&L::A, &L::B]);
        assert_eq!(meta_named.weights, bon::map! { &W::A: &1.0 });
        assert_eq!(
            meta_named.annotations,
            bon::map! {&A::A: &serde_json::Value::String("FOO".to_string())}
        );

        let meta_keyed = store.object_meta_keyed(foo_key).expect("metadata keyed");
        assert_eq!(
            meta_keyed.name,
            store.name_store().field_key_interned(&N::Foo)
        );
    }

    #[test]
    fn test_aggregate() {
        let store = TestStore::foobarbazquux();
        let aggregate = store.aggregate();

        assert_eq!(
            aggregate.names,
            bon::map! { N::Foo: 1usize, N::Bar: 1usize, N::Baz: 1usize, N::Quux: 1usize },
            "names"
        );
        assert_eq!(
            aggregate.kinds,
            bon::map! { K::A: 1usize, K::B: 1usize, K::C: 1usize },
            "kinds"
        );
        assert_eq!(
            aggregate.labels,
            bon::map! { L::A: 1usize, L::B: 2usize, L::C: 2usize },
            "labels"
        );
        assert_eq!(
            aggregate.weights,
            bon::map! { W::A: 1.0, W::B: 4.0},
            "weights"
        );
        assert_eq!(
            aggregate.annotations,
            bon::map! { A::A: 4usize, A::B: 2usize },
            "annotations"
        );
    }
}