graphersal 0.1.0

In-memory graph traversal engine modelled on Apache TinkerPop Gremlin, with a Rhai DSL, optimizer and GraphSON/GraphML I/O
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
//! The script side of `profile()` and `execute()`: [`TraversalMetrics`] as a Rhai value and
//! [`ScriptExecution`], the Rhai form of an [`Execution`](crate::Execution).
//!
//! Both are pure data in a script (`p.duration_ns`, `p.metrics[0].name`, `r.results`, `r.error`,
//! `r.profile`, `to_map()`, `to_json()`); only the session visualizer turns them into text
//! (`try_render_value`): a metrics value as the `profile()` text table, an execution as its
//! results followed by the table.

use std::collections::HashMap;

use compact_str::CompactString;
use rhai::Dynamic;

use crate::error::{BoxedTraverserError, DiagnosticError, TraverserError};
use crate::graph::schema::VisualizeFormat;
use crate::traversal::render::{RenderOptions, RenderedOutput};
use crate::traversal::source::ListItem;
use crate::value::{ElementProperty, PropertyMap};
use crate::{ExecOptions, ProfileType, StepLocation, TraversalMetrics};

/// The keys `execute(#{...})` accepts.
const EXECUTE_OPTION_KEYS: &str = "profile, profile_types";

/// The error of an [`ScriptExecution`] as data: everything a script, the playground or a binding
/// shows about it, computed once from the [`TraverserError`].
#[derive(Debug, Clone)]
struct ExecutionErrorData {
    /// The error and its root cause in one line, plain data: without the `Error: ` prefix and the
    /// plan frames of the rendered `diagnostic`.
    message: String,
    /// How to fix the query (the error's `help()`), when it has advice.
    help: Option<String>,
    /// The full diagnostic the CLI prints (message, plan frames, cause, help).
    diagnostic: String,
    /// The failing step, numbered like `Metrics.id`.
    location: Option<StepLocation>,
}

impl ExecutionErrorData {
    fn of(err: &TraverserError) -> Self {
        let root = err.root_cause();
        let message = if std::ptr::eq(root, err) {
            err.to_string()
        } else {
            format!("{err}: {root}")
        };
        Self {
            message,
            help: err.help(),
            diagnostic: crate::error::format_diagnostic(err),
            location: err.step_location(),
        }
    }

    /// `#{message, help?, step_id?, step_path?, diagnostic}`; an unknown part is absent.
    fn to_property(&self) -> ElementProperty {
        let mut map = PropertyMap::default();
        map.insert("message", text(&self.message));
        if let Some(help) = &self.help {
            map.insert("help", text(help));
        }
        if let Some(location) = &self.location {
            map.insert("step_id", text(&location.step_id));
            map.insert(
                "step_path",
                ElementProperty::Array(
                    location
                        .step_path
                        .iter()
                        .map(|entry| {
                            let mut step = PropertyMap::default();
                            step.insert("id", text(&entry.id));
                            step.insert("name", text(&entry.name));
                            ElementProperty::Object(Box::new(step))
                        })
                        .collect(),
                ),
            );
        }
        map.insert("diagnostic", text(&self.diagnostic));
        ElementProperty::Object(Box::new(map))
    }
}

fn text(value: &str) -> ElementProperty {
    ElementProperty::String(CompactString::new(value))
}

/// The result of the DSL terminal `execute()` / `execute(#{profile: true, profile_types: [..]})`:
/// the results `to_list()` would return, the error (`()` when the run succeeded) and the profile
/// (`()` unless requested; partial up to the failing step when the run failed).
///
/// `execute()` never throws: every error, also one in its options, is in `error`. Read it with
/// `r.results`, `r.error`, `r.profile`, `r.is_ok`, or as a whole with `to_map()` / `to_json()`.
/// As the final value of a session it renders as its results (in the traversal's visualizer
/// format) followed by the profile table; a failed execution renders as its diagnostic.
#[derive(Clone)]
pub struct ScriptExecution {
    items: Vec<ListItem>,
    error: Option<ExecutionErrorData>,
    profile: Option<TraversalMetrics>,
    /// Whether the run committed a change to the graph.
    mutated: bool,
    /// What the run changed (data, schema).
    changes: crate::graph::UnitChanges,
    /// The `with(..)` options of the traversal that ran, for its visualizer and display limits.
    options: HashMap<CompactString, ElementProperty>,
    /// Who a graph value among the results belongs to (the host or the script).
    origin: super::access::GraphOrigin,
}

impl ScriptExecution {
    pub(crate) fn new(
        items: Vec<ListItem>,
        error: Option<BoxedTraverserError>,
        profile: Option<TraversalMetrics>,
        options: HashMap<CompactString, ElementProperty>,
        origin: super::access::GraphOrigin,
    ) -> Self {
        Self {
            items,
            error: error.as_deref().map(ExecutionErrorData::of),
            profile,
            mutated: false,
            changes: crate::graph::UnitChanges::NONE,
            options,
            origin,
        }
    }

    /// Records whether and what the run changed (see [`crate::Execution::mutated`] and
    /// [`crate::Execution::changes`]).
    pub(crate) fn with_mutated(
        mut self,
        mutated: bool,
        changes: crate::graph::UnitChanges,
    ) -> Self {
        self.mutated = mutated;
        self.changes = changes;
        self
    }

    /// `r.changes`: what the run changed and kept, `#{data: bool, schema: bool, definitions:
    /// bool}` (see [`crate::Execution::changes`]).
    pub fn changes(&mut self) -> Dynamic {
        let mut map = rhai::Map::new();
        map.insert("data".into(), Dynamic::from_bool(self.changes.data));
        map.insert("schema".into(), Dynamic::from_bool(self.changes.schema));
        map.insert(
            "definitions".into(),
            Dynamic::from_bool(self.changes.definitions),
        );
        Dynamic::from_map(map)
    }

    /// `r.mutated`: whether the run changed the graph and kept the change (`false` for a
    /// read-only, failed or vetoed run). In a whole-script unit
    /// ([`eval_value_atomic`](crate::script::eval_value_atomic)) the change is part of the
    /// script's unit, which commits or rolls back at the end; see [`crate::Execution::mutated`].
    pub fn mutated(&mut self) -> bool {
        self.mutated
    }

    /// The results as script values (what `to_list()` returns).
    pub fn results(&mut self) -> rhai::Array {
        self.items
            .iter()
            .cloned()
            .map(|item| super::list_item_to_dynamic(item, &self.origin))
            .collect()
    }

    /// The error as a map `#{message, help, step_id, step_path, diagnostic}`, or `()`.
    pub fn error(&mut self) -> Dynamic {
        self.error
            .as_ref()
            .map(|err| super::element_property_to_dynamic(err.to_property()))
            .unwrap_or(Dynamic::UNIT)
    }

    /// The profile ([`TraversalMetrics`]), or `()` when none was requested.
    pub fn profile(&mut self) -> Dynamic {
        self.profile
            .clone()
            .map(Dynamic::from)
            .unwrap_or(Dynamic::UNIT)
    }

    /// Whether the run succeeded.
    pub fn is_ok(&mut self) -> bool {
        self.error.is_none()
    }

    /// The whole execution as one value tree: `{results, error, profile}` (`null` for an absent
    /// error or profile).
    fn to_property(&self) -> crate::error::TraverserResult<ElementProperty> {
        let mut map = PropertyMap::default();
        map.insert(
            "results",
            ElementProperty::Array(list_items_property(&self.items)?),
        );
        map.insert(
            "error",
            self.error
                .as_ref()
                .map_or(ElementProperty::Null, ExecutionErrorData::to_property),
        );
        map.insert(
            "profile",
            self.profile
                .as_ref()
                .map_or(ElementProperty::Null, TraversalMetrics::to_property),
        );
        Ok(ElementProperty::Object(Box::new(map)))
    }

    /// `to_map()`: the execution as a script map.
    pub fn to_map(&mut self) -> Dynamic {
        let mut map = rhai::Map::new();
        map.insert("results".into(), Dynamic::from(self.results()));
        map.insert("error".into(), self.error());
        map.insert(
            "profile".into(),
            self.profile
                .as_ref()
                .map(|p| super::element_property_to_dynamic(p.to_property()))
                .unwrap_or(Dynamic::UNIT),
        );
        map.insert("mutated".into(), Dynamic::from_bool(self.mutated));
        map.insert("changes".into(), self.changes());
        Dynamic::from_map(map)
    }

    /// `to_json()`: the execution as compact JSON text.
    pub fn to_json(&mut self) -> Result<String, Box<rhai::EvalAltResult>> {
        let value = self.to_property().map_err(super::script_error)?;
        Ok(crate::value::physical::to_json_text(&value).unwrap_or_default())
    }

    /// The session rendering: the results in the traversal's visualizer format (`fallback`
    /// when it has none) within the display limits, then the profile table. A failed execution
    /// is `Err` holding its diagnostic, followed by the partial profile table when there is one.
    pub(crate) fn render(
        &self,
        fallback: VisualizeFormat,
        base: &RenderOptions,
    ) -> Result<RenderedOutput, String> {
        if let Some(err) = &self.error {
            let mut text = err.diagnostic.clone();
            if let Some(profile) = &self.profile {
                text.push_str("\n\n");
                text.push_str(&profile.to_string());
            }
            return Err(text);
        }
        let mut rendered = self.render_results(fallback, base)?;
        if let Some(profile) = &self.profile {
            if !rendered.text.is_empty() {
                rendered.text.push_str("\n\n");
            }
            rendered.text.push_str(&profile.to_string());
        }
        Ok(rendered)
    }

    /// Renders only the results, as the session visualizer would: in the traversal's visualizer
    /// format (`fallback` when it has none, e.g. [`VisualizeFormat::Json`]), cut to the display
    /// limits (`base`, overridden by the traversal's own `render.max_rows` / `render.max_items`
    /// options). The profile is not part of it. A failed execution is `Err` holding its
    /// diagnostic.
    ///
    /// For hosts that show results and metrics separately (the browser playground).
    pub fn render_results(
        &self,
        fallback: VisualizeFormat,
        base: &RenderOptions,
    ) -> Result<RenderedOutput, String> {
        if let Some(err) = &self.error {
            return Err(err.diagnostic.clone());
        }
        let format = self
            .options
            .get("visualizer")
            .and_then(|value| value.as_str())
            .and_then(VisualizeFormat::from_name)
            .unwrap_or(fallback);
        let options = super::render_options_from(&self.options, base)
            .map_err(|err| crate::error::format_diagnostic(&err))?;
        let mut elements = list_items_property(&self.items)
            .map_err(|err| crate::error::format_diagnostic(&err))?;
        let more_rows = match options.max_rows {
            Some(n) if elements.len() > n => {
                elements.truncate(n);
                true
            }
            _ => false,
        };
        let rows_shown = elements.len();
        crate::traversal::source::render_elements(
            &elements, format, &options, rows_shown, more_rows,
        )
        .map_err(|err| crate::error::format_diagnostic(&err))
    }
}

/// The results as plain values (a graph value becomes its element lists).
fn list_items_property(items: &[ListItem]) -> crate::error::TraverserResult<Vec<ElementProperty>> {
    items
        .iter()
        .map(|item| match item {
            ListItem::Value(value) => Ok(value.clone()),
            ListItem::Graph(graph) => crate::graph::subgraph::graph_to_property(graph),
        })
        .collect()
}

/// Parses the options map of `execute(#{...})`: `profile` (bool) and `profile_types` (a list of
/// `ProfileType` values or their names, e.g. `[ProfileType.Memory]` or `["memory"]`; implies
/// `profile: true`). Unknown keys and malformed values are errors.
pub(crate) fn parse_execute_options(options: Dynamic) -> Result<ExecOptions, BoxedTraverserError> {
    let invalid = |key: &str, reason: String| {
        Box::new(TraverserError::InvalidOption {
            key: format!("execute.{key}"),
            reason,
        })
    };
    let Some(map) = options.read_lock::<rhai::Map>() else {
        return Err(invalid(
            "options",
            format!(
                "expected a map such as #{{profile: true}}, got {}",
                super::type_name_of(&options)
            ),
        ));
    };
    let mut profile: Option<bool> = None;
    let mut types = ProfileType::none();
    let mut types_given = false;
    for (key, value) in map.iter() {
        match key.as_str() {
            "profile" => match value.as_bool() {
                Ok(flag) => profile = Some(flag),
                Err(actual) => {
                    return Err(invalid(
                        "profile",
                        format!(
                            "expected true or false, got {}",
                            super::register::display_type_name(actual)
                        ),
                    ));
                }
            },
            "profile_types" => {
                let Some(list) = value.read_lock::<rhai::Array>() else {
                    return Err(invalid(
                        "profile_types",
                        format!(
                            "expected a list such as [ProfileType.Memory], got {}",
                            super::type_name_of(value)
                        ),
                    ));
                };
                for item in list.iter() {
                    types |= profile_type_of(item).ok_or_else(|| {
                        invalid(
                            "profile_types",
                            format!(
                                "unknown profile type {}; known: ProfileType.Memory (\"memory\")",
                                super::debug_value(item)
                            ),
                        )
                    })?;
                }
                types_given = true;
            }
            other => {
                return Err(invalid(
                    other,
                    format!("unknown option; execute() accepts {EXECUTE_OPTION_KEYS}"),
                ));
            }
        }
    }
    // `profile_types` asks for a profile; `profile: false` with types is a contradiction.
    match (profile, types_given) {
        (Some(false), true) => Err(invalid(
            "profile_types",
            "profile types need profiling: drop `profile: false` or the types".to_string(),
        )),
        (Some(true), _) | (None, true) => Ok(ExecOptions::profile(types)),
        (Some(false), false) | (None, false) => Ok(ExecOptions::new()),
    }
}

/// A `ProfileType` value, or the snake_case name of one (`"memory"`).
fn profile_type_of(value: &Dynamic) -> Option<ProfileType> {
    if let Some(flags) = value.read_lock::<ProfileType>() {
        return Some(*flags);
    }
    let name = value.read_lock::<rhai::ImmutableString>()?;
    match name.as_str() {
        "memory" | "Memory" => Some(ProfileType::Memory),
        _ => None,
    }
}

/// Registers [`TraversalMetrics`] and [`ScriptExecution`] with their getters and conversions.
pub(crate) fn register(registry: &mut super::register::Registry) {
    registry
        .register_type_with_name::<TraversalMetrics>("TraversalMetrics")
        .register_get("duration_ns", |m: &mut TraversalMetrics| {
            i64::try_from(m.duration().as_nanos()).unwrap_or(i64::MAX)
        })
        .register_get("metrics", |m: &mut TraversalMetrics| {
            metrics_field(m, "metrics")
        })
        .register_get("optimizer_rules_applied", |m: &mut TraversalMetrics| {
            m.optimizer_rules_applied()
                .iter()
                .map(|rule| Dynamic::from(rule.clone()))
                .collect::<rhai::Array>()
        })
        .register_fn_as(&["to_map", "toMap"], metrics_to_map)
        .register_fn_as(&["to_json", "toJson"], |m: &mut TraversalMetrics| {
            m.to_json()
        })
        .register_fn_as(
            &["to_table", "toTable", "to_string", "to_debug"],
            |m: &mut TraversalMetrics| m.to_string(),
        );

    registry
        .register_type_with_name::<ScriptExecution>("Execution")
        .register_get("results", ScriptExecution::results)
        .register_get("error", ScriptExecution::error)
        .register_get("profile", ScriptExecution::profile)
        .register_get("mutated", ScriptExecution::mutated)
        .register_get("changes", ScriptExecution::changes)
        .register_get("is_ok", ScriptExecution::is_ok)
        .register_get("isOk", ScriptExecution::is_ok)
        .register_fn_as(&["to_map", "toMap"], ScriptExecution::to_map)
        .register_fn_as(&["to_json", "toJson"], ScriptExecution::to_json)
        .register_fn("to_string", |e: &mut ScriptExecution| {
            e.render(VisualizeFormat::Auto, &RenderOptions::default())
                .map(|rendered| rendered.text)
                .unwrap_or_else(|diagnostic| diagnostic)
        })
        .register_fn("to_debug", |e: &mut ScriptExecution| {
            e.to_json().unwrap_or_else(|err| err.to_string())
        });
}

/// `to_map()` of a [`TraversalMetrics`]: the metrics as a script map (the shape of
/// [`TraversalMetrics::to_property`]). Public for hosts that convert script values further (the
/// Python binding).
pub fn metrics_to_map(metrics: &mut TraversalMetrics) -> Dynamic {
    super::element_property_to_dynamic(metrics.to_property())
}

/// One field of the map form of `metrics` (the getters share the map conversion, so a script
/// sees the same keys through `p.metrics` and `p.to_map().metrics`).
fn metrics_field(metrics: &TraversalMetrics, key: &str) -> Dynamic {
    match metrics.to_property() {
        ElementProperty::Object(map) => map
            .get(key)
            .cloned()
            .map(super::element_property_to_dynamic)
            .unwrap_or(Dynamic::UNIT),
        _ => Dynamic::UNIT,
    }
}