ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! The two SEATS a flags vocabulary takes on the wire, and the asymmetry between them.
//!
//! A flags value has more than one reading worth publishing — the bit pattern, the strict text, the
//! name list, the two boolean sentences, the complement, one boolean per declared bit — and a
//! client wants a different one at a different moment. So the OUTPUT seat is an OBJECT
//! ([`FlagsView`]), where a vocabulary's is a scalar: an enum column has exactly one reading and an
//! object over it would be a fragment tax on every ordinary read, and a flags column has a dozen
//! and a scalar over it would pick one for everybody.
//!
//! The INPUT seat is the mirror image and therefore a SCALAR ([`FlagsInput`]). What an operand
//! needs is not a dozen readings but one VALUE written in whichever of three spellings the client's
//! own layer produces, and GraphQL has no input union to hold three shapes under one name — so the
//! wide door is a custom scalar whose parse takes a list, a number or the text form, and whose
//! render is the strict text form and nothing else. Wide in, strict out.
//!
//! # Both faces are GENERIC, and that is what keeps a declaration's emission small
//!
//! There is no per-declaration wire type here. [`FlagsView<F>`] and [`FlagsInput<F>`] are this
//! crate's own types, so `impl InputType for FlagsInput<F>` is a LOCAL impl at every `F` and
//! coherence is not in the conversation — the same argument
//! [`EnumFilter`](crate::EnumFilter)'s single generic face rests on. What varies per declaration is
//! read at RUNTIME off [`FlagsValue`]: the SDL name, and the bit table that becomes the per-flag
//! fields. So a declaration emits a `bitflags!` type and two constants, and the whole schema face
//! follows from those.
//!
//! # The names the two seats publish
//!
//! `TrackDisposition` for the object and `TrackDispositionInput` for the operand — one word apart,
//! derived from [`FlagsValue::GRAPHQL_NAME`] and never spelled twice. They CANNOT share a name:
//! async-graphql's registry holds one entry per name, and an object and a scalar under one word is
//! the collision `Registry::create_type` panics on.

use crate::flags::{self, FlagsValue};

#[cfg(all(test, feature = "async-graphql"))]
mod tests;

/// ONE OPERAND of a flags vocabulary, on its way in.
///
/// The wire form every seat of [`FlagsFilter`](crate::FlagsFilter) takes and the type
/// [`ToGraphqlInput`](crate::ToGraphqlInput) crosses a declared flags type through. It is a
/// transparent carrier: it holds the value and exists to own the wire face, because the value's own
/// type is a declaring crate's and cannot carry this crate's parse.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[repr(transparent)]
pub struct FlagsInput<F>(F);

impl<F> FlagsInput<F> {
  /// Carry a value onto the wire.
  #[inline]
  pub const fn new(value: F) -> Self {
    Self(value)
  }

  /// The value, borrowed.
  #[inline]
  pub const fn get(&self) -> &F {
    &self.0
  }

  /// The value, taken.
  #[inline]
  pub fn into_inner(self) -> F {
    self.0
  }
}

impl<F> From<F> for FlagsInput<F> {
  #[inline]
  fn from(value: F) -> Self {
    Self(value)
  }
}

/// The SDL name of the operand seat — the vocabulary's own word with `Input` behind it.
#[inline]
#[must_use]
pub fn input_name<F: FlagsValue>() -> String {
  format!("{}Input", F::GRAPHQL_NAME)
}

/// What the operand scalar's description tells a client: the three spellings, and the vocabulary.
///
/// Assembled from [`flags::vocabulary`], so the words a schema advertises and the words a refusal
/// quotes back are one list.
#[must_use]
pub fn input_description<F: FlagsValue>() -> String {
  format!(
    "A set of `{name}` flags, written any of three ways: a LIST of flag words \
     (`[\"DEFAULT\", \"FORCED\"]`), an INTEGER bit pattern (`3`), or the TEXT form — flag words \
     and `0x…` tokens separated by `|` (`\"DEFAULT | FORCED\"`), of which a single word is the \
     one-element case. A bit outside the declared set is refused rather than truncated, in every \
     form. Rendered back as the text form. {vocabulary}.",
    name = F::GRAPHQL_NAME,
    vocabulary = flags::vocabulary::<F>()
  )
}

/// One flags value on its way OUT — the OBJECT face, over every reading a bit set has.
///
/// A `Copy` carrier over the value, so a derived answer — `complement`, `union(other)` — is handed
/// to a nested selection without borrowing anything.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[repr(transparent)]
pub struct FlagsView<F>(F);

impl<F> FlagsView<F> {
  /// Show a value.
  #[inline]
  pub const fn new(value: F) -> Self {
    Self(value)
  }

  /// The value, borrowed.
  #[inline]
  pub const fn get(&self) -> &F {
    &self.0
  }

  /// The value, taken.
  #[inline]
  pub fn into_inner(self) -> F {
    self.0
  }
}

impl<F> From<F> for FlagsView<F> {
  #[inline]
  fn from(value: F) -> Self {
    Self(value)
  }
}

/// Every field the object face publishes that is NOT a per-flag boolean, in the order a schema
/// lists them.
///
/// The three READINGS first, then the two SENTENCES, then the derivations — which is the order a
/// reader wants them in, and the order the SDL is rendered in. The per-flag fan is appended after
/// these, so a vocabulary's own words sit together at the end rather than interleaved with the
/// framework's.
///
/// What is deliberately ABSENT is stated as a fact of the face: no constructor (`empty`, `all`,
/// `fromBits`), no `iter`/`iterNames`, and no operator trait spellings. A wire face answers
/// questions about the value in hand; minting a new one is the input seat's job, and an iterator is
/// `names` under a shape GraphQL has no use for.
pub const FIXED_FIELDS: [&str; 11] = [
  "bits",
  "text",
  "names",
  "isEmpty",
  "isAll",
  "complement",
  "contains",
  "intersects",
  "intersection",
  "union",
  "difference",
  // `symmetricDifference` is the twelfth and lives in `SYMMETRIC_DIFFERENCE`, because an array
  // literal of twelve reads worse than eleven plus the one whose name is long enough to be its own
  // line. Both are spent by one iterator below.
];

/// The sixth derivation, kept out of [`FIXED_FIELDS`] only so that array reads as a column.
pub const SYMMETRIC_DIFFERENCE: &str = "symmetricDifference";

/// The argument the six unary methods take — one operand, through the wide door.
pub const OPERAND: &str = "other";

/// Every fixed field, in schema order.
pub fn fixed_fields() -> impl Iterator<Item = &'static str> {
  FIXED_FIELDS
    .into_iter()
    .chain(std::iter::once(SYMMETRIC_DIFFERENCE))
}

/// The four fields that answer with the OBJECT again — the ones a selection may nest into.
///
/// `complement` takes no operand and the other three take one; what they share is the return, which
/// is what a caller of this list is asking about.
pub const SELF_RETURNING: [&str; 4] = [
  "complement",
  "intersection",
  "union",
  "difference",
  // …and `symmetricDifference`, which [`is_self_returning`] adds.
];

/// Whether a field answers with the object face again.
#[must_use]
pub fn is_self_returning(field: &str) -> bool {
  SELF_RETURNING.contains(&field) || field == SYMMETRIC_DIFFERENCE
}

/// The value one self-returning field derives, or [`None`] where the field is not one.
///
/// The WHOLE derivation table in one function, so the schema's field list and the resolver's
/// answers cannot come to disagree about what a word means. Every arm is `bitflags`' own operator —
/// this crate invents no set algebra.
#[must_use]
pub fn derive<F: FlagsValue>(value: F, field: &str, operand: F) -> Option<F> {
  match field {
    "complement" => Some(value.complement()),
    "intersection" => Some(value.intersection(operand)),
    "union" => Some(value.union(operand)),
    "difference" => Some(value.difference(operand)),
    _ if field == SYMMETRIC_DIFFERENCE => Some(value.symmetric_difference(operand)),
    _ => None,
  }
}

/// The two PREDICATES a caller asks with an operand, answered — or [`None`] where the field is not
/// one of them.
#[must_use]
pub fn predicate<F: FlagsValue>(value: F, field: &str, operand: F) -> Option<bool> {
  match field {
    "contains" => Some(value.contains(operand)),
    "intersects" => Some(value.intersects(operand)),
    _ => None,
  }
}

#[cfg(feature = "async-graphql")]
mod wire {
  use std::borrow::Cow;

  use bitflags::parser::ParseHex as _;

  use super::{
    FlagsInput, FlagsValue, FlagsView, OPERAND, derive, fixed_fields, flags, input_description,
    input_name, is_self_returning, predicate,
  };
  use crate::graphql::ToGraphqlOutput;

  /// The operand's PARSE — the wide door, and the whole grammar in one function so that a value
  /// which validates is a value which parses.
  ///
  /// Three forms and no fourth. A GraphQL enum literal is NOT among them: async-graphql renders an
  /// unquoted word as [`async_graphql::Value::Enum`], and accepting it here would be a fourth door
  /// onto a grammar the text form already covers with quotes — so it is refused, naming the three.
  /// The full expression grammar (`DEFAULT | ~FORCED`) is a separate design and is not this door.
  fn read<F: FlagsValue>(value: &async_graphql::Value) -> Result<F, String> {
    match value {
      // ① the LIST of flag words.
      async_graphql::Value::List(items) => {
        let mut words = Vec::with_capacity(items.len());
        for item in items {
          let async_graphql::Value::String(word) = item else {
            return Err(format!(
              "the list form of a `{}` operand carries flag words as STRINGS — `{}` is not one. \
               {}",
              F::GRAPHQL_NAME,
              item,
              flags::vocabulary::<F>()
            ));
          };
          words.push(word.as_str());
        }
        flags::of_words::<F>(words).map_err(|refused| refusal::<F>(&refused))
      }
      // ② the INTEGER bit pattern. It arrives as JSON, so the width check is this door's: a
      // number outside the vocabulary's own width is refused HERE rather than wrapping into a
      // pattern the declaration never wrote.
      async_graphql::Value::Number(number) => {
        let Some(bits) = number.as_u64() else {
          return Err(format!(
            "the integer form of a `{}` operand is a NON-NEGATIVE whole number — `{number}` is \
             not one. {}",
            F::GRAPHQL_NAME,
            flags::vocabulary::<F>()
          ));
        };
        // THROUGH HEX, and that is the only conversion the bound supplies. `Bits` is an
        // associated type with no numeric bound of its own — closing it would shut out a
        // hand-written implementer over a width this crate never named — so what is in hand is
        // `ParseHex`, and rendering the JSON integer as hex and reading it back IS the range check
        // this door owes: a number past the declared width fails the parse rather than wrapping
        // into a pattern the declaration never wrote.
        let widened =
          <F as bitflags::Flags>::Bits::parse_hex(&format!("{bits:x}")).map_err(|_| {
            format!(
              "`{bits}` does not fit the width `{}` is declared at. {}",
              F::GRAPHQL_NAME,
              flags::vocabulary::<F>()
            )
          })?;
        flags::of_bits::<F>(widened).map_err(|refused| refusal::<F>(&refused))
      }
      // ③ the TEXT form, of which a single word is the one-element case.
      async_graphql::Value::String(text) => {
        flags::of_text::<F>(text).map_err(|refused| refusal::<F>(&refused))
      }
      other => Err(format!(
        "a `{}` operand is a LIST of flag words, an INTEGER bit pattern, or the TEXT form — `{}` \
         is none of the three. {}",
        F::GRAPHQL_NAME,
        other,
        flags::vocabulary::<F>()
      )),
    }
  }

  /// One refusal, as a client reads it: what was refused, and the whole legal set beside it.
  ///
  /// Assembled HERE rather than inside [`flags::UnknownFlag`] for that type's own reason — the
  /// vocabulary belongs to the type being parsed into, and this is the one place both halves are in
  /// hand.
  fn refusal<F: FlagsValue>(refused: &flags::UnknownFlag) -> String {
    format!("{refused}. {}", flags::vocabulary::<F>())
  }

  impl<F: FlagsValue> async_graphql::InputType for FlagsInput<F> {
    type RawValueType = Self;

    fn type_name() -> Cow<'static, str> {
      Cow::Owned(input_name::<F>())
    }

    fn create_type_info(registry: &mut async_graphql::registry::Registry) -> String {
      registry.create_input_type::<Self, _>(async_graphql::registry::MetaTypeId::Scalar, |_| {
        async_graphql::registry::MetaType::Scalar {
          name: input_name::<F>(),
          description: Some(input_description::<F>()),
          // NO document-level validator, and the absence is a RULING rather than an oversight.
          //
          // `is_valid` is a predicate: it answers yes or no and async-graphql refuses the document
          // with its own sentence — *Invalid value for argument …, expected type …*. That sentence
          // is exactly what this seat must not answer with. A wide door's refusal is its
          // documentation — the bit that is not declared, and the whole legal mask beside it — and a
          // boolean has nowhere to carry either.
          //
          // So the WHOLE grammar is `parse`'s, in both paths a value can arrive by: a literal in
          // the document reaches it at execution, and a variable reaches it at coercion. What is
          // given up is the phase a bad literal is caught in, and nothing else — the value is
          // refused either way, and only here is the reader told which bit and which words.
          is_valid: None,
          visible: None,
          inaccessible: false,
          tags: Vec::new(),
          specified_by_url: None,
          directive_invocations: Vec::new(),
          requires_scopes: Vec::new(),
        }
      })
    }

    fn parse(value: Option<async_graphql::Value>) -> async_graphql::InputValueResult<Self> {
      let value = value.unwrap_or_default();
      match read::<F>(&value) {
        Ok(parsed) => Ok(Self(parsed)),
        Err(sentence) => Err(async_graphql::InputValueError::custom(sentence)),
      }
    }

    /// The STRICT form, and the only one this seat writes: a client may send three spellings and
    /// reads one back, which is what makes a round trip through this scalar canonical.
    fn to_value(&self) -> async_graphql::Value {
      async_graphql::Value::String(flags::text(&self.0).as_str().to_owned())
    }

    #[inline]
    fn as_raw_value(&self) -> Option<&Self::RawValueType> {
      Some(self)
    }
  }

  /// One field's registry entry, with the arguments it takes.
  fn field(
    name: &str,
    ty: String,
    args: async_graphql::indexmap::IndexMap<String, async_graphql::registry::MetaInputValue>,
  ) -> async_graphql::registry::MetaField {
    async_graphql::registry::MetaField {
      name: name.to_owned(),
      description: None,
      args,
      ty,
      deprecation: async_graphql::registry::Deprecation::NoDeprecated,
      cache_control: async_graphql::CacheControl::default(),
      external: false,
      requires: None,
      provides: None,
      visible: None,
      shareable: false,
      inaccessible: false,
      tags: Vec::new(),
      override_from: None,
      compute_complexity: None,
      directive_invocations: Vec::new(),
      requires_scopes: Vec::new(),
    }
  }

  /// The ONE argument the six unary methods take, registered through the operand seat — so the
  /// three spellings a filter accepts are the three a method accepts, from one type.
  fn operand_argument<F: FlagsValue>(
    registry: &mut async_graphql::registry::Registry,
  ) -> async_graphql::indexmap::IndexMap<String, async_graphql::registry::MetaInputValue> {
    let mut args = async_graphql::indexmap::IndexMap::new();
    args.insert(
      OPERAND.to_owned(),
      async_graphql::registry::MetaInputValue {
        name: OPERAND.to_owned(),
        description: None,
        ty: <FlagsInput<F> as async_graphql::InputType>::create_type_info(registry),
        deprecation: async_graphql::registry::Deprecation::NoDeprecated,
        default_value: None,
        visible: None,
        inaccessible: false,
        tags: Vec::new(),
        is_secret: false,
        directive_invocations: Vec::new(),
      },
    );
    args
  }

  impl<F> async_graphql::resolver_utils::ContainerType for FlagsView<F>
  where
    F: FlagsValue,
    for<'a> <F::Bits as ToGraphqlOutput>::Output<'a>: async_graphql::OutputType,
  {
    async fn resolve_field(
      &self,
      ctx: &async_graphql::Context<'_>,
    ) -> async_graphql::ServerResult<Option<async_graphql::Value>> {
      let name = ctx.item.node.name.node.as_str();

      // The three READINGS. `bits` crosses through the WIDTH's own output row, so the number a
      // client reads out of a flags object is the form it would read out of a plain column of that
      // width — one numeric spelling in the schema, not two.
      match name {
        "bits" => {
          let bits = self.0.bits();
          let crossed = <F::Bits as ToGraphqlOutput>::to_graphql_output(&bits);
          let selection = ctx.with_selection_set(&ctx.item.node.selection_set);
          return async_graphql::OutputType::resolve(&crossed, &selection, ctx.item)
            .await
            .map(Some);
        }
        "text" => {
          return Ok(Some(async_graphql::Value::String(
            flags::text(&self.0).as_str().to_owned(),
          )));
        }
        "names" => {
          return Ok(Some(async_graphql::Value::List(
            flags::names(&self.0)
              .into_iter()
              .map(|word| async_graphql::Value::String(word.as_str().to_owned()))
              .collect(),
          )));
        }
        "isEmpty" => return Ok(Some(async_graphql::Value::Boolean(self.0.is_empty()))),
        "isAll" => return Ok(Some(async_graphql::Value::Boolean(self.0.is_all()))),
        _ => {}
      }

      // The PER-FLAG fan. One boolean per declared bit, read off the same table the schema's field
      // list is built from — so a field a client can select is a field this arm answers.
      if let Some(bit) = flags::bits::<F>().find(|bit| bit.field == name) {
        return Ok(Some(async_graphql::Value::Boolean(
          self.0.contains(bit.value),
        )));
      }

      // The six METHODS. `complement` takes no operand and the other five do; asking for the
      // argument only where one is declared is what keeps `complement` from requiring one.
      let operand = if name == "complement" {
        F::empty()
      } else if is_self_returning(name) || matches!(name, "contains" | "intersects") {
        ctx
          .param_value::<FlagsInput<F>>(OPERAND, None)
          .map(|(_, operand)| operand.into_inner())?
      } else {
        return Ok(None);
      };

      if let Some(answer) = predicate(self.0, name, operand) {
        return Ok(Some(async_graphql::Value::Boolean(answer)));
      }
      let Some(derived) = derive(self.0, name, operand) else {
        return Ok(None);
      };
      let selection = ctx.with_selection_set(&ctx.item.node.selection_set);
      async_graphql::OutputType::resolve(&FlagsView(derived), &selection, ctx.item)
        .await
        .map(Some)
    }
  }

  impl<F> async_graphql::OutputType for FlagsView<F>
  where
    F: FlagsValue,
    for<'a> <F::Bits as ToGraphqlOutput>::Output<'a>: async_graphql::OutputType,
  {
    #[inline]
    fn type_name() -> Cow<'static, str> {
      Cow::Borrowed(F::GRAPHQL_NAME)
    }

    fn create_type_info(registry: &mut async_graphql::registry::Registry) -> String {
      registry.create_output_type::<Self, _>(
        async_graphql::registry::MetaTypeId::Object,
        |registry| {
          let boolean = <bool as async_graphql::OutputType>::create_type_info(registry);
          let string = <String as async_graphql::OutputType>::create_type_info(registry);
          let list = <Vec<String> as async_graphql::OutputType>::create_type_info(registry);
          let bits = <<F::Bits as ToGraphqlOutput>::Output<'static> as async_graphql::OutputType>
            ::create_type_info(registry);
          let object = format!("{}!", F::GRAPHQL_NAME);
          let operand = operand_argument::<F>(registry);

          let mut fields = async_graphql::indexmap::IndexMap::new();
          for name in fixed_fields() {
            let (ty, args) = match name {
              "bits" => (bits.clone(), async_graphql::indexmap::IndexMap::new()),
              "text" => (string.clone(), async_graphql::indexmap::IndexMap::new()),
              "names" => (list.clone(), async_graphql::indexmap::IndexMap::new()),
              "isEmpty" | "isAll" => (boolean.clone(), async_graphql::indexmap::IndexMap::new()),
              "complement" => (object.clone(), async_graphql::indexmap::IndexMap::new()),
              "contains" | "intersects" => (boolean.clone(), operand.clone()),
              _ => (object.clone(), operand.clone()),
            };
            fields.insert(name.to_owned(), field(name, ty, args));
          }
          for bit in flags::bits::<F>() {
            fields.insert(
              bit.field.to_owned(),
              field(
                bit.field,
                boolean.clone(),
                async_graphql::indexmap::IndexMap::new(),
              ),
            );
          }

          async_graphql::registry::MetaType::Object {
            name: F::GRAPHQL_NAME.to_owned(),
            description: None,
            fields,
            cache_control: async_graphql::CacheControl::default(),
            extends: false,
            shareable: false,
            resolvable: true,
            keys: None,
            visible: None,
            inaccessible: false,
            interface_object: false,
            tags: Vec::new(),
            is_subscription: false,
            rust_typename: Some(std::any::type_name::<Self>()),
            directive_invocations: Vec::new(),
            requires_scopes: Vec::new(),
          }
        },
      )
    }

    async fn resolve(
      &self,
      ctx: &async_graphql::ContextSelectionSet<'_>,
      _field: &async_graphql::Positioned<async_graphql::parser::types::Field>,
    ) -> async_graphql::ServerResult<async_graphql::Value> {
      async_graphql::resolver_utils::resolve_container(ctx, self).await
    }
  }

  impl<F> async_graphql::ObjectType for FlagsView<F>
  where
    F: FlagsValue,
    for<'a> <F::Bits as ToGraphqlOutput>::Output<'a>: async_graphql::OutputType,
  {
  }
}