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
//! This house's wire faces, behind the `async-graphql` feature.
//!
//! ```text
//! type TimeRange { start: Timestamp!  end: Timestamp! }
//! input TimeRangeOperand { start: Timestamp!  end: Timestamp! }
//! scalar ContainedOperand
//! input TimeRangeFilter { overlaps: TimeRangeOperand  contains: ContainedOperand
//!                         within: TimeRangeOperand  start: TimestampFilter  end: TimestampFilter }
//!
//! type  TimeRanged<T>Data       — `TimeRanged` + the payload's own object name
//! input TimeRanged<TF>Filter    — `TimeRanged` + the payload filter's own input name
//! ```
//!
//! # TWO operand doors, and the difference is how many SHAPES each takes
//!
//! `overlaps` and `within` take exactly one shape — a whole stretch — so [`TimeRangeOperand`] is an
//! INPUT OBJECT publishing its two seats, which omits nothing and introspects. `contains` takes two
//! shapes, a position or a stretch, and GraphQL has no input union — so [`ContainedOperand`] is a
//! SCALAR whose SYNTAX says which arrived: a bare RFC 3339 instant, or the `[start, end)` text a
//! stretch renders and reads back. That is `mediagraph`'s own answer under its own name
//! (`types/time/timerange/graphql.rs:167`), and the asymmetry between the two doors is the shape
//! count rather than a taste.
//!
//! # An OPERAND newtype, for the reason [`LanguageIdOperand`](crate::LanguageIdOperand) is one
//!
//! GraphQL keeps objects and input types in ONE namespace, and [`TimeRange`] is an object — so the
//! input face cannot wear that name. [`TimeRangeOperand`] is the input object, with the same two
//! fields under the same two names, and a client reads a range back and sends one in the same
//! shape.
//!
//! # WIDE IN, STRICT OUT — and the wide half is [`Timestamp`](crate::Timestamp)'s
//!
//! Each seat is the instant's own scalar, so every spelling that type documents is admitted here and
//! there is no second grammar to keep in step: an offset form normalises, a civil datetime is
//! refused. What this layer adds is the PAIR — the two seats are handed to [`TimeRange::new`], and an
//! inverted range is refused at the door rather than reaching a predicate.
//!
//! # The GENERIC faces take their NAME from the parameter, which is the house's own answer
//!
//! GraphQL has no generics, so a parameterised type has to publish one name per instantiation. That
//! is [`Match<N, S>`](crate::graphql::matches)'s road — `format!("{}Match", N::type_name())`, a
//! [`TypeName`] row and `#[Object(name_type)]` — and it is taken here unchanged. A clash is
//! async-graphql's own refusal: `Registry::create_type` panics when one schema puts two Rust types
//! under one GraphQL name.
//!
//! # There is NO SHORTHAND at either filter, and both absences are the FULL-FORM law
//!
//! Every scalar face in this crate reads a bare value as its `eq`, because a scalar filter has one
//! obvious operator and a bare value omits no word. Neither face here does:
//!
//! * A bare range at [`TimeRangeFilter`] would have to mean one of `overlaps`, `contains` and
//!   `within`, and the operand says which of the three exactly as well as it says nothing.
//! * A bare anything at [`TimeRangedFilter`] would have to choose between the stretch and the
//!   payload, which are two different kinds of question about two different halves.
//!
//! So both refuse a bare value and NAME the refusal, which is what the law asks for where a
//! shorthand would omit a word.

use async_graphql::{
  InputObjectType, InputType, InputValueError, InputValueResult, Object, OutputType, Scalar,
  ScalarType, TypeName, Value,
  registry::{MetaInputValue, MetaType, MetaTypeId, Registry},
};
use std::borrow::Cow;

use crate::{NullableFace, ScalarFilter, Sent, Timestamp, ToGraphqlOutput, sent};

use super::{
  Contained, ContainedOperand, TimeRange, TimeRangeFilter, TimeRangeOperand, TimeRanged,
  TimeRangedFilter,
  storage::{END, START},
};

#[cfg(test)]
mod tests;

/// What a bare value at a range face omits, and the sentence a client is refused with.
const NO_RANGE_SHORTHAND: &str = "a time range filter takes a NAMED interval word — `overlaps`, `contains` or `within` — or a \
   `start`/`end` component filter: a bare range does not say which of the three was meant";

/// What a bare value at a timed-payload face omits.
const NO_RANGED_SHORTHAND: &str = "a timed filter takes `range`, `data`, or both: a bare value does not say which half of the pair \
   it is asking about";

/// One whole stretch of the timeline — the two instants a client reads back and sends in.
///
/// Both fields are NON-NULL — a stretch has two ends or it is not a stretch — and the stretch is
/// HALF-OPEN: `start` is in it and `end` is not. The field documentation below says so to a client,
/// which is the only place a schema can.
#[Object]
impl TimeRange {
  /// The first instant of the stretch, which IS in it.
  #[doc(hidden)]
  #[graphql(name = "start")]
  async fn __async_graphql_start__(&self) -> Timestamp {
    self.start()
  }

  /// The instant the stretch stops BEFORE, which is NOT in it — the stretch is `[start, end)`. Never
  /// earlier than `start`; equal to it for a degenerate stretch, which covers nothing and marks a
  /// position.
  #[doc(hidden)]
  #[graphql(name = "end")]
  async fn __async_graphql_end__(&self) -> Timestamp {
    self.end()
  }
}

/// **THE OPERAND'S DOOR** — an input object of two required instants, and [`TimeRange::new`]'s
/// refusal spent on the pair.
///
/// A hand-written [`InputType`] rather than async-graphql's `InputObject` derive, for
/// [`filter_input_object!`](crate::filter_input_object)'s own reason and one more: the derive would
/// build the struct field by field, and there is no field-by-field construction of a value whose
/// invariant is BETWEEN its fields. The pair goes through the one door or it does not exist.
impl InputType for TimeRangeOperand {
  type RawValueType = Self;

  #[inline]
  fn type_name() -> Cow<'static, str> {
    Cow::Borrowed("TimeRangeOperand")
  }

  fn create_type_info(registry: &mut Registry) -> String {
    registry.create_input_type::<Self, _>(MetaTypeId::InputObject, |registry| {
      MetaType::InputObject {
        name: String::from("TimeRangeOperand"),
        description: None,
        input_fields: crate::__ingraph_filter_input_fields!(
          registry,
          "start" : Timestamp,
          "end" : Timestamp,
        ),
        visible: None,
        inaccessible: false,
        tags: Vec::new(),
        rust_typename: Some(std::any::type_name::<Self>()),
        oneof: false,
        directive_invocations: Vec::new(),
      }
    })
  }

  /// Both seats are REQUIRED, so an object missing either is refused by that seat's own
  /// [`Timestamp`] door rather than by a sentence here — a non-null scalar handed [`None`] answers
  /// *expected type* already.
  ///
  /// What this body adds is the PAIR: two instants that each parse can still fail to be a range, and
  /// [`InvertedTimeRange`](super::InvertedTimeRange)'s own sentence is what a client is told.
  fn parse(value: Option<Value>) -> InputValueResult<Self> {
    let object = match sent(value) {
      Sent::Longhand(object) => object,
      // A range has two seats and neither is the obvious one, so there is no bare form to read —
      // the module note's own law, at the operand rather than at a filter.
      Sent::Bare(bare) => return Err(InputValueError::expected_type(bare)),
      Sent::Null => return Err(InputValueError::expected_type(Value::Null)),
      Sent::Refused(refused) => return Err(InputValueError::expected_type(refused)),
    };

    let start = <Timestamp as InputType>::parse(object.get(START.as_str()).cloned())
      .map_err(InputValueError::propagate)?;
    let end = <Timestamp as InputType>::parse(object.get(END.as_str()).cloned())
      .map_err(InputValueError::propagate)?;

    TimeRange::new(start, end)
      .map(Self::new)
      .map_err(InputValueError::custom)
  }

  fn to_value(&self) -> Value {
    let range = self.get();
    let mut object = async_graphql::indexmap::IndexMap::new();
    object.insert(
      async_graphql::Name::new(START.as_str()),
      InputType::to_value(&range.start()),
    );
    object.insert(
      async_graphql::Name::new(END.as_str()),
      InputType::to_value(&range.end()),
    );
    Value::Object(object)
  }

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

impl InputObjectType for TimeRangeOperand {}

/// **THE TWO-SHAPE DOOR** — an instant or a stretch, told apart by the SYNTAX of one string.
///
/// ```text
///   "2026-08-28T09:00:15Z"                              a POSITION
///   "[2026-08-28T09:00:00Z, 2026-08-28T09:01:00Z)"      a STRETCH
/// ```
///
/// A `#[Scalar]` rather than an input object, and the reason is the one this module's note gives:
/// GraphQL keeps no input union, so a slot taking two shapes has to take them through a form that
/// says which. The bracket is what says it, and it is the same bracket [`TimeRange`]'s
/// [`Display`](core::fmt::Display) writes — so a stretch a client READ back is a stretch it can
/// SEND, which is what makes the pair a round trip.
///
/// **The two grammars are the two types' own.** A position goes through [`Timestamp`]'s parser and a
/// stretch through [`TimeRange`]'s, so every spelling either documents is admitted here and the pair
/// check rides in with the second — an inverted `[b, a)` is refused at this door.
///
/// The shape is chosen by the LEADING CHARACTER, which is unambiguous: RFC 3339 begins with a digit
/// or a `-` for an expanded negative year, and never with `[`.
#[Scalar(name = "ContainedOperand")]
impl ScalarType for ContainedOperand {
  fn parse(value: Value) -> InputValueResult<Self> {
    match &value {
      Value::String(text) => contained(text)
        .map(Self::new)
        .map_err(InputValueError::custom),
      _ => Err(InputValueError::expected_type(value.clone())),
    }
  }

  /// The SOLE notion of validity, shared with [`parse`](ScalarType::parse) so that a query which
  /// validates is a query which parses — the argument the subtag doors in `primitives::lang` make,
  /// unchanged.
  #[inline]
  fn is_valid(value: &Value) -> bool {
    matches!(value, Value::String(text) if contained(text).is_ok())
  }

  /// STRICT OUT: whichever shape came in, written in that shape's own exact form.
  fn to_value(&self) -> Value {
    Value::String(match self.get() {
      Contained::Instant(at) => at.to_string(),
      Contained::Span(span) => span.to_string(),
    })
  }
}

/// One `contains` operand out of one string, or the sentence it is refused with.
///
/// The bracket selects, and each half is then the owning type's own parse — so this function holds
/// the SELECTION and nothing else. A text that begins with `[` and is not a stretch is refused as a
/// stretch rather than retried as an instant: guessing the other shape would report a stretch's
/// error as a position's.
fn contained(text: &str) -> Result<Contained, String> {
  let text = text.trim();

  if text.starts_with('[') {
    return text
      .parse::<TimeRange>()
      .map(Contained::Span)
      .map_err(|refused| refused.to_string());
  }

  text
    .parse::<Timestamp>()
    .map(Contained::Instant)
    .map_err(|refused| refused.to_string())
}

/// The field list [`TimeRangeFilter`]'s face registers, in declaration order — read by the face and
/// by its [`NullableFace`] row alike, which is what keeps the two from publishing different names in
/// different orders.
fn range_fields(
  registry: &mut Registry,
) -> async_graphql::indexmap::IndexMap<String, MetaInputValue> {
  crate::__ingraph_filter_input_fields!(
    registry,
    "overlaps" : Option<TimeRangeOperand>,
    "contains" : Option<ContainedOperand>,
    "within" : Option<TimeRangeOperand>,
    "start" : Option<ScalarFilter<Timestamp>>,
    "end" : Option<ScalarFilter<Timestamp>>,
  )
}

/// The object [`TimeRangeFilter`]'s face renders — the same five names in the same order.
fn range_values(
  filter: &TimeRangeFilter,
) -> async_graphql::indexmap::IndexMap<async_graphql::Name, Value> {
  crate::__ingraph_filter_value_map!(
    filter,
    "overlaps" : overlaps,
    "contains" : contains,
    "within" : within,
    "start" : start,
    "end" : end,
  )
}

/// **The FIVE-SLOT face**: three interval words and two component filters, every one of them
/// optional and none of them a shorthand.
impl InputType for TimeRangeFilter {
  type RawValueType = Self;

  #[inline]
  fn type_name() -> Cow<'static, str> {
    Cow::Borrowed("TimeRangeFilter")
  }

  fn create_type_info(registry: &mut Registry) -> String {
    registry.create_input_type::<Self, _>(MetaTypeId::InputObject, |registry| {
      MetaType::InputObject {
        name: String::from("TimeRangeFilter"),
        description: None,
        input_fields: <Self as NullableFace>::bare_fields(registry),
        visible: None,
        inaccessible: false,
        tags: Vec::new(),
        rust_typename: Some(std::any::type_name::<Self>()),
        oneof: false,
        directive_invocations: Vec::new(),
      }
    })
  }

  /// # NO SHORTHAND, and the refusal is NAMED
  ///
  /// Rule ① — *a bare value is this filter's `eq`* — has nothing to land on here: there is no `eq`,
  /// and the three words a bare range could have meant are three different questions. An explicit
  /// `null` is the NULL TEST, which this face has not got. Both are refused, and the first carries
  /// [`NO_RANGE_SHORTHAND`] so a client is told which word to write rather than only which type was
  /// expected.
  fn parse(value: Option<Value>) -> InputValueResult<Self> {
    let object = match sent(value) {
      Sent::Longhand(object) => object,
      Sent::Bare(_) => return Err(InputValueError::custom(NO_RANGE_SHORTHAND)),
      Sent::Null => return Err(InputValueError::expected_type(Value::Null)),
      Sent::Refused(refused) => return Err(InputValueError::expected_type(refused)),
    };

    Ok(Self {
      overlaps: InputType::parse(object.get("overlaps").cloned())
        .map_err(InputValueError::propagate)?,
      contains: InputType::parse(object.get("contains").cloned())
        .map_err(InputValueError::propagate)?,
      within: InputType::parse(object.get("within").cloned())
        .map_err(InputValueError::propagate)?,
      start: InputType::parse(object.get("start").cloned()).map_err(InputValueError::propagate)?,
      end: InputType::parse(object.get("end").cloned()).map_err(InputValueError::propagate)?,
    })
  }

  fn to_value(&self) -> Value {
    Value::Object(<Self as NullableFace>::bare_values(self))
  }

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

impl InputObjectType for TimeRangeFilter {}

/// The NULLABLE row — the two pieces [`Nullable`](crate::Nullable)'s own blanket assembles this
/// face's twin from, so an `Option<TimeRange>` column publishes `NullableTimeRangeFilter` with
/// `isNull` appended and no second list anywhere.
impl NullableFace for TimeRangeFilter {
  fn bare_fields(
    registry: &mut Registry,
  ) -> async_graphql::indexmap::IndexMap<String, MetaInputValue> {
    range_fields(registry)
  }

  fn bare_values(&self) -> async_graphql::indexmap::IndexMap<async_graphql::Name, Value> {
    range_values(self)
  }
}

/// `TimeRanged<Payload>` publishes `TimeRanged` before the PAYLOAD's own object name —
/// `TimeRangedDetectedLanguage` for a timed detection.
///
/// The bound is [`ToGraphqlOutput`] rather than [`OutputType`], which is this crate's crossing map
/// read where async-graphql would have read its own: a payload reaches the wire through the form its
/// row names, and that form is what carries a published name. `'static` is what makes
/// `Output<'static>` nameable at all — a name is asked for with no value in hand.
impl<T> TypeName for TimeRanged<T>
where
  T: ToGraphqlOutput + Send + Sync + 'static,
  for<'a> T::Output<'a>: OutputType,
{
  #[inline]
  fn type_name() -> Cow<'static, str> {
    Cow::Owned(format!(
      "TimeRanged{}",
      <T::Output<'static> as OutputType>::type_name()
    ))
  }
}

/// One payload and WHEN it was.
///
/// The stretch is a nested object rather than two flattened instants, which is the opposite of the
/// choice [`DetectedLanguage`](crate::DetectedLanguage)'s face makes for its identity — and the
/// reason is the same reason, read the other way. That type flattens because a detection IS its
/// language and there is nothing to disambiguate; this one nests because a timed payload is a PAIR
/// of two independent things, and the payload's own field names are the parameter's rather than this
/// crate's.
#[Object(name_type)]
impl<T> TimeRanged<T>
where
  T: ToGraphqlOutput + Send + Sync + 'static,
  for<'a> T::Output<'a>: OutputType,
{
  /// The stretch of timeline this payload occupies.
  #[doc(hidden)]
  #[graphql(name = "range")]
  async fn __async_graphql_range__(&self) -> &TimeRange {
    self.range()
  }

  /// The payload, in whatever form its own crossing publishes.
  #[doc(hidden)]
  #[graphql(name = "data")]
  async fn __async_graphql_data__(&self) -> T::Output<'_> {
    T::to_graphql_output(self.data())
  }
}

/// **The crossing OUT** — a BORROW, resolved by the `#[Object]` above.
///
/// There is no [`ToGraphqlInput`](crate::ToGraphqlInput) row beside it, and the absence is the
/// filter's shape rather than an omission — the same asymmetry
/// [`DetectedLanguage`](crate::DetectedLanguage) records, arriving here for a different reason. A
/// client never SENDS a whole timed payload: what it sends is a [`TimeRangedFilter`], whose two
/// slots are a [`TimeRangeFilter`] and the payload family's own filter. A whole-pair `eq` would need
/// an input object over the payload — which is a face the payload may not have, and which this crate
/// cannot mint for a parameter.
impl<T> crate::ToGraphqlOutput for TimeRanged<T> {
  type Output<'a>
    = &'a Self
  where
    T: 'a;

  #[inline]
  fn to_graphql_output(marked: &Self) -> &Self {
    marked
  }
}

/// The field list [`TimeRangedFilter`]'s face registers, in declaration order.
fn ranged_fields<TF>(
  registry: &mut Registry,
) -> async_graphql::indexmap::IndexMap<String, MetaInputValue>
where
  TF: InputType,
{
  crate::__ingraph_filter_input_fields!(
    registry,
    "range" : Option<TimeRangeFilter>,
    "data" : Option<TF>,
  )
}

/// The object [`TimeRangedFilter`]'s face renders — the same two names in the same order.
fn ranged_values<TF>(
  filter: &TimeRangedFilter<TF>,
) -> async_graphql::indexmap::IndexMap<async_graphql::Name, Value>
where
  TF: InputType,
{
  crate::__ingraph_filter_value_map!(filter, "range" : range, "data" : data)
}

/// **The TWO-SLOT face**, named `TimeRanged` before the PAYLOAD FILTER's own input name —
/// `TimeRangedDetectedLanguageFilter` for a timed detection.
///
/// The name is composed from `TF` rather than from the payload for the reason this struct holds
/// `TF`: the filter is what a client writes, so the name a client reads is built from the name the
/// client already knows. It sits beside the OUTPUT object's own composed name — `TimeRangedX` and
/// `TimeRangedXFilter` — without either colliding with the other.
impl<TF> InputType for TimeRangedFilter<TF>
where
  TF: InputType,
{
  type RawValueType = Self;

  #[inline]
  fn type_name() -> Cow<'static, str> {
    Cow::Owned(format!("TimeRanged{}", <TF as InputType>::type_name()))
  }

  fn create_type_info(registry: &mut Registry) -> String {
    registry.create_input_type::<Self, _>(MetaTypeId::InputObject, |registry| {
      MetaType::InputObject {
        name: String::from(<Self as InputType>::type_name()),
        description: None,
        input_fields: <Self as NullableFace>::bare_fields(registry),
        visible: None,
        inaccessible: false,
        tags: Vec::new(),
        rust_typename: Some(std::any::type_name::<Self>()),
        oneof: false,
        directive_invocations: Vec::new(),
      }
    })
  }

  /// # NO SHORTHAND — see [`NO_RANGED_SHORTHAND`]
  fn parse(value: Option<Value>) -> InputValueResult<Self> {
    let object = match sent(value) {
      Sent::Longhand(object) => object,
      Sent::Bare(_) => return Err(InputValueError::custom(NO_RANGED_SHORTHAND)),
      Sent::Null => return Err(InputValueError::expected_type(Value::Null)),
      Sent::Refused(refused) => return Err(InputValueError::expected_type(refused)),
    };

    Ok(Self {
      range: InputType::parse(object.get("range").cloned()).map_err(InputValueError::propagate)?,
      data: InputType::parse(object.get("data").cloned()).map_err(InputValueError::propagate)?,
    })
  }

  fn to_value(&self) -> Value {
    Value::Object(<Self as NullableFace>::bare_values(self))
  }

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

impl<TF: InputType> InputObjectType for TimeRangedFilter<TF> {}

/// The NULLABLE row, for [`TimeRangeFilter`]'s reason: an `Option<TimeRanged<T>>` column publishes
/// the twin with `isNull` appended, off this one field list.
impl<TF: InputType> NullableFace for TimeRangedFilter<TF> {
  fn bare_fields(
    registry: &mut Registry,
  ) -> async_graphql::indexmap::IndexMap<String, MetaInputValue> {
    ranged_fields::<TF>(registry)
  }

  fn bare_values(&self) -> async_graphql::indexmap::IndexMap<async_graphql::Name, Value> {
    ranged_values(self)
  }
}