vantage-vista 2.6.0

Universal, schema-bearing data handle for the Vantage data framework
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
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
//! A Rhai `atomic {}` block lands every write it makes, or none.

use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;

use vantage_core::{Result, error};
use vantage_rhai::rhai::{Dynamic, EvalAltResult, Map, Scope};
use vantage_rhai::{Host, Limits};

use super::transactions::{
    FAILED_STATEMENT, PROBE_DEADLINE, Runner, TxFixture, TxTables, absent, ensure, present, run,
    writable,
};
use crate::rhai::{
    ATOMIC_ARM_TIMEOUT, ATOMIC_BLOCK_TIMEOUT, AtomicScope, AtomicVocab, DataVocab, ResolverCell,
    Stop, Terminals, Writes,
};
use crate::{Vista, VistaResolver};

const NESTED: &str = "atomic can't be nested";
/// Ends a hung block inside its probe's deadline, so it fails the probe
/// rather than the whole test.
const BLOCK_LIMIT: Duration = Duration::from_secs(1);
const ARM_BUDGET: Duration = Duration::from_millis(200);

/// Runs every `atomic` probe on fresh tables, one after another, under the
/// same budget and deadlines as [`check_transactions`](super::check_transactions),
/// then panics once, listing the probes that broke the contract. Scripts see
/// the tables as `a` and `b`, and the second datasource's
/// ([`fresh_other`](TxFixture::fresh_other)) as `c` and `d`, and run on a
/// blocking thread, the way a host runs them; reads "outside" go through the
/// unwrapped Vistas.
pub async fn check_atomic_rhai(fx: &impl TxFixture) {
    let mut runner = Runner::new();
    if !fx.supports_transactions() {
        if writable(fx).await {
            run(
                &mut runner,
                "direct_writes_land_and_are_reported",
                PROBE_DEADLINE,
                direct_writes_land_and_are_reported(fx),
            )
            .await;
        } else {
            run(
                &mut runner,
                "direct_reads_pass_through",
                PROBE_DEADLINE,
                direct_reads_pass_through(fx),
            )
            .await;
        }
        return runner.finish();
    }
    run(
        &mut runner,
        "atomic_block_commits",
        PROBE_DEADLINE,
        atomic_block_commits(fx),
    )
    .await;
    run(
        &mut runner,
        "a_throw_rolls_back_and_runs_the_arm",
        PROBE_DEADLINE,
        a_throw_rolls_back_and_runs_the_arm(fx),
    )
    .await;
    run(
        &mut runner,
        "a_throwing_arm_rethrows_the_first_error",
        PROBE_DEADLINE,
        a_throwing_arm_rethrows_the_first_error(fx),
    )
    .await;
    run(
        &mut runner,
        "return_inside_atomic_commits",
        PROBE_DEADLINE,
        return_inside_atomic_commits(fx),
    )
    .await;
    run(
        &mut runner,
        "a_handle_from_before_the_block_joins_it",
        PROBE_DEADLINE,
        a_handle_from_before_the_block_joins_it(fx),
    )
    .await;
    run(
        &mut runner,
        "a_handle_outlives_its_block",
        PROBE_DEADLINE,
        a_handle_outlives_its_block(fx),
    )
    .await;
    run(
        &mut runner,
        "a_failed_statement_fails_the_block",
        PROBE_DEADLINE,
        a_failed_statement_fails_the_block(fx),
    )
    .await;
    run(
        &mut runner,
        "nested_atomic_is_refused",
        PROBE_DEADLINE,
        nested_atomic_is_refused(fx),
    )
    .await;
    run(
        &mut runner,
        "two_databases_commit_together",
        PROBE_DEADLINE,
        two_databases_commit_together(fx),
    )
    .await;
    run(
        &mut runner,
        "a_throw_rolls_both_back",
        PROBE_DEADLINE,
        a_throw_rolls_both_back(fx),
    )
    .await;
    run(
        &mut runner,
        "committed_is_empty_when_nothing_landed",
        PROBE_DEADLINE,
        committed_is_empty_when_nothing_landed(fx),
    )
    .await;
    runner.finish();
}

async fn atomic_block_commits(fx: &impl TxFixture) -> Result<()> {
    let t = fx.fresh().await;
    let ran = eval(
        &t,
        r#"atomic {
            table("a").insert(#{ id: "x", n: 1 });
            table("b").insert(#{ id: "y", a_id: "x", n: 1 });
        }"#,
    )
    .await?;
    if let Err(e) = ran.out {
        return Err(error!(format!("the block throws `{e}`")));
    }
    present(&t.a, "x", "after the block").await?;
    present(&t.b, "y", "after the block").await
}

async fn a_throw_rolls_back_and_runs_the_arm(fx: &impl TxFixture) -> Result<()> {
    let t = fx.fresh().await;
    let ran = eval(
        &t,
        r#"let seen = ();
        atomic {
            table("a").insert(#{ id: "x", n: 1 });
            throw "stop";
        } rollback (e) {
            seen = e;
        }"#,
    )
    .await?;
    threw(&ran, "stop")?;
    ensure(
        ran.seen.as_deref() == Some("stop"),
        format!("the arm binds {:?}, not \"stop\"", ran.seen),
    )?;
    absent(&t.a, "x", "after the throw").await
}

async fn a_throwing_arm_rethrows_the_first_error(fx: &impl TxFixture) -> Result<()> {
    let t = fx.fresh().await;
    let ran = eval(
        &t,
        r#"atomic {
            table("a").insert(#{ id: "x", n: 1 });
            throw "stop";
        } rollback (e) {
            throw "arm";
        }"#,
    )
    .await?;
    threw(&ran, "stop")?;
    absent(&t.a, "x", "after the arm threw").await
}

async fn return_inside_atomic_commits(fx: &impl TxFixture) -> Result<()> {
    let t = fx.fresh().await;
    let ran = eval(
        &t,
        r#"fn f() {
            atomic {
                table("a").insert(#{ id: "x", n: 1 });
                return 7;
            }
        }
        f()"#,
    )
    .await?;
    match &ran.out {
        Ok(v) if v.as_int() == Ok(7) => {}
        Ok(v) => return Err(error!(format!("f() returns {v}, not 7"))),
        Err(e) => return Err(error!(format!("f() throws `{e}`, not returns 7"))),
    }
    present(&t.a, "x", "after the return").await
}

async fn a_handle_from_before_the_block_joins_it(fx: &impl TxFixture) -> Result<()> {
    let t = fx.fresh().await;
    let ran = eval(
        &t,
        r#"let t = table("a");
        atomic {
            t.insert(#{ id: "x", n: 1 });
            throw "stop";
        }"#,
    )
    .await?;
    threw(&ran, "stop")?;
    absent(&t.a, "x", "after the throw").await
}

/// The handle is made inside the block; read after it, it sees the commit.
async fn a_handle_outlives_its_block(fx: &impl TxFixture) -> Result<()> {
    let t = fx.fresh().await;
    let ran = eval(
        &t,
        r#"let h;
        atomic {
            h = table("a");
            h.insert(#{ id: "x", n: 1 });
        }
        h.get("x")"#,
    )
    .await?;
    let row = ran
        .out
        .map_err(|e| error!(format!("the read after the block throws `{e}`")))?;
    let n = row
        .clone()
        .try_cast::<Map>()
        .and_then(|row| row.get("n").and_then(|n| n.as_int().ok()));
    ensure(
        n == Some(1),
        format!("h.get(\"x\") after the block returns {row}, not a row with n = 1"),
    )?;
    present(&t.a, "x", "after the block").await
}

/// The body catches the failed insert and ends Ok, so only the commit can
/// fail the block.
async fn a_failed_statement_fails_the_block(fx: &impl TxFixture) -> Result<()> {
    let t = fx.fresh().await;
    let ran = eval(
        &t,
        r#"atomic {
            table("a").insert(#{ id: "x", n: 1 });
            try { table("a").insert(#{ id: "z", n: -1 }) } catch {}
        }"#,
    )
    .await?;
    let failed = matches!(&ran.out, Err(e) if e.contains(FAILED_STATEMENT));
    ensure(
        failed,
        format!("the block ends {:?}, not `{FAILED_STATEMENT}`", ran.out),
    )?;
    absent(&t.a, "x", "after the failed block").await
}

async fn nested_atomic_is_refused(fx: &impl TxFixture) -> Result<()> {
    let t = fx.fresh().await;
    let ran = eval(
        &t,
        r#"atomic {
            table("a").insert(#{ id: "x", n: 1 });
            atomic { 1 }
        }"#,
    )
    .await?;
    threw(&ran, NESTED)?;
    absent(&t.a, "x", "after the nested block").await
}

/// The block throws after writing directly: the write stays, and the block
/// reports its table once.
async fn direct_writes_land_and_are_reported(fx: &impl TxFixture) -> Result<()> {
    let t = fx.fresh().await;
    let ran = eval(
        &t,
        r#"atomic {
            table("a").insert(#{ id: "x", n: 1 });
            throw "stop";
        }"#,
    )
    .await?;
    threw(&ran, "stop")?;
    present(&t.a, "x", "after the throw, written directly").await?;
    let wanted = [vec![t.a.name().to_string()]];
    ensure(
        ran.unprotected == wanted,
        format!(
            "the block reports {:?} as unprotected, not {wanted:?}",
            ran.unprotected
        ),
    )
}

/// A read-only datasource without transactions: the block reads as outside,
/// and reports no table.
async fn direct_reads_pass_through(fx: &impl TxFixture) -> Result<()> {
    let t = fx.fresh().await;
    let outside = t.a.count().await?;
    let ran = eval(
        &t,
        r#"let seen = ();
        atomic {
            seen = table("a").count().to_string();
        }"#,
    )
    .await?;
    if let Err(e) = ran.out {
        return Err(error!(format!("the block throws `{e}`")));
    }
    ensure(
        ran.seen == Some(outside.to_string()),
        format!(
            "the block counts {:?} rows of {}, {outside} outside",
            ran.seen,
            t.a.name()
        ),
    )?;
    ensure(
        ran.unprotected.concat().is_empty(),
        format!(
            "a block that only reads reports {:?} as unprotected",
            ran.unprotected
        ),
    )
}

async fn two_databases_commit_together(fx: &impl TxFixture) -> Result<()> {
    let Some(o) = fx.fresh_other().await else {
        return Ok(());
    };
    let t = fx.fresh().await;
    let ran = eval_on(
        &t,
        Some(&o),
        r#"atomic {
            table("a").insert(#{ id: "x", n: 1 });
            table("c").insert(#{ id: "x", n: 1 });
        }"#,
    )
    .await?;
    if let Err(e) = ran.out {
        return Err(error!(format!("the block throws `{e}`")));
    }
    present(&t.a, "x", "after the block").await?;
    present(&o.a, "x", "after the block").await
}

async fn a_throw_rolls_both_back(fx: &impl TxFixture) -> Result<()> {
    let Some(o) = fx.fresh_other().await else {
        return Ok(());
    };
    let t = fx.fresh().await;
    let ran = eval_on(
        &t,
        Some(&o),
        r#"atomic {
            table("a").insert(#{ id: "x", n: 1 });
            table("c").insert(#{ id: "x", n: 1 });
            throw "stop";
        }"#,
    )
    .await?;
    threw(&ran, "stop")?;
    absent(&t.a, "x", "after the throw").await?;
    absent(&o.a, "x", "after the throw").await
}

/// A throw before the commit: no datasource committed, so the arm's
/// `committed` is an empty array.
async fn committed_is_empty_when_nothing_landed(fx: &impl TxFixture) -> Result<()> {
    let Some(o) = fx.fresh_other().await else {
        return Ok(());
    };
    let t = fx.fresh().await;
    let ran = eval_on(
        &t,
        Some(&o),
        r#"let seen = ();
        atomic {
            table("a").insert(#{ id: "x", n: 1 });
            table("c").insert(#{ id: "x", n: 1 });
            throw "stop";
        } rollback (e, committed) {
            seen = `${type_of(committed)} of ${committed.len()}`;
        }"#,
    )
    .await?;
    threw(&ran, "stop")?;
    ensure(
        ran.seen.as_deref() == Some("array of 0"),
        format!(
            "the arm's `committed` is {:?}, not an empty array",
            ran.seen
        ),
    )
}

/// What a script returned or threw, its `seen` variable as it left it, and
/// the tables each block reported written directly.
struct Ran {
    out: std::result::Result<Dynamic, String>,
    seen: Option<String>,
    unprotected: Vec<Vec<String>>,
}

async fn eval(t: &TxTables, script: &'static str) -> Result<Ran> {
    eval_on(t, None, script).await
}

/// Runs `script` over the tables, and `other`'s as `c` and `d`, on a
/// blocking thread, since table calls block on the runtime. Each run gets
/// its own cell and atomic scope.
async fn eval_on(t: &TxTables, other: Option<&TxTables>, script: &'static str) -> Result<Ran> {
    let mut tables = vec![("a", t.a.clone()), ("b", t.b.clone())];
    if let Some(o) = other {
        tables.extend([("c", o.a.clone()), ("d", o.b.clone())]);
    }
    tokio::task::spawn_blocking(move || {
        let unprotected = Arc::new(Mutex::new(Vec::new()));
        let host = host(tables, unprotected.clone());
        let mut scope = Scope::new();
        let out = host
            .engine()
            .eval_with_scope::<Dynamic>(&mut scope, script)
            .map_err(|e| message(&e));
        let unprotected =
            std::mem::take(&mut *unprotected.lock().unwrap_or_else(PoisonError::into_inner));
        Ran {
            out,
            seen: scope.get_value::<String>("seen"),
            unprotected,
        }
    })
    .await
    .map_err(|e| error!(format!("the script's thread failed: {e}")))
}

fn host(tables: Vec<(&'static str, Vista)>, unprotected: Arc<Mutex<Vec<Vec<String>>>>) -> Host {
    let base: Arc<dyn VistaResolver> = Arc::new(move |name: &str| {
        tables
            .iter()
            .find(|(n, _)| *n == name)
            .map(|(_, vista)| vista.clone())
            .ok_or_else(|| error!("no such table", name = name))
    });
    let cell = ResolverCell::new(base);
    let terminals = Terminals::ReadWrite {
        limit: None,
        writes: Writes::Allowed,
    };
    let scope = AtomicScope::new(cell.clone())
        .with_limit(BLOCK_LIMIT)
        .with_arm_budget(ARM_BUDGET)
        .on_unprotected(Arc::new(move |tables| {
            let mut reported = unprotected.lock().unwrap_or_else(PoisonError::into_inner);
            reported.push(tables.to_vec());
        }));
    let clock = scope.clock();
    Host::builder(Limits::background())
        .vocab(DataVocab::new(terminals).with_resolver(Arc::new(cell)))
        .vocab(AtomicVocab::new(scope))
        .vocab_fn(move |engine| {
            engine.on_progress(move |_| {
                clock.should_stop(false).map(|stop| {
                    Dynamic::from(match stop {
                        Stop::Cancelled => "cancelled",
                        Stop::BlockTimeout => ATOMIC_BLOCK_TIMEOUT,
                        Stop::ArmTimeout => ATOMIC_ARM_TIMEOUT,
                    })
                })
            });
        })
        .build()
}

/// What the script threw, else the error's text.
fn message(err: &EvalAltResult) -> String {
    match err {
        EvalAltResult::ErrorRuntime(value, _) => value.to_string(),
        other => other.to_string(),
    }
}

fn threw(ran: &Ran, wanted: &str) -> Result<()> {
    match &ran.out {
        Err(e) if e == wanted => Ok(()),
        Err(e) => Err(error!(format!("the script throws `{e}`, not `{wanted}`"))),
        Ok(v) => Err(error!(format!("the script returns {v}, not `{wanted}`"))),
    }
}