p2panda-rs 0.5.0

All the things a panda needs
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
// SPDX-License-Identifier: AGPL-3.0-or-later

use async_trait::async_trait;
use log::debug;

use crate::document::{Document, DocumentId, DocumentView, DocumentViewId};
use crate::schema::SchemaId;
use crate::storage_provider::error::DocumentStorageError;
use crate::storage_provider::traits::DocumentStore;
use crate::test_utils::db::MemoryStore;

#[async_trait]
impl DocumentStore for MemoryStore {
    /// Insert document view into storage.
    ///
    /// returns an error when a fatal storage error occurs.
    async fn insert_document_view(
        &self,
        document_view: &DocumentView,
        schema_id: &SchemaId,
    ) -> Result<(), DocumentStorageError> {
        debug!(
            "Inserting document view with id {} into store",
            document_view.id()
        );
        self.document_views.lock().unwrap().insert(
            document_view.id().to_owned(),
            (schema_id.to_owned(), document_view.to_owned()),
        );

        Ok(())
    }

    /// Get a document view from storage by it's `DocumentViewId`.
    ///
    /// Returns a DocumentView or `None` if no view was found with this id. Returns
    /// an error if a fatal storage error occured.
    async fn get_document_view_by_id(
        &self,
        id: &DocumentViewId,
    ) -> Result<Option<DocumentView>, DocumentStorageError> {
        let view = self
            .document_views
            .lock()
            .unwrap()
            .get(id)
            .map(|(_, document_view)| document_view.to_owned());
        Ok(view)
    }

    /// Insert a document into storage.
    ///
    /// Inserts a document into storage and should retain a pointer to it's most recent
    /// document view. Returns an error if a fatal storage error occured.
    async fn insert_document(&self, document: &Document) -> Result<(), DocumentStorageError> {
        debug!("Inserting document with id {} into store", document.id());

        self.documents
            .lock()
            .unwrap()
            .insert(document.id().to_owned(), document.to_owned());

        if !document.is_deleted() {
            self.insert_document_view(document.view().unwrap(), document.schema())
                .await?;
        }

        Ok(())
    }

    /// Get the lates document view for a document identified by it's `DocumentId`.
    ///
    /// Returns a type implementing `AsDocumentView` wrapped in an `Option`, returns
    /// `None` if no view was found with this document. Returns an error if a fatal storage error
    /// occured.
    ///
    /// Note: if no view for this document was found, it might have been deleted.
    async fn get_document_by_id(
        &self,
        id: &DocumentId,
    ) -> Result<Option<DocumentView>, DocumentStorageError> {
        match self
            .documents
            .lock()
            .unwrap()
            .get(id)
            .map(|document| document.to_owned())
        {
            Some(document) => Ok(document.view().map(|view| view.to_owned())),
            None => Ok(None),
        }
    }

    /// Get the most recent view for all documents which follow the passed schema.
    ///
    /// Returns a vector of `DocumentView`, or an empty vector if none were found. Returns
    /// an error when a fatal storage error occured.
    async fn get_documents_by_schema(
        &self,
        schema_id: &SchemaId,
    ) -> Result<Vec<DocumentView>, DocumentStorageError> {
        let documents: Vec<DocumentView> = self
            .documents
            .lock()
            .unwrap()
            .iter()
            .filter(|(_, document)| document.schema() == schema_id)
            .filter_map(|(_, document)| document.view().cloned())
            .collect();

        Ok(documents)
    }
}
#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use rstest::rstest;

    use crate::document::{DocumentBuilder, DocumentView, DocumentViewFields, DocumentViewId};
    use crate::entry::traits::AsEncodedEntry;
    use crate::entry::{LogId, SeqNum};
    use crate::identity::Author;
    use crate::operation::traits::AsOperation;
    use crate::operation::OperationId;
    use crate::schema::SchemaId;
    use crate::storage_provider::traits::{DocumentStore, EntryStore, OperationStore};
    use crate::test_utils::constants::{self, test_fields};
    use crate::test_utils::db::test_db::{test_db, TestDatabase};
    use crate::test_utils::fixtures::random_document_view_id;

    #[rstest]
    #[tokio::test]
    async fn inserts_gets_one_document_view(
        #[from(test_db)]
        #[with(1, 1, 1)]
        #[future]
        db: TestDatabase,
    ) {
        let db = db.await;
        let author = Author::from(db.test_data.key_pairs[0].public_key());

        // Get one entry from the pre-polulated db
        let entry = db
            .store
            .get_entry_at_seq_num(&author, &LogId::default(), &SeqNum::new(1).unwrap())
            .await
            .unwrap()
            .unwrap();

        let operation = db
            .store
            .get_operation_by_id(&entry.hash().into())
            .await
            .unwrap()
            .unwrap();

        // Construct a `DocumentView`
        let operation_id: OperationId = entry.hash().into();
        let document_view_id: DocumentViewId = operation_id.clone().into();
        let document_view = DocumentView::new(
            &document_view_id,
            &DocumentViewFields::new_from_operation_fields(
                &operation_id,
                &operation.fields().unwrap(),
            ),
        );

        // Insert into db
        let result = db
            .store
            .insert_document_view(
                &document_view,
                &SchemaId::from_str(constants::SCHEMA_ID).unwrap(),
            )
            .await;

        assert!(result.is_ok());

        let retrieved_document_view = db
            .store
            .get_document_view_by_id(&document_view_id)
            .await
            .unwrap()
            .unwrap();

        for (key, _) in test_fields() {
            assert!(retrieved_document_view.get(key).is_some());
            assert_eq!(retrieved_document_view.get(key), document_view.get(key));
        }
    }

    #[rstest]
    #[tokio::test]
    async fn document_view_does_not_exist(
        random_document_view_id: DocumentViewId,
        #[from(test_db)]
        #[with(1, 1, 1)]
        #[future]
        db: TestDatabase,
    ) {
        let db = db.await;
        let view_does_not_exist = db
            .store
            .get_document_view_by_id(&random_document_view_id)
            .await
            .unwrap();

        assert!(view_does_not_exist.is_none());
    }

    #[rstest]
    #[tokio::test]
    async fn inserts_gets_documents(
        #[from(test_db)]
        #[with(1, 1, 1)]
        #[future]
        db: TestDatabase,
    ) {
        let db = db.await;
        let document_id = db.test_data.documents[0].clone();

        let document_operations = db
            .store
            .get_operations_by_document_id(&document_id)
            .await
            .unwrap();

        let document = DocumentBuilder::new(document_operations).build().unwrap();

        let result = db.store.insert_document(&document).await;

        assert!(result.is_ok());

        let document_view = db
            .store
            .get_document_view_by_id(document.view_id())
            .await
            .unwrap()
            .unwrap();

        let expected_document_view = document.view().unwrap();

        for (key, _) in test_fields() {
            assert!(document_view.get(key).is_some());
            assert_eq!(document_view.get(key), expected_document_view.get(key));
        }
    }

    #[rstest]
    #[tokio::test]
    async fn gets_document_by_id(
        #[from(test_db)]
        #[with(1, 1, 1)]
        #[future]
        db: TestDatabase,
    ) {
        let db = db.await;
        let document_id = db.test_data.documents[0].clone();

        let document_operations = db
            .store
            .get_operations_by_document_id(&document_id)
            .await
            .unwrap();

        let document = DocumentBuilder::new(document_operations).build().unwrap();

        let result = db.store.insert_document(&document).await;

        assert!(result.is_ok());

        let document_view = db
            .store
            .get_document_by_id(document.id())
            .await
            .unwrap()
            .unwrap();

        let expected_document_view = document.view().unwrap();

        for (key, _) in test_fields() {
            assert!(document_view.get(key).is_some());
            assert_eq!(document_view.get(key), expected_document_view.get(key));
        }
    }

    #[rstest]
    #[tokio::test]
    async fn no_view_when_document_deleted(
        #[from(test_db)]
        #[with(10, 1, 1, true)]
        #[future]
        db: TestDatabase,
    ) {
        let db = db.await;
        let document_id = db.test_data.documents[0].clone();

        let document_operations = db
            .store
            .get_operations_by_document_id(&document_id)
            .await
            .unwrap();

        let document = DocumentBuilder::new(document_operations).build().unwrap();

        let result = db.store.insert_document(&document).await;

        assert!(result.is_ok());

        let document_view = db.store.get_document_by_id(document.id()).await.unwrap();

        assert!(document_view.is_none());
    }

    #[rstest]
    #[tokio::test]
    async fn get_documents_by_schema_deleted_document(
        #[from(test_db)]
        #[with(10, 1, 1, true)]
        #[future]
        db: TestDatabase,
    ) {
        let db = db.await;
        let document_id = db.test_data.documents[0].clone();

        let document_operations = db
            .store
            .get_operations_by_document_id(&document_id)
            .await
            .unwrap();

        let document = DocumentBuilder::new(document_operations).build().unwrap();

        let result = db.store.insert_document(&document).await;

        assert!(result.is_ok());

        let document_views = db
            .store
            .get_documents_by_schema(&constants::SCHEMA_ID.parse().unwrap())
            .await
            .unwrap();

        assert!(document_views.is_empty());
    }

    #[rstest]
    #[tokio::test]
    async fn updates_a_document(
        #[from(test_db)]
        #[with(10, 1, 1)]
        #[future]
        db: TestDatabase,
    ) {
        let db = db.await;
        let document_id = db.test_data.documents[0].clone();

        let document_operations = db
            .store
            .get_operations_by_document_id(&document_id)
            .await
            .unwrap();

        let document = DocumentBuilder::new(document_operations).build().unwrap();

        let mut current_operations = Vec::new();

        for operation in document.operations() {
            // For each operation in the db we insert a document, cumulatively adding the next operation
            // each time. this should perform an "INSERT" first in the documents table, followed by 9 "UPDATES".
            current_operations.push(operation.clone());
            let document = DocumentBuilder::new(current_operations.clone())
                .build()
                .unwrap();
            let result = db.store.insert_document(&document).await;
            assert!(result.is_ok());

            let document_view = db.store.get_document_by_id(document.id()).await.unwrap();
            assert!(document_view.is_some());
        }
    }

    #[rstest]
    #[tokio::test]
    async fn gets_documents_by_schema(
        #[from(test_db)]
        #[with(10, 2, 1, false, constants::schema())]
        #[future]
        db: TestDatabase,
    ) {
        let db = db.await;
        let schema_id = SchemaId::from_str(constants::SCHEMA_ID).unwrap();

        for document_id in &db.test_data.documents {
            let document_operations = db
                .store
                .get_operations_by_document_id(document_id)
                .await
                .unwrap();

            let document = DocumentBuilder::new(document_operations).build().unwrap();

            db.store.insert_document(&document).await.unwrap();
        }

        let schema_documents = db.store.get_documents_by_schema(&schema_id).await.unwrap();

        assert_eq!(schema_documents.len(), 2);
    }
}