vcon-server 0.4.16

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
//! A live test's database is its own, and is dropped when the test ends,
//! pass or fail. A server that tests ran on for hours once held thousands
//! of such databases: PostgreSQL keeps statistics for each in shared
//! memory, the container's `/dev/shm` filled, and every new connection
//! failed with `could not resize shared memory segment`. A test that is
//! killed drops nothing, so each new database first removes the ones old
//! enough that no running test can own them.

use super::names::{STALE_AFTER, is_stale, name_at};

const NOW: u64 = 1_800_000_000;

#[test]
fn a_name_holds_the_time_it_was_made_and_its_random_part() {
    assert_eq!(
        name_at(0x6b49_d200, &[0xab, 0xcd]),
        "vcon_t_6b49d200_abcd",
        "the prefix, the seconds in hexadecimal, the random bytes"
    );
}

#[test]
fn a_database_just_made_is_not_stale() {
    assert!(!is_stale(&name_at(NOW, &[1]), NOW), "made this second");
    assert!(
        !is_stale(&name_at(NOW - 60, &[1]), NOW),
        "a test a minute old may still run"
    );
}

#[test]
fn a_database_older_than_the_limit_is_stale() {
    assert!(
        is_stale(&name_at(NOW - STALE_AFTER - 1, &[1]), NOW),
        "one second past the limit"
    );
    assert!(is_stale(&name_at(1, &[1]), NOW), "from long ago");
}

#[test]
fn a_database_exactly_at_the_limit_is_kept() {
    assert!(
        !is_stale(&name_at(NOW - STALE_AFTER, &[1]), NOW),
        "the limit itself is not past it"
    );
}

#[test]
fn a_database_from_a_clock_ahead_of_this_one_is_kept() {
    assert!(
        !is_stale(&name_at(NOW + 3600, &[1]), NOW),
        "a time in the future is not an age"
    );
}

#[test]
fn a_database_that_is_not_a_tests_is_never_stale() {
    for name in [
        "vcon",
        "postgres",
        "template1",
        "vcon_t",
        "vcon_t_",
        "vcon_test_1_ab",
        "other_t_1_ab",
    ] {
        assert!(!is_stale(name, NOW), "{name} is not swept");
    }
}

#[test]
fn a_test_name_whose_time_does_not_parse_is_never_stale() {
    for name in [
        "vcon_t_zz_ab",
        "vcon_t__ab",
        "vcon_t_0123456789abcdef",
        "vcon_t_ffffffffffffffffff_ab",
        "vcon_t_-1_ab",
    ] {
        assert!(!is_stale(name, NOW), "{name} is left alone");
    }
}

#[test]
fn the_limit_is_longer_than_any_test_may_run() {
    // The test runner ends a test after `terminate-after` periods of
    // `period`; a database older than twice that is no running test's.
    let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.config/nextest.toml");
    let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
    let line = text
        .lines()
        .find(|l| l.starts_with("slow-timeout = "))
        .expect("the runner's deadline is set");
    let number_after = |key: &str| -> u64 {
        let rest = line.split(key).nth(1).expect("the key is there");
        rest.trim_start_matches([' ', '=', '"'])
            .chars()
            .take_while(char::is_ascii_digit)
            .collect::<String>()
            .parse()
            .unwrap_or_else(|e| panic!("{key} in {line}: {e}"))
    };
    let deadline = number_after("period") * number_after("terminate-after");
    assert!(
        STALE_AFTER >= 2 * deadline,
        "the sweep's limit of {STALE_AFTER} s against a test's deadline of {deadline} s"
    );
}

#[cfg(feature = "backend-tests")]
mod on_a_server {
    use std::time::{SystemTime, UNIX_EPOCH};

    use super::super::super::super::connect::Purpose;
    use super::super::super::live::{as_user, value};
    use super::super::live::{Db, connect, waiters};
    use super::super::names::{STALE_AFTER, name_at};

    /// The tester's connection to the server's own database.
    async fn tester() -> tokio_postgres::Client {
        let (_dir, settings) = as_user("vcon_tester");
        connect(&settings, Purpose::Connect)
            .await
            .expect("the tester connects")
            .client
    }

    async fn exists(client: &tokio_postgres::Client, name: &str) -> bool {
        value(
            client,
            &format!("SELECT count(*) FROM pg_database WHERE datname = '{name}'"),
        )
        .await
            == "1"
    }

    fn now() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("after 1970")
            .as_secs()
    }

    #[tokio::test]
    async fn a_tests_database_is_there_while_the_test_runs_and_gone_when_it_ends() {
        let tester = tester().await;
        let db = Db::migrated().await;
        let name = db.name.clone();
        assert!(
            exists(&tester, &name).await,
            "there while the test holds it"
        );
        drop(db);
        assert!(
            !exists(&tester, &name).await,
            "dropped with the test's guard"
        );
    }

    #[test]
    fn a_tests_database_is_gone_when_the_test_panics() {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("a runtime");
        let named = std::sync::Mutex::new(String::new());
        let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let db = runtime.block_on(Db::fresh());
            named.lock().expect("the name").clone_from(&db.name);
            assert!(
                db.name.is_empty(),
                "a test that fails while it holds a database"
            );
        }));
        assert!(failed.is_err(), "the test inside failed");
        let name = named.lock().expect("the name").clone();
        assert!(
            name.starts_with("vcon_t_"),
            "it had made a database: {name}"
        );
        let gone = runtime.block_on(async { !exists(&tester().await, &name).await });
        assert!(gone, "the guard dropped it while the panic unwound");
    }

    #[tokio::test]
    async fn a_database_with_open_connections_is_dropped_all_the_same() {
        let tester = tester().await;
        let db = Db::migrated().await;
        let name = db.name.clone();
        let held = db.app().await;
        drop(db);
        assert!(
            !exists(&tester, &name).await,
            "dropped though a connection was open"
        );
        assert!(
            held.simple_query("SELECT 1").await.is_err(),
            "the connection that was open was ended by the drop"
        );
    }

    #[tokio::test]
    async fn a_new_database_sweeps_one_a_killed_test_left_and_keeps_a_running_tests() {
        let tester = tester().await;
        let random: [u8; 6] = aws_lc_rs::rand::generate(&aws_lc_rs::rand::SystemRandom::new())
            .expect("random")
            .expose();
        let left = name_at(now() - STALE_AFTER - 60, &random);
        let running = name_at(now(), &random);
        for name in [&left, &running] {
            tester
                .batch_execute(&format!("CREATE DATABASE {name} OWNER vcon_owner"))
                .await
                .expect("a database made around the guard");
        }
        let db = Db::fresh().await;
        assert!(
            !exists(&tester, &left).await,
            "the one older than the limit was swept"
        );
        assert!(
            exists(&tester, &running).await,
            "the one another test could be running on was kept"
        );
        tester
            .batch_execute(&format!("DROP DATABASE {running} WITH (FORCE)"))
            .await
            .expect("this test removes what it made");
        drop(db);
    }

    #[tokio::test]
    async fn a_run_of_databases_leaves_none_behind() {
        let tester = tester().await;
        let mut names = Vec::new();
        for _ in 0..4 {
            let db = Db::fresh().await;
            names.push(db.name.clone());
        }
        let listed = names
            .iter()
            .map(|n| format!("'{n}'"))
            .collect::<Vec<_>>()
            .join(", ");
        assert_eq!(
            value(
                &tester,
                &format!("SELECT count(*) FROM pg_database WHERE datname IN ({listed})")
            )
            .await,
            "0",
            "each was dropped when its guard went out of scope"
        );
        assert_eq!(
            names
                .iter()
                .collect::<std::collections::BTreeSet<_>>()
                .len(),
            4,
            "and each had a name of its own"
        );
    }

    /// Asks `sql` up to fifty times, a tenth of a second apart, until its
    /// value is `want`.
    async fn within_five_seconds_of(
        client: &tokio_postgres::Client,
        sql: &str,
        want: &str,
    ) -> bool {
        for _ in 0..50 {
            if value(client, sql).await == want {
                return true;
            }
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        }
        false
    }

    // A test that waits until its one session waits for a lock counts the
    // sessions that wait. The tests of a run share a server: on
    // 2026-11-14 two such tests of the registry ran at the same moment,
    // each counted the other's waiting session too, neither saw exactly
    // one, and one of them ended at the lock timeout.

    #[tokio::test]
    async fn a_session_that_begins_to_wait_is_counted_by_a_transaction_already_open() {
        // The registry's tests count from the session that holds the
        // lock, inside its transaction. PostgreSQL keeps what a
        // transaction first read of the sessions (pg_stat_activity) to
        // the transaction's end, so a count made through that view does
        // not see a session that came after.
        let db = Db::fresh().await;
        let holder = db.admin().await;
        holder
            .batch_execute("BEGIN; SELECT pg_advisory_xact_lock(7)")
            .await
            .expect("holds the lock in a transaction");
        assert_eq!(
            value(&holder, &waiters(Some("advisory"))).await,
            "0",
            "no session waits yet"
        );
        let waiter = db.admin().await;
        let waiting = tokio::spawn(async move {
            waiter
                .batch_execute("BEGIN; SELECT pg_advisory_xact_lock(7); COMMIT")
                .await
        });
        assert!(
            within_five_seconds_of(&holder, &waiters(Some("advisory")), "1").await,
            "the session that came after the transaction's first count"
        );
        holder.batch_execute("COMMIT").await.expect("commits");
        waiting
            .await
            .expect("the task ends")
            .expect("the waiter got the lock");
    }

    #[tokio::test]
    async fn a_session_waiting_for_a_row_is_counted_and_is_not_an_advisory_wait() {
        let (here, other) = (Db::fresh().await, Db::fresh().await);
        let holder = here.admin().await;
        holder
            .batch_execute("CREATE TABLE held (n int); INSERT INTO held VALUES (1)")
            .await
            .expect("a table with a row");
        holder
            .batch_execute("BEGIN; SELECT n FROM held FOR UPDATE")
            .await
            .expect("holds the row");
        let waiter = here.admin().await;
        let waiting =
            tokio::spawn(
                async move { waiter.batch_execute("SELECT n FROM held FOR UPDATE").await },
            );
        let counting = here.admin().await;
        assert!(
            within_five_seconds_of(&counting, &waiters(None), "1").await,
            "the session that waits for the row"
        );
        assert_eq!(
            value(&counting, &waiters(Some("advisory"))).await,
            "0",
            "it waits for no advisory lock"
        );
        assert_eq!(
            value(&other.admin().await, &waiters(None)).await,
            "0",
            "and another database counts none"
        );
        holder.batch_execute("COMMIT").await.expect("commits");
        waiting
            .await
            .expect("the task ends")
            .expect("the waiter got the row");
    }

    #[tokio::test]
    async fn a_session_waiting_in_this_database_is_counted() {
        let db = Db::fresh().await;
        let holder = db.admin().await;
        holder
            .batch_execute("SELECT pg_advisory_lock(7)")
            .await
            .expect("holds the lock");
        let waiter = db.admin().await;
        let waiting =
            tokio::spawn(async move { waiter.batch_execute("SELECT pg_advisory_lock(7)").await });
        for kind in [Some("advisory"), None] {
            assert!(
                within_five_seconds_of(&holder, &waiters(kind), "1").await,
                "the one session that waits, by {kind:?}"
            );
        }
        assert_eq!(
            value(&holder, &waiters(Some("tuple"))).await,
            "0",
            "no session waits for a lock of another kind"
        );
        holder
            .batch_execute("SELECT pg_advisory_unlock(7)")
            .await
            .expect("gives the lock up");
        waiting
            .await
            .expect("the task ends")
            .expect("the waiter got the lock");
        assert_eq!(
            value(&holder, &waiters(None)).await,
            "0",
            "no session waits now"
        );
    }

    #[tokio::test]
    async fn a_session_waiting_in_another_database_is_not_counted() {
        let (here, other) = (Db::fresh().await, Db::fresh().await);
        let holder = other.admin().await;
        holder
            .batch_execute("SELECT pg_advisory_lock(7)")
            .await
            .expect("holds the lock");
        let waiter = other.admin().await;
        let waiting =
            tokio::spawn(async move { waiter.batch_execute("SELECT pg_advisory_lock(7)").await });
        assert!(
            within_five_seconds_of(&holder, &waiters(Some("advisory")), "1").await,
            "the other database has its one waiting session"
        );
        let mine = here.admin().await;
        for kind in [Some("advisory"), None] {
            assert_eq!(
                value(&mine, &waiters(kind)).await,
                "0",
                "this database has none, by {kind:?}"
            );
        }
        holder
            .batch_execute("SELECT pg_advisory_unlock(7)")
            .await
            .expect("gives the lock up");
        waiting
            .await
            .expect("the task ends")
            .expect("the waiter got the lock");
    }
}