vcon-server 0.4.15

Stores vCons encrypted at rest, on local disk or in an S3 bucket (as objects or Parquet files), and returns them to authorized readers.
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
//! A tenant's reads on a PostgreSQL catalog while another server removes
//! the tenant: its objects first, then its rows, the lock row last. No
//! read is answered as damaged: a read answers the whole version, or is
//! refused as a removed tenant's. The live tests need a PostgreSQL server.

#[cfg(feature = "backend-tests")]
mod on_a_server {
    use std::sync::Arc;
    use std::sync::atomic::Ordering::SeqCst;
    use std::sync::atomic::{AtomicBool, AtomicUsize};
    use std::time::Duration;

    use uuid::Uuid;

    use super::super::super::catalog::{CatalogError, Database, PgCatalog};
    use super::super::catalog_tests::on_a_server::{database, entry, owner_reads, tenant_catalog};
    use super::super::schema_tests::live::{Db, waiters};
    use crate::backend::Catalog;
    use crate::backend::conformance::{START, TestClock, vcon};
    use crate::backend::local::LocalObjects;
    use crate::envelope::{self, Key, REGISTRY};
    use crate::fs::OsFs;
    use crate::ids::TenantId;
    use crate::store::{Caller, Created, Store, StoreError};

    const A: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bca1";

    /// How long a step a test waits for may take.
    const PATIENCE: Duration = Duration::from_secs(20);

    /// How many reads each racing reader makes at least.
    const RACE_READS: usize = 40;

    /// A tenant's Store on a database of the test's own, its objects in a
    /// directory.
    struct Tenant {
        store: Store,
        caller: Caller,
        tenant: TenantId,
        database: Arc<Database>,
        objects: tempfile::TempDir,
    }

    /// The test's database and a tenant on it. The test holds the
    /// database itself, bound before the tenant (`let (db, t) =
    /// tenant();`), so it is dropped when the test ends, pass or fail: a
    /// reader thread a failed check left running may still hold the
    /// tenant, and nextest ends the process once the test returns, so a
    /// database the tenant held would never be dropped.
    fn tenant() -> (Db, Arc<Tenant>) {
        let (db, database) = database();
        let tenant = TenantId::generate();
        let key = Key::generate().expect("a tenant key");
        let catalog_key = envelope::catalog_key(&key).expect("the catalog key");
        let catalog =
            PgCatalog::create(database.clone(), tenant, &catalog_key).expect("the catalog");
        let objects = tempfile::tempdir().expect("a directory");
        let store = Store::open_on(
            tenant,
            key,
            Box::new(catalog),
            Arc::new(LocalObjects::new(objects.path().to_owned(), Arc::new(OsFs))),
            None,
            Arc::new(OsFs),
            TestClock::at(START),
            true,
        )
        .expect("opens");
        let t = Arc::new(Tenant {
            store,
            caller: Caller {
                key: Key::generate().expect("a key").id(),
            },
            tenant,
            database,
            objects,
        });
        (db, t)
    }

    fn stored(t: &Tenant) -> Vec<u8> {
        let (found, body) = vcon(A, "v0");
        let Ok(Created::New(_)) = t.store.create(&t.caller, &found, &body) else {
            panic!("a new vCon")
        };
        body
    }

    /// Deletes every object of the tenant's directory, as the bucket's
    /// removal does.
    fn objects_removed(t: &Tenant) {
        for entry in std::fs::read_dir(t.objects.path()).expect("the objects") {
            let path = entry.expect("an entry").path();
            if path.is_dir() {
                std::fs::remove_dir_all(&path).expect("removed");
            } else {
                std::fs::remove_file(&path).expect("removed");
            }
        }
    }

    /// Runs `readers` threads that read A until `done` is set and at
    /// least RACE_READS times each, each read checked by `check` with the
    /// value of `gate` taken before the read began; gives back the
    /// threads, each of which answers how many reads it made.
    fn race_reads(
        t: &Arc<Tenant>,
        readers: usize,
        done: &Arc<AtomicBool>,
        gate: &Arc<AtomicUsize>,
        check: impl Fn(usize, Result<Vec<u8>, StoreError>) + Send + Sync + 'static,
    ) -> Vec<std::thread::JoinHandle<usize>> {
        let check = Arc::new(check);
        let a = Uuid::parse_str(A).expect("a uuid");
        (0..readers)
            .map(|_| {
                let (t, done, gate, check) = (t.clone(), done.clone(), gate.clone(), check.clone());
                std::thread::spawn(move || {
                    let deadline = std::time::Instant::now() + PATIENCE * 6;
                    let mut made = 0;
                    while made < RACE_READS || !done.load(SeqCst) {
                        assert!(
                            std::time::Instant::now() < deadline,
                            "the race ended within its deadline"
                        );
                        let before = gate.load(SeqCst);
                        check(before, t.store.get(&t.caller, a).map(|s| s.body));
                        made += 1;
                    }
                    made
                })
            })
            .collect()
    }

    fn joined(readers: Vec<std::thread::JoinHandle<usize>>) -> usize {
        readers
            .into_iter()
            .map(|r| r.join().expect("a reader ends without a failed check"))
            .sum()
    }

    /// Reads race the tenant's removal on another server (its objects
    /// first, then its rows, the lock row last): a read answers the whole
    /// version or is refused, never as damaged, and every read that began
    /// after the removal ended is refused.
    #[test]
    fn reads_racing_a_tenant_removal_answer_the_version_or_are_refused() {
        let (_db, t) = tenant();
        let body = stored(&t);
        let done = Arc::new(AtomicBool::new(false));
        let removed = Arc::new(AtomicUsize::new(0));
        let answered_reads = Arc::new(AtomicUsize::new(0));
        let counted = answered_reads.clone();
        let readers = race_reads(
            &t,
            4,
            &done,
            &removed,
            move |before, answered| match answered {
                Ok(b) => {
                    assert_eq!(
                        before, 0,
                        "no read that began after the removal is answered"
                    );
                    assert_eq!(b, body, "the whole version");
                    counted.fetch_add(1, SeqCst);
                }
                Err(e) => assert_ne!(e, StoreError::Damaged, "refused, not as damaged"),
            },
        );
        let deadline = std::time::Instant::now() + PATIENCE;
        while answered_reads.load(SeqCst) < 8 {
            assert!(
                std::time::Instant::now() < deadline,
                "reads were answered before the removal"
            );
            std::thread::yield_now();
        }
        PgCatalog::remove(&t.database, t.tenant, 1, || {
            objects_removed(&t);
            Ok(())
        })
        .expect("the tenant is removed");
        removed.store(1, SeqCst);
        done.store(true, SeqCst);
        joined(readers);
    }

    /// The tenant's lock row, as the owner reads it: `["false"]`,
    /// `["true"]`, or no row.
    fn mark(db: &Db, t: &Tenant) -> Vec<String> {
        owner_reads(db, t.tenant, "SELECT removing::text FROM vcon.tenant_lock")
    }

    fn present(t: &Tenant) -> bool {
        PgCatalog::present(&t.database)
            .expect("the tenants present")
            .contains(&t.tenant)
    }

    fn a() -> Uuid {
        Uuid::parse_str(A).expect("a uuid")
    }

    // What must work.

    #[test]
    fn a_made_tenant_s_lock_row_is_not_marked() {
        let (db, t) = tenant();
        assert_eq!(
            mark(&db, &t),
            ["false"],
            "a new tenant is not being removed"
        );
    }

    #[test]
    fn the_lock_row_is_marked_before_the_objects_go() {
        let (db, t) = tenant();
        let body = stored(&t);
        PgCatalog::remove(&t.database, t.tenant, 10, || {
            assert_eq!(mark(&db, &t), ["true"], "marked when the objects go");
            assert!(
                std::fs::read_dir(t.objects.path())
                    .expect("the objects")
                    .next()
                    .is_some(),
                "and the objects are still there"
            );
            assert!(!body.is_empty(), "a vCon was stored");
            objects_removed(&t);
            Ok(())
        })
        .expect("removed");
        assert_eq!(
            mark(&db, &t),
            Vec::<String>::new(),
            "the lock row is gone at the end"
        );
        assert!(!present(&t), "and the tenant is not present");
    }

    #[test]
    fn a_read_after_the_mark_is_refused_not_damaged_while_the_object_is_there() {
        let (_db, t) = tenant();
        stored(&t);
        PgCatalog::remove(&t.database, t.tenant, 10, || {
            let read = t.store.get(&t.caller, a()).map(|s| s.body);
            let Err(e) = read else {
                panic!("a read after the mark is refused")
            };
            assert_ne!(
                e,
                StoreError::Damaged,
                "refused as a removed tenant's, not as damaged"
            );
            objects_removed(&t);
            Ok(())
        })
        .expect("removed");
    }

    #[test]
    fn a_read_after_the_removal_is_refused_not_damaged() {
        let (_db, t) = tenant();
        stored(&t);
        PgCatalog::remove(&t.database, t.tenant, 1, || {
            objects_removed(&t);
            Ok(())
        })
        .expect("removed");
        let read = t.store.get(&t.caller, a()).map(|s| s.body);
        let Err(e) = read else {
            panic!("a read after the removal is refused")
        };
        assert_ne!(e, StoreError::Damaged, "refused, not as damaged");
    }

    #[test]
    fn a_removal_made_again_after_its_objects_failed_removes_the_tenant() {
        let (_db, t) = tenant();
        stored(&t);
        assert_eq!(
            PgCatalog::remove(&t.database, t.tenant, 10, || Err(CatalogError::Io)),
            Err(CatalogError::Io),
            "the objects' error"
        );
        PgCatalog::remove(&t.database, t.tenant, 10, || {
            objects_removed(&t);
            Ok(())
        })
        .expect("removed the second time");
        assert!(!present(&t), "the tenant is gone");
    }

    #[test]
    fn a_tenant_whose_lock_row_is_gone_is_removed_with_its_objects() {
        let (db, t) = tenant();
        stored(&t);
        owner_reads(
            &db,
            t.tenant,
            "DELETE FROM vcon.tenant_lock RETURNING 'gone'",
        );
        let called = AtomicBool::new(false);
        PgCatalog::remove(&t.database, t.tenant, 10, || {
            called.store(true, SeqCst);
            objects_removed(&t);
            Ok(())
        })
        .expect("removed");
        assert!(called.load(SeqCst), "its objects are removed");
        assert_eq!(
            owner_reads(&db, t.tenant, "SELECT count(*) FROM vcon.vcon"),
            ["0"],
            "and its rows"
        );
    }

    #[test]
    fn a_removal_waits_for_a_write_that_holds_the_lock_row() {
        let (db, database) = database();
        let (tenant, _, catalog) = tenant_catalog(&database);
        let mut held = catalog.immediate().expect("a write");
        held.record(&entry("held"), time::OffsetDateTime::UNIX_EPOCH)
            .expect("the write holds the lock row");
        let (ended, end) = std::sync::mpsc::channel();
        let removing = database.clone();
        let remover = std::thread::spawn(move || {
            let removed = PgCatalog::remove(&removing, tenant, 10, || Ok(()));
            let _ = ended.send(());
            removed
        });
        let deadline = std::time::Instant::now() + PATIENCE;
        while owner_reads(&db, tenant, &waiters(None)) != ["1"] {
            assert!(
                std::time::Instant::now() < deadline,
                "the removal waits for the write"
            );
            std::thread::yield_now();
        }
        assert!(
            end.try_recv().is_err(),
            "the removal has not ended while the write holds the row"
        );
        held.commit().expect("the write commits");
        assert_eq!(
            remover.join().expect("the remover ends"),
            Ok(()),
            "then the removal ends"
        );
        assert!(
            !PgCatalog::present(&database)
                .expect("present")
                .contains(&tenant),
            "and the tenant is gone"
        );
    }

    // What must be refused.

    #[test]
    fn a_write_after_the_mark_is_refused_and_stores_nothing() {
        let (db, t) = tenant();
        stored(&t);
        PgCatalog::remove(&t.database, t.tenant, 10, || {
            let (found, body) = vcon("01a07da8-c2bb-83e5-b9a2-279e0d16bcb2", "late");
            assert!(
                t.store.create(&t.caller, &found, &body).is_err(),
                "a write after the mark is refused"
            );
            assert_eq!(
                owner_reads(&db, t.tenant, "SELECT count(*) FROM vcon.vcon"),
                ["1"],
                "and stores no vCon"
            );
            objects_removed(&t);
            Ok(())
        })
        .expect("removed");
    }

    #[test]
    fn a_removal_whose_objects_fail_keeps_the_rows_and_the_mark() {
        let (db, t) = tenant();
        stored(&t);
        assert_eq!(
            PgCatalog::remove(&t.database, t.tenant, 10, || Err(CatalogError::Io)),
            Err(CatalogError::Io),
            "the objects' error"
        );
        assert_eq!(mark(&db, &t), ["true"], "the lock row stays marked");
        assert!(
            present(&t),
            "so the tenant is present, for the next removal"
        );
        let read = t.store.get(&t.caller, a()).map(|s| s.body);
        let Err(e) = read else {
            panic!("a read of a tenant left marked is refused")
        };
        assert_ne!(e, StoreError::Damaged, "refused, not as damaged");
    }

    #[test]
    fn the_registry_s_id_is_refused_before_anything_is_removed() {
        let (_db, t) = tenant();
        let called = AtomicBool::new(false);
        assert_eq!(
            PgCatalog::remove(&t.database, REGISTRY, 10, || {
                called.store(true, SeqCst);
                Ok(())
            }),
            Err(CatalogError::NoTenant),
            "the registry is no tenant"
        );
        assert!(!called.load(SeqCst), "and no object is removed");
    }

    #[test]
    fn a_batch_of_no_rows_is_refused_after_the_objects() {
        let (db, t) = tenant();
        stored(&t);
        assert_eq!(
            PgCatalog::remove(&t.database, t.tenant, 0, || Ok(())),
            Err(CatalogError::Io),
            "remove_in's refusal of a batch of 0"
        );
        assert_eq!(
            mark(&db, &t),
            ["true"],
            "the tenant stays marked, refused to reads"
        );
    }
}