vantage-vista 0.6.20

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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! Conventional Rhai vocabulary over the type-erased [`Vista`].
//!
//! vantage-vista owns Rhai engine construction with a *backend-agnostic*
//! vocabulary: `table(name)` resolves a fresh target [`Vista`] through an
//! injected [`TargetResolver`], and a small set of builder verbs narrow it in
//! place. Backends layer their vendor-specific vocabulary (expression syntax,
//! `with_condition`) on top by overriding
//! [`TableShell::register_rhai_extensions`](crate::TableShell::register_rhai_extensions).
//!
//! This keeps Rhai out of vantage-table and lets engine-less datasources
//! (CSV/Mongo/REST) still script the conventional verbs — they only lose the
//! vendor expression syntax. Graceful degradation, not all-or-nothing.
//!
//! Everything here uses only [`Vista`]'s public API, preserving the one-way
//! `vantage-table → vantage-vista` dependency (Rhai is a leaf).

use std::sync::{Arc, Mutex};

use ciborium::Value as CborValue;
use rhai::{Dynamic, Engine, EvalAltResult, Map as RhaiMap, Scope};
use vantage_core::{Result, error};
use vantage_types::Record;

use super::convert::{dynamic_to_cbor, map_to_record, record_to_dynamic};
use crate::{sort::SortDirection, vista::Vista};

/// A [`Vista`] handle usable from Rhai: `Clone + Send + Sync + 'static` via
/// `Arc<Mutex<…>>`, with interior mutability so the builder verbs narrow it in
/// place and return the same handle for chaining. The inner `Option` lets
/// [`eval_ref_script`] move the finished `Vista` out even if the script kept
/// extra references.
///
/// `Arc<Mutex<…>>` (not `Rc<RefCell<…>>`) so the type satisfies Rhai's
/// `Send + Sync` bound when a consumer compiles Rhai with its `sync` feature —
/// `Vista` is itself `Send + Sync` (its `TableShell` is), so nothing is lost.
#[derive(Clone)]
pub struct RhaiVista(pub Arc<Mutex<Option<Vista>>>);

impl RhaiVista {
    /// Wrap a `Vista` for use inside a script.
    pub fn wrap(vista: Vista) -> Self {
        RhaiVista(Arc::new(Mutex::new(Some(vista))))
    }

    /// Apply an in-place mutation to the wrapped `Vista` and return the same
    /// handle for chaining. Backends call this from
    /// [`TableShell::register_rhai_extensions`](crate::TableShell::register_rhai_extensions)
    /// to add vendor verbs (e.g. `with_condition`) without re-deriving the
    /// borrow/`Option` bookkeeping.
    pub fn apply<F>(&self, f: F) -> std::result::Result<RhaiVista, Box<EvalAltResult>>
    where
        F: FnOnce(&mut Vista) -> Result<()>,
    {
        with_inner(self, f)
    }
}

/// Resolve a table name to a fresh, unconditioned target [`Vista`]. Injected by
/// the backend, which owns the by-name catalog; vantage-vista stays
/// backend-agnostic behind this boxed closure.
pub type TargetResolver = Arc<dyn Fn(&str) -> Result<Vista> + Send + Sync>;

/// Register the conventional `Vista` vocabulary onto `engine`.
///
/// Adds the `table(name)` constructor (backed by `resolver`) and the in-place
/// builder verbs (`with_id`, `add_condition_eq`, `add_order`, `add_search`,
/// `set_page_size`, `get_ref`). Each verb returns the same handle so scripts can
/// chain: `table("order").add_condition_eq("client", row.id).add_order("date", "desc")`.
pub fn register_conventional_onto(engine: &mut Engine, resolver: TargetResolver) {
    engine.register_type_with_name::<RhaiVista>("Vista");

    engine.register_fn(
        "table",
        move |name: &str| -> std::result::Result<RhaiVista, Box<EvalAltResult>> {
            let vista = resolver(name).map_err(to_rhai_err)?;
            Ok(RhaiVista::wrap(vista))
        },
    );

    engine.register_fn(
        "with_id",
        |v: &mut RhaiVista, id: Dynamic| -> std::result::Result<RhaiVista, Box<EvalAltResult>> {
            let cbor = dynamic_to_cbor(id)?;
            with_inner(v, |vista| vista.with_id(cbor).map(|_| ()))
        },
    );

    engine.register_fn(
        "add_condition_eq",
        |v: &mut RhaiVista,
         field: &str,
         value: Dynamic|
         -> std::result::Result<RhaiVista, Box<EvalAltResult>> {
            let cbor = dynamic_to_cbor(value)?;
            let field = field.to_string();
            with_inner(v, move |vista| vista.add_condition_eq(field, cbor))
        },
    );

    // `add_condition("col", "ne", value)` — the operator form. `op` is a
    // symbolic name (`ne`/`gt`/`in`/…); `in`/`not_in` take a list value. A
    // driver that can't push the operator returns Unimplemented, which surfaces
    // as a Rhai error the caller can handle (or gate on `can_filter_operators`).
    engine.register_fn(
        "add_condition",
        |v: &mut RhaiVista,
         field: &str,
         op: &str,
         value: Dynamic|
         -> std::result::Result<RhaiVista, Box<EvalAltResult>> {
            let op = parse_op(op)?;
            let cbor = dynamic_to_cbor(value)?;
            let field = field.to_string();
            with_inner(v, move |vista| vista.add_condition(field, op, cbor))
        },
    );

    engine.register_fn(
        "add_order",
        |v: &mut RhaiVista,
         column: &str,
         dir: &str|
         -> std::result::Result<RhaiVista, Box<EvalAltResult>> {
            let direction = parse_dir(dir)?;
            let column = column.to_string();
            with_inner(v, move |vista| vista.add_order(&column, direction))
        },
    );

    // Single-arg form defaults to ascending.
    engine.register_fn(
        "add_order",
        |v: &mut RhaiVista, column: &str| -> std::result::Result<RhaiVista, Box<EvalAltResult>> {
            let column = column.to_string();
            with_inner(v, move |vista| {
                vista.add_order(&column, SortDirection::Ascending)
            })
        },
    );

    engine.register_fn(
        "add_search",
        |v: &mut RhaiVista, text: &str| -> std::result::Result<RhaiVista, Box<EvalAltResult>> {
            let text = text.to_string();
            with_inner(v, move |vista| vista.add_search(text))
        },
    );

    engine.register_fn(
        "set_page_size",
        |v: &mut RhaiVista, size: i64| -> std::result::Result<RhaiVista, Box<EvalAltResult>> {
            if size <= 0 {
                return Err("set_page_size: page size must be > 0".into());
            }
            with_inner(v, move |vista| vista.set_page_size(size as usize))
        },
    );

    engine.register_fn(
        "get_ref",
        |v: &mut RhaiVista,
         relation: &str,
         row: RhaiMap|
         -> std::result::Result<RhaiVista, Box<EvalAltResult>> {
            let record = map_to_record(row)?;
            let guard = lock(v)?;
            let vista = guard
                .as_ref()
                .ok_or_else(|| Box::<EvalAltResult>::from("get_ref: vista already consumed"))?;
            let target = vista.get_ref(relation, &record).map_err(to_rhai_err)?;
            Ok(RhaiVista::wrap(target))
        },
    );
}

/// Evaluate a reference build-script and return the `Vista` it produced.
///
/// `engine` must already have the conventional vocabulary (via
/// [`register_conventional_onto`]) plus any vendor extensions registered. The
/// parent `row` is exposed to the script as the `row` map. The script's final
/// expression must evaluate to a `Vista` (e.g. `table("order").add_…(…)`).
pub fn eval_ref_script(engine: &Engine, code: &str, row: &Record<CborValue>) -> Result<Vista> {
    let mut scope = Scope::new();
    scope.push_dynamic("row", record_to_dynamic(row));

    let result: RhaiVista = engine
        .eval_with_scope(&mut scope, code)
        .map_err(|e| error!(format!("rhai reference build-script failed: {e}")))?;

    result
        .0
        .lock()
        .map_err(|_| error!("rhai reference build-script: result mutex poisoned"))?
        .take()
        .ok_or_else(|| error!("rhai reference build-script did not return a Vista"))
}

/// Evaluate a *modify* script against an already-built [`Vista`], applying extra
/// modifications in place and returning it. The vista is exposed to the script
/// as `self`.
///
/// Unlike [`eval_ref_script`] (which *builds* a target and returns it), this
/// runs the script for its side effects on `self` and ignores the script's
/// return value — the canonical "the YAML built the table, now a sneaky Rhai
/// tweak narrows it" use-case:
///
/// ```rhai
/// self.with_condition(ident("is_paying_client") == true)
/// ```
///
/// `engine` must already carry the conventional vocabulary (via
/// [`register_conventional_onto`]) plus any vendor extensions.
pub fn eval_modify_script(engine: &Engine, code: &str, vista: Vista) -> Result<Vista> {
    let handle = RhaiVista::wrap(vista);
    let mut scope = Scope::new();
    scope.push("self", handle.clone());

    engine
        .run_with_scope(&mut scope, code)
        .map_err(|e| error!(format!("rhai modify script failed: {e}")))?;

    // `take()` succeeds regardless of the scope's lingering `Arc` clone — it
    // empties the shared `Option`, not the `Arc`.
    handle
        .0
        .lock()
        .map_err(|_| error!("rhai modify script: result mutex poisoned"))?
        .take()
        .ok_or_else(|| error!("rhai modify script consumed `self`"))
}

/// A diorama augmentation *source* closure: given a master `row` and a freshly
/// resolved `base` detail [`Vista`], return the `base` narrowed for that row.
/// Hand-written Rust and Rhai both produce this same shape.
pub type AugmentSourceFn = Arc<dyn Fn(&Record<CborValue>, Vista) -> Result<Vista> + Send + Sync>;

/// Evaluate an augmentation *source* script: narrow a pre-built `base` Vista in
/// place using values from the master `row`, and return it. The base is exposed
/// to the script as `self`, the master row as `row` — so a one-liner like
///
/// ```rhai
/// self.add_condition_eq("key", row.key)
/// ```
///
/// is the canonical form. Mirrors [`eval_modify_script`] but with the parent row
/// in scope; the engine must already carry the conventional vocabulary (via
/// [`register_conventional_onto`]) plus any vendor extensions.
pub fn eval_augment_source(
    engine: &Engine,
    code: &str,
    base: Vista,
    row: &Record<CborValue>,
) -> Result<Vista> {
    let handle = RhaiVista::wrap(base);
    let mut scope = Scope::new();
    scope.push("self", handle.clone());
    scope.push_dynamic("row", record_to_dynamic(row));

    engine
        .run_with_scope(&mut scope, code)
        .map_err(|e| error!(format!("rhai augment source script failed: {e}")))?;

    handle
        .0
        .lock()
        .map_err(|_| error!("rhai augment source: result mutex poisoned"))?
        .take()
        .ok_or_else(|| error!("rhai augment source consumed `self`"))
}

/// A lazy-expression value closure: given the record as built so far, compute
/// one column value. This is the CBOR-carrier form of
/// `vantage_table::Table::with_lazy_expression`'s callback — driver factories
/// adapt it to their native value type when lowering a spec's `lazy:` script.
pub type LazyValueFn = Arc<dyn Fn(&Record<CborValue>) -> Result<CborValue> + Send + Sync>;

/// Evaluate a lazy-expression script for one record. The record as built so
/// far — source columns plus any lazy columns declared earlier — is exposed
/// as the `row` map; the script's final expression becomes the column's
/// value:
///
/// ```rhai
/// row.contents.split("\n").len() - 1
/// ```
pub fn eval_lazy_expression(
    engine: &Engine,
    code: &str,
    row: &Record<CborValue>,
) -> Result<CborValue> {
    let mut scope = Scope::new();
    scope.push_dynamic("row", record_to_dynamic(row));

    let result: Dynamic = engine
        .eval_with_scope(&mut scope, code)
        .map_err(|e| error!(format!("rhai lazy expression failed: {e}")))?;
    dynamic_to_cbor(result).map_err(|e| error!(format!("rhai lazy expression result: {e}")))
}

/// Build a reusable [`LazyValueFn`] from a Rhai `code` string. The engine is
/// plain — a lazy expression derives a value from `row`, it doesn't build
/// queries or fetch data, so no resolver or vendor vocabulary is needed.
pub fn lazy_value_closure(code: String) -> LazyValueFn {
    Arc::new(move |row: &Record<CborValue>| -> Result<CborValue> {
        let engine = Engine::new();
        eval_lazy_expression(&engine, code.as_str(), row)
    })
}

/// Build a reusable [`AugmentSourceFn`] from a Rhai `code` string and a
/// `resolver` for `table(name)`. Keeps all Rhai engine assembly inside
/// vantage-vista: a consumer (diorama's augmentation lowering) only flips the
/// `rhai` feature and calls this — it never touches the `rhai` crate directly.
///
/// The engine is rebuilt per call (cheap; `rhai`'s `sync` feature is not assumed,
/// so an [`Engine`] cannot be stored in a `Send + Sync` closure). Vendor
/// extensions come from the supplied `base`'s shell, so scripted narrowing can
/// use a backend's expression syntax when present.
pub fn augment_source_closure(resolver: TargetResolver, code: String) -> AugmentSourceFn {
    Arc::new(
        move |row: &Record<CborValue>, base: Vista| -> Result<Vista> {
            let mut engine = Engine::new();
            base.source.register_rhai_extensions(&mut engine);
            register_conventional_onto(&mut engine, resolver.clone());
            eval_augment_source(&engine, code.as_str(), base, row)
        },
    )
}

// ---- helpers --------------------------------------------------------------

type Guard<'a> = std::sync::MutexGuard<'a, Option<Vista>>;

fn lock(v: &RhaiVista) -> std::result::Result<Guard<'_>, Box<EvalAltResult>> {
    v.0.lock()
        .map_err(|_| Box::<EvalAltResult>::from("RhaiVista mutex poisoned"))
}

/// Apply an in-place mutation to the wrapped `Vista` and return the same handle
/// for chaining.
fn with_inner<F>(v: &RhaiVista, f: F) -> std::result::Result<RhaiVista, Box<EvalAltResult>>
where
    F: FnOnce(&mut Vista) -> Result<()>,
{
    {
        let mut guard = lock(v)?;
        let vista = guard
            .as_mut()
            .ok_or_else(|| Box::<EvalAltResult>::from("vista already consumed in script"))?;
        f(vista).map_err(to_rhai_err)?;
    }
    Ok(v.clone())
}

fn parse_dir(dir: &str) -> std::result::Result<SortDirection, Box<EvalAltResult>> {
    match dir.to_ascii_lowercase().as_str() {
        "asc" | "ascending" => Ok(SortDirection::Ascending),
        "desc" | "descending" => Ok(SortDirection::Descending),
        other => Err(format!("invalid sort direction '{other}' (expected 'asc' or 'desc')").into()),
    }
}

fn parse_op(op: &str) -> std::result::Result<crate::FilterOp, Box<EvalAltResult>> {
    use crate::FilterOp;
    Ok(match op.to_ascii_lowercase().as_str() {
        "eq" | "=" | "==" => FilterOp::Eq,
        "ne" | "!=" | "<>" => FilterOp::Ne,
        "gt" | ">" => FilterOp::Gt,
        "gte" | ">=" => FilterOp::Gte,
        "lt" | "<" => FilterOp::Lt,
        "lte" | "<=" => FilterOp::Lte,
        "in" | "in_set" => FilterOp::InSet,
        "not_in" | "not_in_set" | "nin" | "!in" => FilterOp::NotInSet,
        other => {
            return Err(format!(
                "invalid filter operator '{other}' (expected eq/ne/gt/gte/lt/lte/in/not_in)"
            )
            .into());
        }
    })
}

fn to_rhai_err(e: vantage_core::VantageError) -> Box<EvalAltResult> {
    Box::<EvalAltResult>::from(e.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Column, VistaMetadata, mocks::MockShell};
    use vantage_dataset::ReadableValueSet;

    fn cbor_text(s: &str) -> CborValue {
        CborValue::Text(s.into())
    }

    fn record(pairs: &[(&str, CborValue)]) -> Record<CborValue> {
        pairs
            .iter()
            .map(|(k, v)| ((*k).to_string(), v.clone()))
            .collect()
    }

    /// Fresh `users` Vista with three seeded rows (two VIPs). Built anew on each
    /// call so the resolver hands out an unconditioned target every time.
    fn users_vista() -> Vista {
        let source = MockShell::new()
            .with_record(
                "1",
                record(&[
                    ("id", cbor_text("1")),
                    ("name", cbor_text("Alice")),
                    ("vip_flag", CborValue::Bool(true)),
                ]),
            )
            .with_record(
                "2",
                record(&[
                    ("id", cbor_text("2")),
                    ("name", cbor_text("Bob")),
                    ("vip_flag", CborValue::Bool(false)),
                ]),
            )
            .with_record(
                "3",
                record(&[
                    ("id", cbor_text("3")),
                    ("name", cbor_text("Carol")),
                    ("vip_flag", CborValue::Bool(true)),
                ]),
            );
        let metadata = VistaMetadata::new()
            .with_column(Column::new("id", "String").with_flag("id"))
            .with_column(Column::new("name", "String").with_flag("title"))
            .with_column(Column::new("vip_flag", "bool"))
            .with_id_column("id");
        Vista::new("users", Box::new(source.with_metadata(metadata)))
    }

    fn engine() -> Engine {
        let resolver: TargetResolver = Arc::new(|name: &str| {
            if name == "users" {
                Ok(users_vista())
            } else {
                Err(error!("unknown table in test resolver", table = name))
            }
        });
        let mut engine = Engine::new();
        register_conventional_onto(&mut engine, resolver);
        engine
    }

    #[tokio::test]
    async fn script_narrows_target_with_literal_condition() {
        let row = record(&[("id", cbor_text("1"))]);
        let vista = eval_ref_script(
            &engine(),
            r#"table("users").add_condition_eq("vip_flag", true)"#,
            &row,
        )
        .unwrap();

        let rows = vista.list_values().await.unwrap();
        assert_eq!(rows.len(), 2, "only the two VIP rows should survive");
        assert!(rows.contains_key("1") && rows.contains_key("3"));
    }

    #[tokio::test]
    async fn add_condition_verb_dispatches_via_operator_name() {
        // `add_condition(.., "eq", ..)` routes through the same eq path as the
        // dedicated verb (MockShell only pushes equality) — proving the verb,
        // `parse_op`, and dispatch are wired.
        let row = record(&[("id", cbor_text("1"))]);
        let vista = eval_ref_script(
            &engine(),
            r#"table("users").add_condition("vip_flag", "eq", true)"#,
            &row,
        )
        .unwrap();
        let rows = vista.list_values().await.unwrap();
        assert_eq!(rows.len(), 2);
        assert!(rows.contains_key("1") && rows.contains_key("3"));
    }

    #[test]
    fn add_condition_rejects_unknown_operator() {
        let row = record(&[("id", cbor_text("1"))]);
        let result = eval_ref_script(
            &engine(),
            r#"table("users").add_condition("vip_flag", "wat", true)"#,
            &row,
        );
        match result {
            Ok(_) => panic!("expected an error for an unknown operator"),
            Err(e) => assert!(e.to_string().contains("invalid filter operator")),
        }
    }

    #[tokio::test]
    async fn script_can_read_the_parent_row() {
        let row = record(&[("id", cbor_text("3"))]);
        let vista = eval_ref_script(
            &engine(),
            r#"table("users").add_condition_eq("id", row.id)"#,
            &row,
        )
        .unwrap();

        let rows = vista.list_values().await.unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows["3"].get("name"), Some(&cbor_text("Carol")));
    }

    #[tokio::test]
    async fn modify_script_tweaks_an_existing_vista() {
        // The YAML built `users`; a post-build modify script narrows it in place
        // via `self`, with no parent row in scope.
        let vista = users_vista();
        let modified = eval_modify_script(
            &engine(),
            r#"self.add_condition_eq("vip_flag", true)"#,
            vista,
        )
        .unwrap();

        let rows = modified.list_values().await.unwrap();
        assert_eq!(rows.len(), 2);
        assert!(rows.contains_key("1") && rows.contains_key("3"));
    }

    #[test]
    fn unknown_table_surfaces_resolver_error() {
        let row = record(&[]);
        let err = match eval_ref_script(&engine(), r#"table("ghosts")"#, &row) {
            Ok(_) => panic!("expected the resolver to reject an unknown table"),
            Err(e) => e,
        };
        assert!(err.to_string().contains("unknown table"));
    }
}