rullst-orm 12.1.1

Fast, un-opinionated, database-agnostic ORM and query builder for Rust
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
use std::sync::atomic::{AtomicUsize, Ordering};

use async_trait::async_trait;
use serde::{Deserialize, Serialize};

use super::*;
use crate::polyglot::{
    CollectionName, DocumentEntry, DocumentId, DocumentInventory, DocumentPage, DocumentRepository,
    MockDocumentStore, PolyglotError,
};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Event {
    sequence: u64,
    label: String,
}

fn event(sequence: u64) -> Event {
    Event {
        sequence,
        label: format!("secret-event-{sequence}"),
    }
}

fn binding(collection: &CollectionName) -> DocumentRecoveryBinding {
    DocumentRecoveryBinding::try_new("academy.production", collection.clone())
        .expect("valid binding")
}

fn recovery_key(byte: u8) -> DocumentRecoveryKey {
    DocumentRecoveryKey::try_new("backup-2026-09", [byte; 32]).expect("valid key")
}

#[tokio::test]
async fn encrypted_snapshot_restores_and_replays_exact_subset() {
    let source = MockDocumentStore::<Event>::new();
    let destination = MockDocumentStore::<Event>::new();
    let collection = CollectionName::new("events").expect("valid collection");
    let first = DocumentId::new("event-01").expect("valid ID");
    let second = DocumentId::new("event-02").expect("valid ID");
    source
        .create(&collection, &second, &event(2))
        .await
        .expect("seed second");
    source
        .create(&collection, &first, &event(1))
        .await
        .expect("seed first");
    destination
        .create(&collection, &first, &event(1))
        .await
        .expect("seed resumable prefix");

    let binding = binding(&collection);
    let key = recovery_key(7);
    let policy = DocumentRecoveryPolicy::default();
    let snapshot = export_document_snapshot(&source, &binding, &key, policy)
        .await
        .expect("export snapshot");
    let independently_sealed = export_document_snapshot(&source, &binding, &key, policy)
        .await
        .expect("repeat export");
    assert_ne!(snapshot, independently_sealed);
    assert!(!snapshot.as_str().contains("secret-event"));
    assert_eq!(
        format!("{snapshot:?}"),
        "EncryptedDocumentSnapshot([REDACTED])"
    );
    assert!(!format!("{key:?}").contains("[7, 7"));

    let first_report = restore_document_snapshot(&destination, &snapshot, &binding, &key, policy)
        .await
        .expect("resume restore");
    assert_eq!(first_report.inserted(), 1);
    assert_eq!(first_report.replayed(), 1);
    assert_eq!(first_report.verified(), 2);

    let replay = restore_document_snapshot(&destination, &snapshot, &binding, &key, policy)
        .await
        .expect("idempotent replay");
    assert_eq!(replay.inserted(), 0);
    assert_eq!(replay.replayed(), 2);
    assert_eq!(replay.verified(), 2);
}

#[tokio::test]
// TM-ORM-01
async fn tampering_wrong_key_and_cross_scope_copy_fail_closed() {
    let source = MockDocumentStore::<Event>::new();
    let collection = CollectionName::new("events").expect("valid collection");
    source
        .create(
            &collection,
            &DocumentId::new("event-01").expect("valid ID"),
            &event(1),
        )
        .await
        .expect("seed source");
    let binding = binding(&collection);
    let key = recovery_key(9);
    let policy = DocumentRecoveryPolicy::default();
    let snapshot = export_document_snapshot(&source, &binding, &key, policy)
        .await
        .expect("export snapshot");

    let mut tampered = snapshot.as_str().as_bytes().to_vec();
    let index = tampered.len().saturating_sub(8);
    tampered[index] = if tampered[index] == b'A' { b'B' } else { b'A' };
    let tampered = String::from_utf8(tampered).expect("ASCII envelope");
    let tampered = EncryptedDocumentSnapshot::try_from_envelope(tampered, policy)
        .expect("structurally valid envelope");
    let destination = MockDocumentStore::<Event>::new();
    assert!(matches!(
        restore_document_snapshot(&destination, &tampered, &binding, &key, policy).await,
        Err(DocumentRecoveryError::AuthenticationFailed)
    ));

    let wrong_key = recovery_key(10);
    assert!(matches!(
        restore_document_snapshot(&destination, &snapshot, &binding, &wrong_key, policy).await,
        Err(DocumentRecoveryError::AuthenticationFailed)
    ));
    let other_binding = DocumentRecoveryBinding::try_new("other.production", collection)
        .expect("valid other binding");
    assert!(matches!(
        restore_document_snapshot(&destination, &snapshot, &other_binding, &key, policy).await,
        Err(DocumentRecoveryError::AuthenticationFailed)
    ));
}

#[tokio::test]
async fn malformed_envelopes_and_wrong_rotation_id_fail_before_repository_access() {
    let policy = DocumentRecoveryPolicy::default();
    assert!(matches!(
        EncryptedDocumentSnapshot::try_from_envelope("not-an-envelope", policy),
        Err(DocumentRecoveryError::InvalidEnvelope)
    ));

    let source = MockDocumentStore::<Event>::new();
    let destination = MockDocumentStore::<Event>::new();
    let collection = CollectionName::new("events").expect("valid collection");
    let binding = binding(&collection);
    let key = recovery_key(14);
    let snapshot = export_document_snapshot(&source, &binding, &key, policy)
        .await
        .expect("empty snapshot");
    let future = snapshot.as_str().replacen(":v1:", ":v2:", 1);
    assert!(matches!(
        EncryptedDocumentSnapshot::try_from_envelope(future, policy),
        Err(DocumentRecoveryError::UnsupportedVersion)
    ));
    let malformed_ciphertext = format!("{}=", snapshot.as_str());
    assert!(matches!(
        EncryptedDocumentSnapshot::try_from_envelope(malformed_ciphertext, policy),
        Err(DocumentRecoveryError::InvalidEnvelope)
    ));

    let rotated =
        DocumentRecoveryKey::try_new("backup-2026-10", [14; 32]).expect("valid rotated key");
    assert!(matches!(
        restore_document_snapshot(&destination, &snapshot, &binding, &rotated, policy).await,
        Err(DocumentRecoveryError::KeyIdMismatch)
    ));
}

#[tokio::test]
// TM-ORM-02
async fn conflicting_or_extra_destination_content_is_never_overwritten() {
    let source = MockDocumentStore::<Event>::new();
    let collection = CollectionName::new("events").expect("valid collection");
    let id = DocumentId::new("event-01").expect("valid ID");
    source
        .create(&collection, &id, &event(1))
        .await
        .expect("seed source");
    let binding = binding(&collection);
    let key = recovery_key(11);
    let policy = DocumentRecoveryPolicy::default();
    let snapshot = export_document_snapshot(&source, &binding, &key, policy)
        .await
        .expect("export snapshot");

    let conflicting = MockDocumentStore::<Event>::new();
    conflicting
        .create(&collection, &id, &event(99))
        .await
        .expect("seed conflict");
    assert!(matches!(
        restore_document_snapshot(&conflicting, &snapshot, &binding, &key, policy).await,
        Err(DocumentRecoveryError::DestinationConflict)
    ));
    assert_eq!(
        conflicting
            .find(&collection, &id)
            .await
            .expect("find conflict"),
        Some(event(99))
    );

    let extra = MockDocumentStore::<Event>::new();
    extra
        .create(
            &collection,
            &DocumentId::new("extra").expect("valid extra ID"),
            &event(3),
        )
        .await
        .expect("seed extra");
    assert!(matches!(
        restore_document_snapshot(&extra, &snapshot, &binding, &key, policy).await,
        Err(DocumentRecoveryError::DestinationConflict)
    ));
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct ReservedIdModel {
    id: String,
}

#[tokio::test]
async fn policy_bounds_and_non_portable_models_fail_before_sealing() {
    assert!(DocumentRecoveryPolicy::try_new(0, 1, 1_024).is_err());
    assert!(DocumentRecoveryPolicy::try_new(1, 0, 1_024).is_err());
    assert!(DocumentRecoveryPolicy::try_new(1, 1, 1_023).is_err());

    let collection = CollectionName::new("events").expect("valid collection");
    let binding = binding(&collection);
    let key = recovery_key(12);
    let source = MockDocumentStore::<ReservedIdModel>::new();
    source
        .create(
            &collection,
            &DocumentId::new("event-01").expect("valid ID"),
            &ReservedIdModel {
                id: "embedded".to_owned(),
            },
        )
        .await
        .expect("mock accepts backend-specific shape");
    assert!(matches!(
        export_document_snapshot(&source, &binding, &key, DocumentRecoveryPolicy::default()).await,
        Err(DocumentRecoveryError::NonPortableModel)
    ));

    let bounded = MockDocumentStore::<Event>::new();
    bounded
        .create(
            &collection,
            &DocumentId::new("one").expect("valid ID"),
            &event(1),
        )
        .await
        .expect("seed first");
    bounded
        .create(
            &collection,
            &DocumentId::new("two").expect("valid ID"),
            &event(2),
        )
        .await
        .expect("seed second");
    let one_document = DocumentRecoveryPolicy::try_new(1, 1, 1_024).expect("valid strict policy");
    assert!(matches!(
        export_document_snapshot(&bounded, &binding, &key, one_document).await,
        Err(DocumentRecoveryError::CapacityExceeded)
    ));
}

struct ChangingInventory {
    observations: AtomicUsize,
}

struct UnorderedInventory;

#[async_trait]
impl DocumentRepository<Event> for UnorderedInventory {
    async fn create(
        &self,
        _: &CollectionName,
        _: &DocumentId,
        _: &Event,
    ) -> Result<(), PolyglotError> {
        unreachable!("export does not mutate")
    }

    async fn find(
        &self,
        _: &CollectionName,
        _: &DocumentId,
    ) -> Result<Option<Event>, PolyglotError> {
        unreachable!("export does not find individual records")
    }

    async fn replace(
        &self,
        _: &CollectionName,
        _: &DocumentId,
        _: &Event,
    ) -> Result<(), PolyglotError> {
        unreachable!("export does not mutate")
    }

    async fn delete(&self, _: &CollectionName, _: &DocumentId) -> Result<bool, PolyglotError> {
        unreachable!("export does not mutate")
    }

    async fn list(&self, _: &CollectionName, _: DocumentPage) -> Result<Vec<Event>, PolyglotError> {
        unreachable!("export uses identifier-preserving inventory")
    }
}

#[async_trait]
impl DocumentInventory<Event> for UnorderedInventory {
    async fn list_entries(
        &self,
        _: &CollectionName,
        _: DocumentPage,
    ) -> Result<Vec<DocumentEntry<Event>>, PolyglotError> {
        Ok(vec![
            DocumentEntry::new(DocumentId::new("event-02").expect("valid ID"), event(2)),
            DocumentEntry::new(DocumentId::new("event-01").expect("valid ID"), event(1)),
        ])
    }
}

#[async_trait]
impl DocumentRepository<Event> for ChangingInventory {
    async fn create(
        &self,
        _: &CollectionName,
        _: &DocumentId,
        _: &Event,
    ) -> Result<(), PolyglotError> {
        unreachable!("export does not mutate")
    }

    async fn find(
        &self,
        _: &CollectionName,
        _: &DocumentId,
    ) -> Result<Option<Event>, PolyglotError> {
        unreachable!("export does not find individual records")
    }

    async fn replace(
        &self,
        _: &CollectionName,
        _: &DocumentId,
        _: &Event,
    ) -> Result<(), PolyglotError> {
        unreachable!("export does not mutate")
    }

    async fn delete(&self, _: &CollectionName, _: &DocumentId) -> Result<bool, PolyglotError> {
        unreachable!("export does not mutate")
    }

    async fn list(&self, _: &CollectionName, _: DocumentPage) -> Result<Vec<Event>, PolyglotError> {
        unreachable!("export uses identifier-preserving inventory")
    }
}

#[async_trait]
impl DocumentInventory<Event> for ChangingInventory {
    async fn list_entries(
        &self,
        _: &CollectionName,
        _: DocumentPage,
    ) -> Result<Vec<DocumentEntry<Event>>, PolyglotError> {
        let observation = self.observations.fetch_add(1, Ordering::SeqCst);
        Ok(vec![DocumentEntry::new(
            DocumentId::new("event-01").expect("valid ID"),
            event(observation as u64),
        )])
    }
}

#[tokio::test]
async fn changing_source_is_rejected_before_snapshot_creation() {
    let source = ChangingInventory {
        observations: AtomicUsize::new(0),
    };
    let collection = CollectionName::new("events").expect("valid collection");
    assert!(matches!(
        export_document_snapshot(
            &source,
            &binding(&collection),
            &recovery_key(13),
            DocumentRecoveryPolicy::default()
        )
        .await,
        Err(DocumentRecoveryError::SourceChanged)
    ));
}

#[tokio::test]
async fn unordered_inventory_is_rejected_before_snapshot_creation() {
    let collection = CollectionName::new("events").expect("valid collection");
    assert!(matches!(
        export_document_snapshot(
            &UnorderedInventory,
            &binding(&collection),
            &recovery_key(15),
            DocumentRecoveryPolicy::default()
        )
        .await,
        Err(DocumentRecoveryError::InvalidInventory)
    ));
}