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
//! Repository of entities.

use std::{io, marker::PhantomData, vec};

use rand::{seq::SliceRandom, thread_rng};
use uuid::Uuid;

pub use cursor::*;
pub use error::*;

use crate::{Entity, Serializer, storage, Storage};

mod cursor;
mod error;

/// Repository of entities, backed by provided storage.
///
/// See this [crate](../index.html) root documentation for more information.
///
/// # Example
///
/// ```
/// use dodo::prelude::*;
/// # use serde::{Deserialize, Serialize};
/// # use uuid::Uuid;
/// #
/// # #[derive(Debug, Entity, Serialize, Deserialize, Eq, PartialEq)]
/// # #[serde(rename_all = "camelCase")]
/// # struct Person { id: Option<Uuid>, age: u64 }
/// #
/// # impl Person {
/// #    fn new() -> Self { Self { id : None, age : 42 } }
/// # }
///
/// type PersonRepository = Repository<Person, Directory, JsonSerializer>;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
/// #   let path  = tempfile::tempdir()?;
///     let directory = Directory::new(&path)?;
///     let mut repository = PersonRepository::new(directory);
///
///     let mut person = Person::new();
///     repository.insert(&mut person)?;
///
///     let entities = repository.find_all()?.collect()?;
///
///     println!("{:?}", entities);
///
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Repository<T, S, R> {
    storage: S,
    _t: PhantomData<T>,
    _r: PhantomData<R>,
}

impl<T, S, R> Repository<T, S, R>
    where T: Entity,
          S: Storage,
          R: Serializer {
    /// Create a new repository, using provided storage.
    ///
    /// # Examples
    ///
    /// ```
    /// use dodo::prelude::*;
    /// # use serde::{Deserialize, Serialize};
    /// # use uuid::Uuid;
    /// #
    /// # #[derive(Debug, Entity, Serialize, Deserialize, Eq, PartialEq)]
    /// # #[serde(rename_all = "camelCase")]
    /// # struct Person { id: Option<Uuid>, age: u64 }
    ///
    /// type PersonRepository = Repository<Person, Directory, JsonSerializer>;
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #   let path  = tempfile::tempdir()?;
    ///     let directory = Directory::new(&path)?;
    ///     let repository = PersonRepository::new(directory);
    ///     Ok(())
    /// }
    /// ```
    pub fn new(storage: S) -> Self {
        Self {
            storage,
            _t: PhantomData,
            _r: PhantomData,
        }
    }

    /// Find an specific entity, if it exists.
    ///
    /// Returns an error if not found.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dodo::{prelude::*, storage::Memory};
    /// # use serde::{Deserialize, Serialize};
    /// # use uuid::Uuid;
    /// #
    /// # #[derive(Debug, Entity, Serialize, Deserialize, Eq, PartialEq)]
    /// # #[serde(rename_all = "camelCase")]
    /// # struct Person { id: Option<Uuid>, age: u64 }
    /// # type PersonRepository = Repository<Person, Memory, JsonSerializer>;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #     let repository = PersonRepository::new(Memory::new());
    /// #
    /// # let id = Uuid::parse_str("78190929-3d84-4735-9e40-80e3cd5530e9").unwrap();
    /// let person = repository.find(id);
    ///
    /// match person {
    ///     Ok(person) => println!("Found!"),
    ///     Err(dodo::Error::NotFound(_)) => println!("Not found!"),
    ///     Err(_) => println!("Other error!")
    /// }
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn find(&self, id: Uuid) -> Result<T> {
        let reader = self.storage.read(id)?;
        R::deserialize(reader).map_err(From::from)
    }

    /// Provide a cursor iterating through the entities in this repository.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dodo::{prelude::*, storage::Memory};
    /// # use serde::{Deserialize, Serialize};
    /// # use uuid::Uuid;
    /// #
    /// # #[derive(Debug, Entity, Serialize, Deserialize, Eq, PartialEq)]
    /// # #[serde(rename_all = "camelCase")]
    /// # struct Person { id: Option<Uuid>, age: u64 }
    /// #
    /// # type PersonRepository = Repository<Person, Memory, JsonSerializer>;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #     let repository = PersonRepository::new(Memory::new());
    /// #
    /// let persons = repository.find_all()?.collect();
    ///
    /// println!("{:#?}", persons);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn find_all(&self) -> Result<RepositoryCursor<T, S, S::Iterator, R>> {
        RepositoryCursor::new(&self.storage)
    }

    /// Insert entity into this repository.
    ///
    /// The repository always assigns a new id to the entity, even if it already has one. Thus, the
    /// entity need to be mutable when inserted.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dodo::{prelude::*, storage::Memory};
    /// # use serde::{Deserialize, Serialize};
    /// # use uuid::Uuid;
    /// #
    /// # #[derive(Debug, Entity, Serialize, Deserialize, Eq, PartialEq)]
    /// # #[serde(rename_all = "camelCase")]
    /// # struct Person { id: Option<Uuid>, age: u64 }
    /// #
    /// # impl Person {
    /// #    fn new() -> Self { Self { id : None, age : 42 } }
    /// # }
    /// #
    /// # type PersonRepository = Repository<Person, Memory, JsonSerializer>;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #     let mut repository = PersonRepository::new(Memory::new());
    /// #
    /// let mut person = Person::new();  //Required to be mutable
    /// repository.insert(&mut person)?; //Assign new id to the entity.
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn insert(&mut self, entity: &mut T) -> Result<()> {
        let (id, writer) = self.storage.new()?;
        let old_id = entity.id(); //Backup old id, in case anything goes wrong.
        entity.set_id(Some(id));
        match R::serialize(writer, entity) {
            Ok(_) => Ok(()),
            Err(e) => {
                entity.set_id(old_id); //Something did go wrong. Restore old id.
                Err(e.into())
            }
        }
    }

    /// Update entity in this repository to a new version.
    ///
    /// The entity must exist in the repository and have an id.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dodo::{prelude::*, storage::Memory};
    /// # use serde::{Deserialize, Serialize};
    /// # use uuid::Uuid;
    /// #
    /// # #[derive(Debug, Entity, Serialize, Deserialize, Eq, PartialEq)]
    /// # #[serde(rename_all = "camelCase")]
    /// # struct Person { id: Option<Uuid>, age: u64 }
    /// #
    /// # impl Person {
    /// #    fn new() -> Self { Self { id : None, age : 42 } }
    /// # }
    /// #
    /// # type PersonRepository = Repository<Person, Memory, JsonSerializer>;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #     let mut repository = PersonRepository::new(Memory::new());
    /// #
    /// let mut person = Person::new();
    /// repository.insert(&mut person)?;
    ///
    /// person.age = 1337;
    /// repository.update(&person)?;
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn update(&mut self, entity: &T) -> Result<()> {
        let id = entity.id().ok_or(Error::Unidentified)?;
        let writer = self.storage.overwrite(id)?;
        R::serialize(writer, entity).map_err(From::from)
    }

    /// Update or insert entity into this repository.
    ///
    /// The entity is created if it doesn't exists, using the id currently assigned to it. You
    /// will receive an error if the entity doesn't have an id.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dodo::{prelude::*, storage::Memory};
    /// # use serde::{Deserialize, Serialize};
    /// # use uuid::Uuid;
    /// #
    /// # #[derive(Debug, Entity, Serialize, Deserialize, Eq, PartialEq)]
    /// # #[serde(rename_all = "camelCase")]
    /// # struct Person { id: Option<Uuid>, age: u64 }
    /// #
    /// # impl Person {
    /// #    fn new() -> Self { Self { id : None,  age : 42 } }
    /// # }
    /// #
    /// # type PersonRepository = Repository<Person, Memory, JsonSerializer>;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #     let mut repository = PersonRepository::new(Memory::new());
    /// #
    /// let mut person = Person::new();
    /// person.id = Some(Uuid::parse_str("78190929-3d84-4735-9e40-80e3cd5530e9").unwrap());
    /// repository.upsert(&mut person)?; //Doesn't exist ? No problem here!
    ///
    /// let mut person = Person::new();
    /// repository.insert(&mut person)?;
    /// person.age = 1337;
    /// repository.upsert(&mut person)?; //Already exist ? No problem too!
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn upsert(&mut self, entity: &T) -> Result<()> {
        let id = entity.id().ok_or(Error::Unidentified)?;
        let writer = self.storage.write(id)?;
        R::serialize(writer, entity).map_err(From::from)
    }

    /// Delete entity with provided id.
    ///
    /// This does not fail if the entity doesn't exist.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dodo::{prelude::*, storage::Memory};
    /// # use serde::{Deserialize, Serialize};
    /// # use uuid::Uuid;
    /// #
    /// # #[derive(Debug, Entity, Serialize, Deserialize, Eq, PartialEq)]
    /// # #[serde(rename_all = "camelCase")]
    /// # struct Person { id: Option<Uuid>, age: u64 }
    /// #
    /// # impl Person {
    /// #    fn new() -> Self { Self { id : None, age : 42 } }
    /// # }
    /// #
    /// # type PersonRepository = Repository<Person, Memory, JsonSerializer>;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #     let mut repository = PersonRepository::new(Memory::new());
    /// #
    /// let mut person = Person::new();
    /// repository.insert(&mut person)?; //Inserted here.
    /// repository.delete(person.id.unwrap())?; //Deleted here.
    ///
    /// let id : Uuid = Uuid::parse_str("78190929-3d84-4735-9e40-80e3cd5530e9").unwrap();
    /// repository.delete(id)?; //Doesn't exist ? No problem!
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn delete(&mut self, id: Uuid) -> Result<()> {
        self.storage.delete(id).map_err(From::from)
    }

    /// Delete every entity in this repository.
    ///
    /// Everything in this repository will be deleted. Use at your own risks.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dodo::{prelude::*, storage::Memory};
    /// # use serde::{Deserialize, Serialize};
    /// # use uuid::Uuid;
    /// #
    /// # #[derive(Debug, Entity, Serialize, Deserialize, Eq, PartialEq)]
    /// # #[serde(rename_all = "camelCase")]
    /// # struct Person { id: Option<Uuid>, age: u64 }
    /// #
    /// # impl Person {
    /// #    fn new() -> Self { Self { id : None, age : 42 } }
    /// # }
    /// #
    /// # type PersonRepository = Repository<Person, Memory, JsonSerializer>;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #     let mut repository = PersonRepository::new(Memory::new());
    /// #
    /// repository.insert(&mut Person::new())?;
    /// repository.insert(&mut Person::new())?;
    ///
    /// repository.clear();
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn clear(&mut self) -> Result<()> {
        self.storage.clear().map_err(From::from)
    }
}

/// Repository cursor, yeilding all entities inside the repository.
///
/// # Example
///
/// ```
/// # use dodo::prelude::*;
/// # use serde::{Deserialize, Serialize};
/// # use uuid::Uuid;
/// #
/// # #[derive(Debug, Entity, Serialize, Deserialize, Eq, PartialEq)]
/// # #[serde(rename_all = "camelCase")]
/// # struct Person { id: Option<Uuid>, age: u64 }
/// #
/// # impl Person {
/// #    fn new() -> Self { Self { id : None, age : 42 } }
/// # }
/// #
/// # type PersonRepository = Repository<Person, Directory, JsonSerializer>;
/// #
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// #   let path  = tempfile::tempdir()?;
/// #    let directory = Directory::new(&path)?;
/// #    let mut repository = PersonRepository::new(directory);
/// #
/// let entities = repository.find_all()?
///                          .filter(|person| person.age > 20)
///                          .skip(1)
///                          .take(3)?;
/// #
/// #     Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct RepositoryCursor<'a, T, S, I, R> {
    storage: &'a S,
    iterator: I,
    _t: PhantomData<T>,
    _r: PhantomData<R>,
}

impl<'a, T, S, R> RepositoryCursor<'a, T, S, S::Iterator, R>
    where T: Entity,
          S: Storage,
          R: Serializer {
    fn new(storage: &'a S) -> Result<Self> {
        let iterator = storage.iter()?;
        Ok(Self {
            storage,
            iterator,
            _t: PhantomData,
            _r: PhantomData,
        })
    }

    /// Shuffles the order the entities are yielded.
    ///
    /// Use this if you need to shuffle the entire repository contents. When done this early, this
    /// shuffles ids, not entities, so it is pretty lightweight. Nevertheless, this still has some
    /// serious performance implications, as this collects every id in the storage. With a small
    /// repository, this shouldn't be a problem, but with a large one, this will allocate a
    /// substantial amount of memory.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dodo::{prelude::*, storage::Memory};
    /// # use serde::{Deserialize, Serialize};
    /// # use uuid::Uuid;
    /// #
    /// # #[derive(Debug, Entity, Serialize, Deserialize, Eq, PartialEq)]
    /// # #[serde(rename_all = "camelCase")]
    /// # struct Person { id: Option<Uuid>, age: u64 }
    /// #
    /// # impl Person {
    /// #    fn new() -> Self { Self { id : None, age : 42 } }
    /// # }
    /// #
    /// # type PersonRepository = Repository<Person, Memory, JsonSerializer>;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #     let mut repository = PersonRepository::new(Memory::new());
    /// #
    /// let mut person1 = Person::new();
    /// let mut person2 = Person::new();
    /// repository.insert(&mut person1)?;
    /// repository.insert(&mut person2)?;
    ///
    /// let persons : Vec<Person> = repository.find_all()?
    ///                                       .shuffled()
    ///                                       .collect()?;
    ///
    /// assert!(persons.contains(&person1), "Person1 should be in the results.");
    /// assert!(persons.contains(&person2), "Person2 should be in the results.");
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn shuffled(self) -> RepositoryCursor<'a, T, S, vec::IntoIter<storage::Result<Uuid>>, R> {
        let Self { storage, iterator, .. } = self;

        let mut entries: Vec<storage::Result<Uuid>> = iterator.collect();
        entries.shuffle(&mut thread_rng());

        RepositoryCursor {
            iterator: entries.into_iter(),
            storage,
            _t: PhantomData,
            _r: PhantomData,
        }
    }
}

impl<'a, T, S, I, R> Cursor for RepositoryCursor<'a, T, S, I, R>
    where T: Entity,
          S: Storage,
          I: Iterator<Item=storage::Result<Uuid>>,
          R: Serializer {
    type Item = T;

    #[inline]
    fn next(&mut self) -> Result<Option<Self::Item>> {
        let Self { storage, iterator, .. } = self;

        //Map Storage Result to Repository Result.
        let into_result = |result: storage::Result<Uuid>| -> Result<Uuid> {
            result.map_err(From::from)
        };
        //Map Id to Reader.
        let into_reader = |result: Result<Uuid>| -> Result<S::Read> {
            result.and_then(|id| {
                storage.read(id).map_err(From::from)
            })
        };
        //Map Reader to Entity
        let into_entity = |result: Result<S::Read>| -> Result<Self::Item> {
            result.and_then(|reader| {
                R::deserialize(reader).map_err(From::from)
            })
        };
        //Repository might be modified while we are iterating over it. If an entry is deleted
        //before we have time to read it, we simply ignore it.
        let ignore_not_found = |result: &Result<Self::Item>| -> bool {
            match result {
                Err(Error::Io(e)) if e.kind() == io::ErrorKind::NotFound => false,
                _ => true
            }
        };

        iterator
            .next()
            .map(into_result)
            .map(into_reader)
            .map(into_entity)
            .filter(ignore_not_found)
            .transpose()
    }
}