1
use std::any::TypeId;
2
use std::collections::{hash_map, HashMap};
3
use std::fmt::Debug;
4
use std::marker::PhantomData;
5

            
6
use derive_where::derive_where;
7

            
8
use crate::document::{BorrowedDocument, DocumentId, KeyId};
9
use crate::key::{ByteSource, Key, KeyDescription};
10
use crate::schema::collection::Collection;
11
use crate::schema::view::map::{self, MappedValue};
12
use crate::schema::view::{
13
    self, MapReduce, Serialized, SerializedView, ViewSchema, ViewUpdatePolicy,
14
};
15
use crate::schema::{CollectionName, Schema, SchemaName, View, ViewName};
16
use crate::Error;
17

            
18
/// A collection of defined collections and views.
19
pub struct Schematic {
20
    /// The name of the schema this was built from.
21
    pub name: SchemaName,
22
    contained_collections: HashMap<CollectionName, KeyDescription>,
23
    collections_by_type_id: HashMap<TypeId, CollectionName>,
24
    collection_encryption_keys: HashMap<CollectionName, KeyId>,
25
    collection_id_generators: HashMap<CollectionName, Box<dyn IdGenerator>>,
26
    views: HashMap<TypeId, Box<dyn view::Serialized>>,
27
    views_by_name: HashMap<ViewName, TypeId>,
28
    views_by_collection: HashMap<CollectionName, Vec<TypeId>>,
29
    eager_views_by_collection: HashMap<CollectionName, Vec<TypeId>>,
30
}
31

            
32
impl Schematic {
33
    /// Returns an initialized version from `S`.
34
146030
    pub fn from_schema<S: Schema + ?Sized>() -> Result<Self, Error> {
35
146030
        let mut schematic = Self {
36
146030
            name: S::schema_name(),
37
146030
            contained_collections: HashMap::new(),
38
146030
            collections_by_type_id: HashMap::new(),
39
146030
            collection_encryption_keys: HashMap::new(),
40
146030
            collection_id_generators: HashMap::new(),
41
146030
            views: HashMap::new(),
42
146030
            views_by_name: HashMap::new(),
43
146030
            views_by_collection: HashMap::new(),
44
146030
            eager_views_by_collection: HashMap::new(),
45
146030
        };
46
146030
        S::define_collections(&mut schematic)?;
47
146030
        Ok(schematic)
48
146030
    }
49

            
50
    /// Adds the collection `C` and its views.
51
5790863
    pub fn define_collection<C: Collection + 'static>(&mut self) -> Result<(), Error> {
52
5790863
        let name = C::collection_name();
53
5790863
        match self.contained_collections.entry(name.clone()) {
54
5790863
            hash_map::Entry::Vacant(entry) => {
55
5790863
                self.collections_by_type_id
56
5790863
                    .insert(TypeId::of::<C>(), name.clone());
57
5790863
                if let Some(key) = C::encryption_key() {
58
1799970
                    self.collection_encryption_keys.insert(name.clone(), key);
59
3990893
                }
60
5790863
                self.collection_id_generators
61
5790863
                    .insert(name, Box::<KeyIdGenerator<C>>::default());
62
5790863
                entry.insert(KeyDescription::for_key::<C::PrimaryKey>());
63
5790863
                C::define_views(self)
64
            }
65
            hash_map::Entry::Occupied(_) => Err(Error::CollectionAlreadyDefined),
66
        }
67
5790863
    }
68

            
69
    /// Adds the view `V`.
70
17316172
    pub fn define_view<V: MapReduce + ViewSchema<View = V> + SerializedView + Clone + 'static>(
71
17316172
        &mut self,
72
17316172
        view: V,
73
17316172
    ) -> Result<(), Error> {
74
17316172
        self.define_view_with_schema(view.clone(), view)
75
17316172
    }
76

            
77
    /// Adds the view `V`.
78
17316172
    pub fn define_view_with_schema<
79
17316172
        V: SerializedView + 'static,
80
17316172
        S: MapReduce + ViewSchema<View = V> + 'static,
81
17316172
    >(
82
17316172
        &mut self,
83
17316172
        view: V,
84
17316172
        schema: S,
85
17316172
    ) -> Result<(), Error> {
86
17316172
        let instance = ViewInstance { view, schema };
87
17316172
        let name = instance.view_name();
88
17316172
        if self.views_by_name.contains_key(&name) {
89
            return Err(Error::ViewAlreadyRegistered(name));
90
17316172
        }
91
17316172

            
92
17316172
        let collection = instance.collection();
93
17316172
        let eager = instance.update_policy().is_eager();
94
17316172
        self.views.insert(TypeId::of::<V>(), Box::new(instance));
95
17316172
        self.views_by_name.insert(name, TypeId::of::<V>());
96
17316172

            
97
17316172
        if eager {
98
3853093
            let unique_views = self
99
3853093
                .eager_views_by_collection
100
3853093
                .entry(collection.clone())
101
3853093
                .or_default();
102
3853093
            unique_views.push(TypeId::of::<V>());
103
13463079
        }
104
17316172
        let views = self.views_by_collection.entry(collection).or_default();
105
17316172
        views.push(TypeId::of::<V>());
106
17316172

            
107
17316172
        Ok(())
108
17316172
    }
109

            
110
    /// Returns `true` if this schema contains the collection `C`.
111
    #[must_use]
112
    pub fn contains_collection<C: Collection + 'static>(&self) -> bool {
113
        self.collections_by_type_id.contains_key(&TypeId::of::<C>())
114
    }
115

            
116
    /// Returns the description of the primary keyof the collection with the
117
    /// given name, or `None` if the collection can't be found.
118
    #[must_use]
119
1348320
    pub fn collection_primary_key_description<'a>(
120
1348320
        &'a self,
121
1348320
        collection: &CollectionName,
122
1348320
    ) -> Option<&'a KeyDescription> {
123
1348320
        self.contained_collections.get(collection)
124
1348320
    }
125

            
126
    /// Returns the next id in sequence for the collection, if the primary key
127
    /// type supports the operation and the next id would not overflow.
128
670840
    pub fn next_id_for_collection(
129
670840
        &self,
130
670840
        collection: &CollectionName,
131
670840
        id: Option<DocumentId>,
132
670840
    ) -> Result<DocumentId, Error> {
133
670840
        let generator = self
134
670840
            .collection_id_generators
135
670840
            .get(collection)
136
670840
            .ok_or(Error::CollectionNotFound)?;
137
670840
        generator.next_id(id)
138
670840
    }
139

            
140
    /// Looks up a [`view::Serialized`] by name.
141
1409200
    pub fn view_by_name(&self, name: &ViewName) -> Result<&'_ dyn view::Serialized, Error> {
142
1409200
        self.views_by_name
143
1409200
            .get(name)
144
1409200
            .and_then(|type_id| self.views.get(type_id))
145
1409200
            .map(AsRef::as_ref)
146
1409200
            .ok_or(Error::ViewNotFound)
147
1409200
    }
148

            
149
    /// Looks up a [`view::Serialized`] through the the type `V`.
150
52941
    pub fn view<V: View + 'static>(&self) -> Result<&'_ dyn view::Serialized, Error> {
151
52941
        self.views
152
52941
            .get(&TypeId::of::<V>())
153
52941
            .map(AsRef::as_ref)
154
52941
            .ok_or(Error::ViewNotFound)
155
52941
    }
156

            
157
    /// Iterates over all registered views.
158
160
    pub fn views(&self) -> impl Iterator<Item = &'_ dyn view::Serialized> {
159
160
        self.views.values().map(AsRef::as_ref)
160
160
    }
161

            
162
    /// Iterates over all views that belong to `collection`.
163
2256800
    pub fn views_in_collection(
164
2256800
        &self,
165
2256800
        collection: &CollectionName,
166
2256800
    ) -> impl Iterator<Item = &'_ dyn view::Serialized> {
167
2256800
        self.views_by_collection
168
2256800
            .get(collection)
169
2256800
            .into_iter()
170
2256800
            .flat_map(|view_ids| {
171
1415800
                view_ids
172
1415800
                    .iter()
173
6688560
                    .filter_map(|id| self.views.get(id).map(AsRef::as_ref))
174
2256800
            })
175
2256800
    }
176

            
177
    /// Iterates over all views that are eagerly updated that belong to
178
    /// `collection`.
179
2252520
    pub fn eager_views_in_collection(
180
2252520
        &self,
181
2252520
        collection: &CollectionName,
182
2252520
    ) -> impl Iterator<Item = &'_ dyn view::Serialized> {
183
2252520
        self.eager_views_by_collection
184
2252520
            .get(collection)
185
2252520
            .into_iter()
186
2252520
            .flat_map(|view_ids| {
187
821095
                view_ids
188
821095
                    .iter()
189
821095
                    .filter_map(|id| self.views.get(id).map(AsRef::as_ref))
190
2252520
            })
191
2252520
    }
192

            
193
    /// Returns a collection's default encryption key, if one was defined.
194
    #[must_use]
195
4650920
    pub fn encryption_key_for_collection(&self, collection: &CollectionName) -> Option<&KeyId> {
196
4650920
        self.collection_encryption_keys.get(collection)
197
4650920
    }
198

            
199
    /// Returns a list of all collections contained in this schematic.
200
1680
    pub fn collections(&self) -> impl Iterator<Item = &CollectionName> {
201
1680
        self.contained_collections.keys()
202
1680
    }
203
}
204

            
205
impl Debug for Schematic {
206
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207
        let mut views = self
208
            .views
209
            .values()
210
            .map(|v| v.view_name())
211
            .collect::<Vec<_>>();
212
        views.sort();
213

            
214
        f.debug_struct("Schematic")
215
            .field("name", &self.name)
216
            .field("contained_collections", &self.contained_collections)
217
            .field("collections_by_type_id", &self.collections_by_type_id)
218
            .field(
219
                "collection_encryption_keys",
220
                &self.collection_encryption_keys,
221
            )
222
            .field("collection_id_generators", &self.collection_id_generators)
223
            .field("views", &views)
224
            .field("views_by_name", &self.views_by_name)
225
            .field("views_by_collection", &self.views_by_collection)
226
            .field("eager_views_by_collection", &self.eager_views_by_collection)
227
            .finish()
228
    }
229
}
230

            
231
#[derive(Debug)]
232
struct ViewInstance<V, S> {
233
    view: V,
234
    schema: S,
235
}
236

            
237
impl<V, S> Serialized for ViewInstance<V, S>
238
where
239
    V: SerializedView,
240
    S: MapReduce + ViewSchema<View = V>,
241
{
242
18207770
    fn collection(&self) -> CollectionName {
243
18207770
        <<V as View>::Collection as Collection>::collection_name()
244
18207770
    }
245

            
246
4609
    fn key_description(&self) -> KeyDescription {
247
4609
        KeyDescription::for_key::<<V as View>::Key>()
248
4609
    }
249

            
250
24274285
    fn update_policy(&self) -> ViewUpdatePolicy {
251
24274285
        self.schema.update_policy()
252
24274285
    }
253

            
254
140651
    fn version(&self) -> u64 {
255
140651
        self.schema.version()
256
140651
    }
257

            
258
24775447
    fn view_name(&self) -> ViewName {
259
24775447
        self.view.view_name()
260
24775447
    }
261

            
262
564683
    fn map(&self, document: &BorrowedDocument<'_>) -> Result<Vec<map::Serialized>, view::Error> {
263
564683
        let mappings = self.schema.map(document)?;
264

            
265
564683
        mappings
266
564683
            .iter()
267
564683
            .map(map::Map::serialized::<V>)
268
564683
            .collect::<Result<_, _>>()
269
564683
            .map_err(view::Error::key_serialization)
270
564683
    }
271

            
272
569365
    fn reduce(&self, mappings: &[(&[u8], &[u8])], rereduce: bool) -> Result<Vec<u8>, view::Error> {
273
569365
        let mappings = mappings
274
569365
            .iter()
275
160933501
            .map(|(key, value)| {
276
160933501
                match <S::MappedKey<'_> as Key>::from_ord_bytes(ByteSource::Borrowed(key)) {
277
160933501
                    Ok(key) => {
278
160933501
                        let value = V::deserialize(value)?;
279
160933501
                        Ok(MappedValue::new(key, value))
280
                    }
281
                    Err(err) => Err(view::Error::key_serialization(err)),
282
                }
283
160933501
            })
284
569365
            .collect::<Result<Vec<_>, view::Error>>()?;
285

            
286
569365
        let reduced_value = self.schema.reduce(&mappings, rereduce)?;
287

            
288
511002
        V::serialize(&reduced_value).map_err(view::Error::from)
289
569365
    }
290
}
291

            
292
pub trait IdGenerator: Debug + Send + Sync {
293
    fn next_id(&self, id: Option<DocumentId>) -> Result<DocumentId, Error>;
294
}
295

            
296
5790863
#[derive_where(Default, Debug)]
297
pub struct KeyIdGenerator<C: Collection>(PhantomData<C>);
298

            
299
impl<C> IdGenerator for KeyIdGenerator<C>
300
where
301
    C: Collection,
302
{
303
468599
    fn next_id(&self, id: Option<DocumentId>) -> Result<DocumentId, Error> {
304
468599
        let key = id.map(|id| id.deserialize::<C::PrimaryKey>()).transpose()?;
305
468599
        let key = if let Some(key) = key {
306
430471
            key
307
        } else {
308
38128
            <C::PrimaryKey as Key<'_>>::first_value()
309
38128
                .map_err(|err| Error::DocumentPush(C::collection_name(), err))?
310
        };
311
468599
        let next_value = key
312
468599
            .next_value()
313
468599
            .map_err(|err| Error::DocumentPush(C::collection_name(), err))?;
314
468598
        DocumentId::new(&next_value)
315
468599
    }
316
}
317

            
318
1
#[test]
319
1
fn schema_tests() -> anyhow::Result<()> {
320
    use crate::test_util::{Basic, BasicCount};
321
1
    let schema = Schematic::from_schema::<Basic>()?;
322

            
323
1
    assert_eq!(schema.collections_by_type_id.len(), 1);
324
1
    assert_eq!(
325
1
        schema.collections_by_type_id[&TypeId::of::<Basic>()],
326
1
        Basic::collection_name()
327
1
    );
328
1
    assert_eq!(schema.views.len(), 6);
329
1
    assert_eq!(
330
1
        schema.views[&TypeId::of::<BasicCount>()].view_name(),
331
1
        View::view_name(&BasicCount)
332
1
    );
333

            
334
1
    Ok(())
335
1
}