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
use std::{fmt::Debug, ops::Bound, sync::Arc};

use crate::{
    interpreter::{
        execution::{
            compute_context_field_with_separate_value,
            compute_fold_specific_field_with_separate_value, QueryCarrier,
        },
        hints::Range,
        Adapter, AsVertex, ContextIterator, ContextOutcomeIterator, InterpretedQuery, TaggedValue,
        VertexIterator,
    },
    ir::{
        ContextField, FieldRef, FieldValue, FoldSpecificField, IRQueryComponent, Operation, Type,
    },
};

use super::CandidateValue;

/// Indicates that a property's value is dependent on another value in the query.
///
/// If [`VertexInfo::dynamically_required_property()`](super::VertexInfo::dynamically_required_property)
/// is able to determine a value for the specified property, it returns
/// a [`DynamicallyResolvedValue`]. The specified property's value may be different
/// in different query results, but the way in which it varies can be determined programmatically
/// and can be resolved to a [`CandidateValue`] for each query result.
///
/// # Example
///
/// Consider the following query, which fetches emails where the sender also included
/// their own address in the receipients:
/// ```graphql
/// {
///     Email {
///         contents @output
///
///         sender {
///             address @tag(name: "sender")
///         }
///         recipient {
///             address @filter(op: "=", value: ["%sender"])
///         }
///     }
/// }
/// ```
///
/// A naïve implementation of resolving the `recipient` edge would resolve all recipients
/// for each email and rely on Trustfall to filter out recipient addresses that don't match
/// the sender's address. This implementation is valid, but can be made faster.
///
/// To improve performance, the implementation could avoid loading _all_ recipients and instead
/// only load the recipient that matches the sender's address (if any).
///
/// However, as the sender's address varies from email to email, its value must be resolved
/// dynamically, i.e. separately for each possible query result. Resolving the `recipient` edge
/// might then look like this:
/// ```rust
/// # use std::sync::Arc;
/// # use trustfall_core::{
/// #     ir::{EdgeParameters, FieldValue},
/// #     interpreter::{
/// #         Adapter, AsVertex, CandidateValue, ContextIterator, ContextOutcomeIterator,
/// #         ResolveEdgeInfo, ResolveInfo, VertexInfo, VertexIterator,
/// #     },
/// # };
/// # #[derive(Debug, Clone)]
/// # struct Vertex;
/// # struct EmailAdapter;
/// # impl<'a> Adapter<'a> for EmailAdapter {
/// #     type Vertex = Vertex;
/// #
/// #     fn resolve_starting_vertices(
/// #         &self,
/// #         edge_name: &Arc<str>,
/// #         parameters: &EdgeParameters,
/// #         resolve_info: &ResolveInfo,
/// #     ) -> VertexIterator<'a, Self::Vertex> {
/// #         todo!()
/// #     }
/// #
/// #     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> {
/// #         todo!()
/// #     }
/// #
/// #     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>> {
/// #         todo!()
/// #     }
/// #
/// #     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> {
/// #         todo!()
/// #     }
/// # }
/// #
/// # fn resolve_recipient_from_candidate_value<'a, V>(
/// #     vertex: &V,
/// #     candidate: CandidateValue<FieldValue>
/// # ) -> VertexIterator<'a, Vertex> {
/// #     todo!()
/// # }
/// #
/// # fn resolve_recipient_otherwise<'a, V>(
/// #     contexts: ContextIterator<'a, V>,
/// # ) -> ContextOutcomeIterator<'a, V, VertexIterator<'a, Vertex>> {
/// #     todo!()
/// # }
/// #
/// # impl EmailAdapter {
/// // Inside our adapter implementation:
/// // we use this method to resolve `recipient` edges.
/// fn resolve_recipient_edge<'a, V: AsVertex<Vertex> + 'a>(
///     &self,
///     contexts: ContextIterator<'a, V>,
///     resolve_info: &ResolveEdgeInfo,
/// ) -> ContextOutcomeIterator<'a, V, VertexIterator<'a, Vertex>> {
///     if let Some(dynamic_value) = resolve_info.destination().dynamically_required_property("address") {
///         // The query is looking for a specific recipient's address,
///         // so let's look it up directly.
///         dynamic_value.resolve_with(self, contexts, |vertex, candidate| {
///             resolve_recipient_from_candidate_value(vertex, candidate)
///         })
///     } else {
///         // No specific recipient address, use the general-case edge resolver logic.
///         resolve_recipient_otherwise(contexts)
///     }
/// }
/// # }
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DynamicallyResolvedValue<'a> {
    query: InterpretedQuery,
    resolve_on_component: &'a IRQueryComponent,
    field: &'a FieldRef,
    operation: Operation<(), ()>,
    initial_candidate: CandidateValue<FieldValue>,
}

macro_rules! compute_candidate_from_tagged_value {
    ($iterator:ident, $initial_candidate:ident, $candidate:ident, $value:ident, $blk:block) => {
        Box::new($iterator.map(move |(ctx, tagged_value)| {
            let mut $candidate = $initial_candidate.clone();
            match tagged_value {
                TaggedValue::NonexistentOptional => (ctx, $candidate),
                TaggedValue::Some($value) => {
                    {
                        $blk
                    }
                    (ctx, $candidate)
                }
            }
        }))
    };
}

macro_rules! resolve_fold_specific_field {
    ($iterator:ident, $initial_candidate:ident, $candidate:ident, $value:ident, $blk:block) => {
        Box::new($iterator.map(move |(ctx, tagged_value)| {
            let mut $candidate = $initial_candidate.clone();
            if let TaggedValue::Some($value) = tagged_value {
                $blk
            }
            (ctx, $candidate)
        }))
    };
}

impl<'a> DynamicallyResolvedValue<'a> {
    pub(super) fn new(
        query: InterpretedQuery,
        resolve_on_component: &'a IRQueryComponent,
        field: &'a FieldRef,
        operation: Operation<(), ()>,
        initial_candidate: CandidateValue<FieldValue>,
    ) -> Self {
        Self { query, resolve_on_component, field, operation, initial_candidate }
    }

    #[allow(dead_code)] // false-positive: dead in the bin target, not dead in the lib
    pub fn resolve<'vertex, AdapterT: Adapter<'vertex>, V: AsVertex<AdapterT::Vertex> + 'vertex>(
        self,
        adapter: &AdapterT,
        contexts: ContextIterator<'vertex, V>,
    ) -> ContextOutcomeIterator<'vertex, V, CandidateValue<FieldValue>> {
        match &self.field {
            FieldRef::ContextField(context_field) => {
                if context_field.vertex_id < self.resolve_on_component.root {
                    // We're inside at least one level of `@fold` relative to
                    // the origin of this tag.
                    //
                    // We'll have to grab the tag's value from the context directly.
                    let field_ref = self.field;
                    self.compute_candidate_from_tagged_value_with_imported_tags(field_ref, contexts)
                } else {
                    self.compute_candidate_from_tagged_value(context_field, adapter, contexts)
                }
            }
            FieldRef::FoldSpecificField(fold_field) => {
                // TODO cover this with tests
                if fold_field.fold_root_vid < self.resolve_on_component.root {
                    // We're inside at least one level of `@fold` relative to
                    // the origin of this tag.
                    //
                    // We'll have to grab the tag's value from the context directly.
                    let field_ref = self.field;
                    self.compute_candidate_from_tagged_value_with_imported_tags(field_ref, contexts)
                } else {
                    self.resolve_fold_specific_field(fold_field, contexts)
                }
            }
        }
    }

    #[allow(dead_code)] // false-positive: dead in the bin target, not dead in the lib
    pub fn resolve_with<
        'vertex,
        AdapterT: Adapter<'vertex>,
        V: AsVertex<AdapterT::Vertex> + 'vertex,
    >(
        self,
        adapter: &AdapterT,
        contexts: ContextIterator<'vertex, V>,
        mut neighbor_resolver: impl FnMut(
                &AdapterT::Vertex,
                CandidateValue<FieldValue>,
            ) -> VertexIterator<'vertex, AdapterT::Vertex>
            + 'vertex,
    ) -> ContextOutcomeIterator<'vertex, V, VertexIterator<'vertex, AdapterT::Vertex>> {
        Box::new(self.resolve(adapter, contexts).map(move |(ctx, candidate)| {
            let neighbors = match ctx.active_vertex.as_ref().and_then(AsVertex::as_vertex) {
                Some(vertex) => neighbor_resolver(vertex, candidate),
                None => Box::new(std::iter::empty()),
            };
            (ctx, neighbors)
        }))
    }

    fn compute_candidate_from_tagged_value<
        'vertex,
        AdapterT: Adapter<'vertex>,
        V: AsVertex<AdapterT::Vertex> + 'vertex,
    >(
        self,
        context_field: &'a ContextField,
        adapter: &AdapterT,
        contexts: ContextIterator<'vertex, V>,
    ) -> ContextOutcomeIterator<'vertex, V, CandidateValue<FieldValue>> {
        let mut carrier = QueryCarrier { query: Some(self.query) };
        let iterator = compute_context_field_with_separate_value(
            adapter,
            &mut carrier,
            self.resolve_on_component,
            context_field,
            contexts,
        );

        let field_name = context_field.field_name.clone();
        let field_type = context_field.field_type.clone();

        compute_candidate_from_operation(
            &self.operation,
            self.initial_candidate,
            field_name,
            field_type,
            iterator,
        )
    }

    fn compute_candidate_from_tagged_value_with_imported_tags<
        'vertex,
        VertexT: Debug + Clone + 'vertex,
    >(
        self,
        field_ref: &'a FieldRef,
        contexts: ContextIterator<'vertex, VertexT>,
    ) -> ContextOutcomeIterator<'vertex, VertexT, CandidateValue<FieldValue>> {
        let cloned_field_ref = field_ref.clone();
        let iterator = Box::new(contexts.map(move |ctx| {
            let value = ctx.imported_tags[&cloned_field_ref].clone();
            (ctx, value)
        }));
        let (field_name, field_type) = match field_ref {
            FieldRef::ContextField(c) => (c.field_name.clone(), c.field_type.clone()),
            FieldRef::FoldSpecificField(f) => {
                (f.kind.field_name().into(), f.kind.field_type().clone())
            }
        };
        compute_candidate_from_operation(
            &self.operation,
            self.initial_candidate,
            field_name,
            field_type,
            iterator,
        )
    }

    fn resolve_fold_specific_field<'vertex, VertexT: Debug + Clone + 'vertex>(
        self,
        fold_field: &'a FoldSpecificField,
        contexts: ContextIterator<'vertex, VertexT>,
    ) -> ContextOutcomeIterator<'vertex, VertexT, CandidateValue<FieldValue>> {
        let iterator = compute_fold_specific_field_with_separate_value(
            fold_field.fold_eid,
            &fold_field.kind,
            contexts,
        );
        let initial_candidate = self.initial_candidate;

        match &self.operation {
            Operation::Equals(_, _) => {
                resolve_fold_specific_field!(iterator, initial_candidate, candidate, value, {
                    candidate.intersect(CandidateValue::Single(value));
                })
            }
            Operation::NotEquals(_, _) => {
                resolve_fold_specific_field!(iterator, initial_candidate, candidate, value, {
                    candidate.exclude_single_value(&value);
                })
            }
            Operation::LessThan(_, _) => {
                resolve_fold_specific_field!(iterator, initial_candidate, candidate, value, {
                    candidate.intersect(CandidateValue::Range(Range::with_end(
                        Bound::Excluded(value),
                        false,
                    )));
                })
            }
            Operation::LessThanOrEqual(_, _) => {
                resolve_fold_specific_field!(iterator, initial_candidate, candidate, value, {
                    candidate.intersect(CandidateValue::Range(Range::with_end(
                        Bound::Included(value),
                        false,
                    )));
                })
            }
            Operation::GreaterThan(_, _) => {
                resolve_fold_specific_field!(iterator, initial_candidate, candidate, value, {
                    candidate.intersect(CandidateValue::Range(Range::with_start(
                        Bound::Excluded(value),
                        false,
                    )));
                })
            }
            Operation::GreaterThanOrEqual(_, _) => {
                resolve_fold_specific_field!(iterator, initial_candidate, candidate, value, {
                    candidate.intersect(CandidateValue::Range(Range::with_end(
                        Bound::Included(value),
                        false,
                    )));
                })
            }
            Operation::OneOf(_, _) => {
                let fold_field = fold_field.clone();
                resolve_fold_specific_field!(iterator, initial_candidate, candidate, value, {
                    let values = value
                        .as_slice()
                        .unwrap_or_else(|| {
                            panic!(
                                "\
field {fold_field:?} produced an invalid value when resolving @tag: {value:?}",
                            )
                        })
                        .to_vec();
                    candidate.intersect(CandidateValue::Multiple(values));
                })
            }
            _ => unreachable!(
                "unsupported 'operation' {:?} for tag {:?} in component {:?}",
                &self.operation, fold_field, self.resolve_on_component,
            ),
        }
    }
}

fn compute_candidate_from_operation<'vertex, Vertex: Debug + Clone + 'vertex>(
    operation: &Operation<(), ()>,
    initial_candidate: CandidateValue<FieldValue>,
    field_name: Arc<str>,
    field_type: Type,
    iterator: ContextOutcomeIterator<'vertex, Vertex, TaggedValue>,
) -> ContextOutcomeIterator<'vertex, Vertex, CandidateValue<FieldValue>> {
    match operation {
        Operation::Equals(_, _) => {
            compute_candidate_from_tagged_value!(iterator, initial_candidate, candidate, value, {
                candidate.intersect(CandidateValue::Single(value));
            })
        }
        Operation::NotEquals(_, _) => {
            compute_candidate_from_tagged_value!(iterator, initial_candidate, candidate, value, {
                candidate.exclude_single_value(&value);
            })
        }
        Operation::LessThan(_, _) => {
            compute_candidate_from_tagged_value!(iterator, initial_candidate, candidate, value, {
                candidate.intersect(CandidateValue::Range(Range::with_end(
                    Bound::Excluded(value),
                    true, // nullability is handled in the initial_candidate
                )));
            })
        }
        Operation::LessThanOrEqual(_, _) => {
            compute_candidate_from_tagged_value!(iterator, initial_candidate, candidate, value, {
                candidate.intersect(CandidateValue::Range(Range::with_end(
                    Bound::Included(value),
                    true, // nullability is handled in the initial_candidate
                )));
            })
        }
        Operation::GreaterThan(_, _) => {
            compute_candidate_from_tagged_value!(iterator, initial_candidate, candidate, value, {
                candidate.intersect(CandidateValue::Range(Range::with_start(
                    Bound::Excluded(value),
                    true, // nullability is handled in the initial_candidate
                )));
            })
        }
        Operation::GreaterThanOrEqual(_, _) => {
            compute_candidate_from_tagged_value!(iterator, initial_candidate, candidate, value, {
                candidate.intersect(CandidateValue::Range(Range::with_end(
                    Bound::Included(value),
                    true, // nullability is handled in the initial_candidate
                )));
            })
        }
        Operation::OneOf(_, _) => {
            compute_candidate_from_tagged_value!(iterator, initial_candidate, candidate, value, {
                let values = value
                    .as_slice()
                    .unwrap_or_else(|| {
                        panic!(
                            "\
field {} of type {} produced an invalid value when resolving @tag: {value:?}",
                            field_name, field_type,
                        )
                    })
                    .to_vec();
                candidate.intersect(CandidateValue::Multiple(values));
            })
        }
        _ => unreachable!("unsupported 'operation': {:?}", operation,),
    }
}