trustfall_core 0.8.1

The trustfall query engine, empowering you to query everything.
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
540
541
542
543
544
545
546
use std::sync::Arc;

use async_graphql_parser::types::{
    BaseType, FieldDefinition, InputValueDefinition, TypeDefinition, TypeKind,
};

use crate::{
    accessor_property, field_property,
    interpreter::{
        helpers::{resolve_neighbors_with, resolve_property_with},
        AsVertex, CandidateValue, ContextIterator, ContextOutcomeIterator, ResolveEdgeInfo,
        ResolveInfo, Typename, VertexInfo, VertexIterator,
    },
    ir::{EdgeParameters, FieldValue, TransparentValue, Type},
};

use super::Schema;

/// A Trustfall adapter for querying Trustfall schemas.
///
/// The schema matching this adapter is in the adjacent
/// [`schema.graphql` file](https://github.com/obi1kenobi/trustfall/blob/main/trustfall_core/src/schema/adapter/schema.graphql),
/// and is also available via the [`SchemaAdapter::schema_text()`] function.
///
/// # Example
///
/// Create the adapter for querying a given schema like so:
/// ```rust
/// # use trustfall_core::schema::{Schema, SchemaAdapter};
/// #
/// # fn main() {
/// let schema_text = include_str!("./schema.graphql");
/// let schema = Schema::parse(schema_text).expect("not a valid schema");
///
/// // Create an adapter that queries
/// // the schema in the local `schema.graphql` file.
/// # #[allow(unused_variables)]
/// let adapter = SchemaAdapter::new(&schema);
///
/// // Run queries using the adapter, etc.
/// # }
/// ```
///
/// Then you can query the contents of that schema.
/// For example, the following query asks for all vertex properties and their types:
/// ```graphql
/// query {
///     VertexType {
///         name @output
///
///         property {
///             property_name: name @output
///             property_type: type @output
///         }
///     }
/// }
/// ```
#[derive(Debug)]
pub struct SchemaAdapter<'a> {
    schema: &'a Schema,
}

impl<'a> SchemaAdapter<'a> {
    /// Make an adapter for querying the given Trustfall schema.
    #[inline(always)]
    pub fn new(schema_to_query: &'a Schema) -> Self {
        Self { schema: schema_to_query }
    }

    /// A schema that describes Trustfall schemas.
    ///
    /// Queries on this adapter must conform to this schema.
    pub fn schema_text() -> &'static str {
        include_str!("./schema.graphql")
    }
}

fn vertex_type_iter(
    schema: &Schema,
    vertex_type_name: Option<CandidateValue<FieldValue>>,
) -> VertexIterator<'_, SchemaVertex<'_>> {
    let root_query_type = schema.query_type_name();

    if let Some(CandidateValue::Single(FieldValue::String(name))) = vertex_type_name {
        let neighbors = schema
            .vertex_types
            .get(name.as_ref())
            .filter(move |v| v.name.node != root_query_type)
            .into_iter()
            .map(|defn| SchemaVertex::VertexType(VertexType::new(defn)));

        Box::new(neighbors)
    } else if let Some(CandidateValue::Multiple(possibilities)) = vertex_type_name {
        let neighbors = possibilities.into_iter().filter_map(move |name| {
            schema
                .vertex_types
                .get(name.as_arc_str().expect("vertex type name was not a string"))
                .and_then(move |defn| {
                    (defn.name.node != root_query_type)
                        .then(|| SchemaVertex::VertexType(VertexType::new(defn)))
                })
        });
        Box::new(neighbors)
    } else {
        Box::new(
            schema
                .vertex_types
                .values()
                .filter(move |v| v.name.node != root_query_type)
                .map(|v| SchemaVertex::VertexType(VertexType::new(v))),
        )
    }
}

fn entrypoints_iter(schema: &Schema) -> VertexIterator<'_, SchemaVertex<'_>> {
    Box::new(
        schema.query_type.fields.iter().map(|field| SchemaVertex::Edge(Edge::new(&field.node))),
    )
}

#[derive(Debug, Clone)]
pub enum SchemaVertex<'a> {
    VertexType(VertexType<'a>),
    Property(Property<'a>),
    Edge(Edge<'a>),
    EdgeParameter(EdgeParameter<'a>),
    Schema,
}

impl<'a> SchemaVertex<'a> {
    #[inline(always)]
    fn as_vertex_type(&self) -> Option<&VertexType<'a>> {
        match self {
            Self::VertexType(v) => Some(v),
            _ => None,
        }
    }

    #[inline(always)]
    fn as_property(&self) -> Option<&Property<'a>> {
        match self {
            Self::Property(p) => Some(p),
            _ => None,
        }
    }

    #[inline(always)]
    fn as_edge(&self) -> Option<&Edge<'a>> {
        match self {
            Self::Edge(e) => Some(e),
            _ => None,
        }
    }

    #[inline(always)]
    fn as_edge_parameter(&self) -> Option<&EdgeParameter<'a>> {
        match self {
            Self::EdgeParameter(e) => Some(e),
            _ => None,
        }
    }
}

impl Typename for SchemaVertex<'_> {
    #[inline(always)]
    fn typename(&self) -> &'static str {
        match self {
            SchemaVertex::VertexType(..) => "VertexType",
            SchemaVertex::Property(..) => "Property",
            SchemaVertex::Edge(..) => "Edge",
            SchemaVertex::EdgeParameter(..) => "EdgeParameter",
            SchemaVertex::Schema => "Schema",
        }
    }
}

#[derive(Debug, Clone)]
pub struct VertexType<'a> {
    defn: &'a TypeDefinition,
}

impl<'a> VertexType<'a> {
    #[inline(always)]
    fn new(defn: &'a TypeDefinition) -> Self {
        Self { defn }
    }

    #[inline(always)]
    fn name(&self) -> &'a str {
        self.defn.name.node.as_str()
    }

    #[inline(always)]
    fn docs(&self) -> Option<&'a str> {
        self.defn.description.as_ref().map(|x| x.node.as_str())
    }

    #[inline(always)]
    fn is_interface(&self) -> bool {
        matches!(self.defn.kind, TypeKind::Interface(..))
    }
}

#[derive(Debug, Clone)]
pub struct Property<'a> {
    parent: &'a TypeDefinition,
    name: &'a str,
    docs: Option<&'a str>,
    type_: Type,
}

impl<'a> Property<'a> {
    #[inline(always)]
    fn new(parent: &'a TypeDefinition, name: &'a str, docs: Option<&'a str>, type_: Type) -> Self {
        Self { parent, name, docs, type_ }
    }
}

#[derive(Debug, Clone)]
pub struct Edge<'a> {
    defn: &'a FieldDefinition,
}

impl<'a> Edge<'a> {
    #[inline(always)]
    fn new(defn: &'a FieldDefinition) -> Self {
        Self { defn }
    }

    #[inline(always)]
    fn name(&self) -> &'a str {
        &self.defn.name.node
    }

    #[inline(always)]
    fn docs(&self) -> Option<&'a str> {
        self.defn.description.as_ref().map(|x| x.node.as_str())
    }

    #[inline(always)]
    fn to_many(&self) -> bool {
        matches!(self.defn.ty.node.base, BaseType::List(..))
    }

    #[inline(always)]
    fn at_least_one(&self) -> bool {
        !self.defn.ty.node.nullable
    }
}

#[derive(Debug, Clone)]
pub struct EdgeParameter<'a> {
    defn: &'a InputValueDefinition,
}

impl<'a> EdgeParameter<'a> {
    #[inline(always)]
    fn new(defn: &'a InputValueDefinition) -> Self {
        Self { defn }
    }

    #[inline(always)]
    fn name(&self) -> &'a str {
        &self.defn.name.node
    }

    #[inline(always)]
    fn docs(&self) -> Option<&'a str> {
        self.defn.description.as_ref().map(|pos| pos.node.as_str())
    }

    #[inline(always)]
    fn type_(&self) -> String {
        self.defn.ty.node.to_string()
    }
}

impl<'a> crate::interpreter::Adapter<'a> for SchemaAdapter<'a> {
    type Vertex = SchemaVertex<'a>;

    fn resolve_starting_vertices(
        &self,
        edge_name: &Arc<str>,
        _parameters: &EdgeParameters,
        resolve_info: &ResolveInfo,
    ) -> VertexIterator<'a, Self::Vertex> {
        match edge_name.as_ref() {
            "VertexType" => {
                let name = resolve_info.statically_required_property("name");
                vertex_type_iter(self.schema, name)
            }
            "Entrypoint" => entrypoints_iter(self.schema),
            "Schema" => Box::new(std::iter::once(SchemaVertex::Schema)),
            _ => unreachable!("unexpected starting edge: {edge_name}"),
        }
    }

    fn resolve_property<V: AsVertex<Self::Vertex> + 'a>(
        &self,
        contexts: ContextIterator<'a, V>,
        type_name: &Arc<str>,
        property_name: &Arc<str>,
        _resolve_info: &ResolveInfo,
    ) -> ContextOutcomeIterator<'a, V, FieldValue> {
        if property_name.as_ref() == "__typename" {
            return resolve_property_with::<Self::Vertex, V>(contexts, |vertex| {
                vertex.typename().into()
            });
        }

        match type_name.as_ref() {
            "VertexType" => match property_name.as_ref() {
                "name" => resolve_property_with(contexts, accessor_property!(as_vertex_type, name)),
                "docs" => resolve_property_with(contexts, accessor_property!(as_vertex_type, docs)),
                "is_interface" => resolve_property_with(
                    contexts,
                    accessor_property!(as_vertex_type, is_interface),
                ),
                _ => unreachable!("unexpected property name on type {type_name}: {property_name}"),
            },
            "Property" => match property_name.as_ref() {
                "name" => resolve_property_with(contexts, field_property!(as_property, name)),
                "docs" => resolve_property_with(contexts, field_property!(as_property, docs)),
                "type" => resolve_property_with(
                    contexts,
                    field_property!(as_property, type_, { type_.to_string().into() }),
                ),
                _ => unreachable!("unexpected property name on type {type_name}: {property_name}"),
            },
            "Edge" => match property_name.as_ref() {
                "name" => resolve_property_with(contexts, accessor_property!(as_edge, name)),
                "docs" => resolve_property_with(contexts, accessor_property!(as_edge, docs)),
                "to_many" => resolve_property_with(contexts, accessor_property!(as_edge, to_many)),
                "at_least_one" => {
                    resolve_property_with(contexts, accessor_property!(as_edge, at_least_one))
                }
                _ => unreachable!("unexpected property name on type {type_name}: {property_name}"),
            },
            "EdgeParameter" => match property_name.as_ref() {
                "name" => {
                    resolve_property_with(contexts, accessor_property!(as_edge_parameter, name))
                }
                "docs" => {
                    resolve_property_with(contexts, accessor_property!(as_edge_parameter, docs))
                }
                "type" => {
                    resolve_property_with(contexts, accessor_property!(as_edge_parameter, type_))
                }
                "default" => resolve_property_with(contexts, |vertex| {
                    let vertex = vertex.as_edge_parameter().expect("not an EdgeParameter");
                    vertex
                        .defn
                        .default_value
                        .as_ref()
                        .map(|v| {
                            let value = &v.node;
                            value.clone().try_into().expect("failed to convert ConstValue")
                        })
                        .or_else(|| {
                            // Nullable edge parameters have an implicit default value of `null`.
                            vertex.defn.ty.node.nullable.then_some(FieldValue::NULL)
                        })
                        .map(|value| {
                            let transparent = TransparentValue::from(value);
                            serde_json::to_string(&transparent)
                                .expect("serde_json failed to serialize value")
                        })
                        .into()
                }),
                _ => unreachable!("unexpected property name on type {type_name}: {property_name}"),
            },
            _ => unreachable!("unexpected type name: {type_name}"),
        }
    }

    fn resolve_neighbors<V: AsVertex<Self::Vertex> + 'a>(
        &self,
        contexts: ContextIterator<'a, V>,
        type_name: &Arc<str>,
        edge_name: &Arc<str>,
        _parameters: &EdgeParameters,
        resolve_info: &ResolveEdgeInfo,
    ) -> ContextOutcomeIterator<'a, V, VertexIterator<'a, Self::Vertex>> {
        let schema = self.schema;
        match type_name.as_ref() {
            "VertexType" => match edge_name.as_ref() {
                "implements" => resolve_neighbors_with(contexts, move |vertex| {
                    resolve_vertex_type_implements_edge(schema, vertex)
                }),
                "implementer" => resolve_neighbors_with(contexts, move |vertex| {
                    resolve_vertex_type_implementer_edge(schema, vertex)
                }),
                "property" => resolve_neighbors_with(contexts, move |vertex| {
                    resolve_vertex_type_property_edge(schema, vertex)
                }),
                "edge" => resolve_neighbors_with(contexts, move |vertex| {
                    resolve_vertex_type_edge_edge(schema, vertex)
                }),
                _ => unreachable!("unexpected edge name on type {type_name}: {edge_name}"),
            },
            "Edge" => match edge_name.as_ref() {
                "target" => resolve_neighbors_with(contexts, move |vertex| {
                    let vertex = vertex.as_edge().expect("not an Edge");
                    let edge_type = Type::from_type(&vertex.defn.ty.node);
                    let target_type = edge_type.base_type();
                    Box::new(
                        schema
                            .vertex_types
                            .get(target_type)
                            .map(|defn| SchemaVertex::VertexType(VertexType::new(defn)))
                            .into_iter(),
                    )
                }),
                "parameter" => resolve_neighbors_with(contexts, move |vertex| {
                    let vertex = vertex.as_edge().expect("not an Edge");
                    let parameters = vertex.defn.arguments.as_slice();

                    Box::new(
                        parameters
                            .iter()
                            .map(|inp| SchemaVertex::EdgeParameter(EdgeParameter::new(&inp.node))),
                    )
                }),
                _ => unreachable!("unexpected edge name on type {type_name}: {edge_name}"),
            },
            "Schema" => match edge_name.as_ref() {
                "vertex_type" => {
                    let schema = self.schema;
                    let destination = resolve_info.destination();

                    // `.cloned()` to get rid of reference, so we can own it when we need to move it later
                    let vertex_type_name = destination.statically_required_property("name");

                    resolve_neighbors_with(contexts, move |_| {
                        // `.clone()` each time as we may have multiple "vertex_type" edges
                        vertex_type_iter(schema, vertex_type_name.clone())
                    })
                }
                "entrypoint" => {
                    let schema = self.schema;
                    resolve_neighbors_with(contexts, move |_| entrypoints_iter(schema))
                }
                _ => unreachable!("unexpected property name on type {type_name}: {edge_name}"),
            },
            _ => unreachable!("unexpected type name: {type_name}"),
        }
    }

    #[allow(unused_variables)]
    fn resolve_coercion<V: AsVertex<Self::Vertex> + 'a>(
        &self,
        contexts: ContextIterator<'a, V>,
        type_name: &Arc<str>,
        coerce_to_type: &Arc<str>,
        resolve_info: &ResolveInfo,
    ) -> ContextOutcomeIterator<'a, V, bool> {
        unreachable!("unexpected type coercion: {type_name} -> {coerce_to_type}")
    }
}

#[inline(always)]
fn resolve_vertex_type_implements_edge<'a>(
    schema: &'a Schema,
    vertex: &SchemaVertex<'a>,
) -> Box<dyn Iterator<Item = SchemaVertex<'a>> + 'a> {
    let vertex = vertex.as_vertex_type().expect("not a VertexType");
    let implements = super::get_vertex_type_implements(vertex.defn);

    Box::new(implements.iter().filter_map(move |x| {
        let implements_type = x.node.as_str();
        schema
            .vertex_types
            .get(implements_type)
            .map(|defn| SchemaVertex::VertexType(VertexType::new(defn)))
    }))
}

#[inline(always)]
fn resolve_vertex_type_implementer_edge<'a>(
    schema: &'a Schema,
    vertex: &SchemaVertex<'a>,
) -> Box<dyn Iterator<Item = SchemaVertex<'a>> + 'a> {
    let vertex = vertex.as_vertex_type().expect("not a VertexType");
    Box::new(
        schema
            .subtypes(vertex.defn.name.node.as_str())
            .expect("input type was not part of this schema")
            .filter_map(|implementer_type| {
                schema
                    .vertex_types
                    .get(implementer_type)
                    .map(|x| SchemaVertex::VertexType(VertexType::new(x)))
            }),
    )
}

#[inline(always)]
fn resolve_vertex_type_property_edge<'a>(
    schema: &'a Schema,
    vertex: &SchemaVertex<'a>,
) -> Box<dyn Iterator<Item = SchemaVertex<'a>> + 'a> {
    let vertex = vertex.as_vertex_type().expect("not a VertexType");
    let fields = super::get_vertex_type_fields(vertex.defn);

    let parent_defn = vertex.defn;
    Box::new(fields.iter().filter_map(move |p| {
        let field = &p.node;
        let field_ty = Type::from_type(&field.ty.node);
        let base_ty = field_ty.base_type();

        if !schema.vertex_types.contains_key(base_ty) {
            Some(SchemaVertex::Property(Property::new(
                parent_defn,
                field.name.node.as_str(),
                field.description.as_ref().map(|x| x.node.as_str()),
                field_ty,
            )))
        } else {
            None
        }
    }))
}

#[inline(always)]
fn resolve_vertex_type_edge_edge<'a>(
    schema: &'a Schema,
    vertex: &SchemaVertex<'a>,
) -> Box<dyn Iterator<Item = SchemaVertex<'a>> + 'a> {
    let vertex = vertex.as_vertex_type().expect("not a VertexType");
    let fields = super::get_vertex_type_fields(vertex.defn);

    Box::new(fields.iter().filter_map(move |p| {
        let field = &p.node;
        let field_ty = Type::from_type(&field.ty.node);
        let base_ty = field_ty.base_type();

        if schema.vertex_types.contains_key(base_ty) {
            Some(SchemaVertex::Edge(Edge::new(field)))
        } else {
            None
        }
    }))
}

#[cfg(test)]
mod tests;