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
//! The [`Timebase`] primitive: the newtype, the error its canonical spelling parses through,
//! and the filter that guards a column of it.

use core::{fmt, num::NonZeroI32, str::FromStr};

use crate::{CompositeFilterMarker, CompositeMarker, DefaultMarker, ScalarFilter, ToGraphqlInput};
use mediatime as mt;
use smol_bytes::Utf8Bytes;

use crate::graphql::filter::opt_accessor;

#[cfg(feature = "sqlx")]
mod comparison;
#[cfg(feature = "async-graphql")]
mod graphql;
mod storage;

#[cfg(test)]
mod tests;

#[cfg(feature = "sqlx")]
pub use comparison::{SqlTimebaseComparison, TimebaseCrossingError};
pub use storage::TimebaseColumnError;
// The two column names under prefixed spellings, for the two SIBLING comparisons that reach a NESTED
// timebase — the timestamp's and the range's, which push a `timebase` segment onto the address and
// then name these beneath it. `sqlx`'s, because a lowering is the only reader either name has.
#[cfg(feature = "sqlx")]
pub(crate) use storage::{DEN as TIMEBASE_DEN, NUM as TIMEBASE_NUM};

/// A media timebase — the rational `num / den` the stream itself declares, wrapping
/// [`mediatime::Timebase`].
///
/// No [`Ord`], though the wrapped type has one. `mediatime` orders timebases as rationals, and that
/// ordering answers a question about the numbers rather than about time: a coarser tick rate is not
/// a later or a larger instant. Where the rational order is genuinely wanted it is one `get()`
/// away.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Timebase(mt::Timebase);

impl Timebase {
  /// Wrap a [`mediatime::Timebase`].
  ///
  /// The `const` route in; [`From`] is the other one and is not `const`.
  #[inline]
  pub const fn new(timebase: mt::Timebase) -> Self {
    Self(timebase)
  }

  /// The wrapped [`mediatime::Timebase`].
  #[inline]
  pub const fn get(&self) -> mt::Timebase {
    self.0
  }

  /// The storage form: the same rational in LOWEST TERMS, as the pair `(num, den)` the two columns
  /// hold.
  ///
  /// THE one reduction, and it is public so that it can be. A timebase is written through these two
  /// columns and queried through the same two, so the write path and the crossing have to agree on
  /// which pair a timebase becomes — and they agree by calling this, not by each dividing
  /// correctly. A disagreement has no error to report and no wrong value to see: a row written from
  /// `2/180000` and a filter binding `1/90000` simply never meet.
  ///
  /// Total, and free of sign handling: `mediatime`'s constructor refuses a negative half, so `num`
  /// is non-negative and `den` positive, and Euclid over those two needs no cases — see
  /// [`rational::gcd`](super::rational), which [`Rate`](super::Rate) reduces through too. `0/d`
  /// reduces to `0/1`, since `gcd(0, d)` is `d`.
  ///
  /// This is not [`Display`](fmt::Display), and the difference is deliberate: the rendering keeps
  /// the pair the stream DECLARED, where storage keeps the pair that makes two spellings of one
  /// timebase a single row. Reducing is what buys an index on `(num, den)` that answers equality
  /// exactly.
  #[inline]
  pub const fn reduced(&self) -> (i32, NonZeroI32) {
    let num = self.0.num();
    let den = self.0.den().get();
    let divisor = super::rational::gcd(num, den);

    match NonZeroI32::new(den / divisor) {
      Some(den) => (num / divisor, den),
      // `divisor` divides `den`, which is positive, so the quotient is at least one.
      None => unreachable!(),
    }
  }
}

impl From<mt::Timebase> for Timebase {
  #[inline]
  fn from(timebase: mt::Timebase) -> Self {
    Self(timebase)
  }
}

impl From<Timebase> for mt::Timebase {
  #[inline]
  fn from(timebase: Timebase) -> Self {
    timebase.0
  }
}

/// The canonical spelling, `num/den` — `mediatime`'s own rendering, forwarded.
///
/// Exact and unreduced: a timebase is the pair the stream declared, so `2/4` renders as `2/4` and
/// not as the `1/2` it equals. That is what makes this the inverse of [`FromStr`] rather than
/// merely a display of it.
impl fmt::Display for Timebase {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    self.0.fmt(f)
  }
}

impl FromStr for Timebase {
  type Err = ParseTimebaseError;

  /// Read the canonical `num/den` spelling — the text arm of what a whole-value filter operand may
  /// be.
  ///
  /// Whitespace is not trimmed and no other spelling is admitted: `" 1/90000"` and `"1 / 90000"`
  /// are refused, because a filter operand comes off a wire rather than out of a person's hand and
  /// a tolerant parser here would let two spellings of one timebase into a query.
  ///
  /// # NARROWER than `mediatime`'s own, in both directions it differs
  ///
  /// `mediatime::Timebase`'s [`FromStr`] trims whitespace and accepts a roster NAME on a second arm,
  /// and this one does neither. Both differences are the wire being a different caller from a
  /// configuration file:
  ///
  /// - **The trimming** is a convenience for a hand-written config, where `1 / 1000` is what a
  ///   person types. An operand arrives as a JSON string, where the surrounding space is not
  ///   something anyone typed, and two spellings of one timebase are two cache keys and two `IN`
  ///   list members.
  /// - **The name arm** is not missing, it is one layer out: the wire face reads `"NTSC_VIDEO"`
  ///   through `mediatime::Timebase::from_name` and this parser through the slash, and it tells the
  ///   two apart by that slash — which is total, no roster name containing one. Keeping the arms
  ///   apart is what buys the error below its detail: a refusal here names the half that was wrong,
  ///   where a two-armed parser can only say the input was neither thing.
  ///
  /// # Errors
  ///
  /// [`ParseTimebaseError`], naming the half or the rule that refused. The separator is the FIRST
  /// `/`, so `"1/2/3"` fails on its denominator rather than on its shape.
  fn from_str(text: &str) -> Result<Self, Self::Err> {
    let (num, den) = text
      .split_once('/')
      .ok_or(ParseTimebaseError::MissingSeparator)?;

    let num = num
      .parse::<i32>()
      .map_err(|_| ParseTimebaseError::Numerator)?;
    let den = den
      .parse::<i32>()
      .map_err(|_| ParseTimebaseError::Denominator)?;
    let den = NonZeroI32::new(den).ok_or(ParseTimebaseError::ZeroDenominator)?;

    mt::Timebase::try_new(num, den)
      .map(Self)
      .ok_or(ParseTimebaseError::NegativeHalf)
  }
}

/// A string does not name a [`Timebase`].
///
/// One variant per way the canonical spelling can fail, rather than one opaque error, because the
/// operand arrives from a client: which half was wrong is the only part of the answer that tells
/// the client what to send instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ParseTimebaseError {
  /// No `/`. A bare number names a numerator and leaves the denominator unsaid — it is not `n/1`.
  MissingSeparator,
  /// The text before the `/` is not an `i32`.
  Numerator,
  /// The text after the FIRST `/` is not an `i32`.
  Denominator,
  /// The denominator is zero, which [`NonZeroI32`] forbids.
  ZeroDenominator,
  /// A half is negative, which `mediatime`'s constructor refuses.
  NegativeHalf,
}

impl fmt::Display for ParseTimebaseError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let reason = match self {
      Self::MissingSeparator => "a timebase is spelled num/den",
      Self::Numerator => "the numerator is not a 32-bit integer",
      Self::Denominator => "the denominator is not a 32-bit integer",
      Self::ZeroDenominator => "the denominator must not be zero",
      Self::NegativeHalf => "neither half may be negative",
    };

    f.write_str(reason)
  }
}

impl core::error::Error for ParseTimebaseError {}

/// A whole timebase, on its way IN — the carrier the value facet's four operators cross on.
///
/// A type of its own rather than [`Timebase`] itself, and GraphQL's own namespace is what forces it:
/// objects and input types share one, so the scalar a client SENDS cannot be spelled `Timebase`
/// while an object of that name is published. What the split buys back is that the two faces can
/// differ where they should — the object is a FAN of six readings, and an operand is one value.
///
/// Transparent in both directions: it holds a [`Timebase`] that has already been validated, so
/// [`ToGraphqlInput`]'s crossing off it is [`Infallible`](core::convert::Infallible). Every refusal happens HERE, at
/// the scalar's own `parse`, which is the one door a wire value comes through.
///
/// Declared UNGATED, beside the type it carries, and the reason is the ungated-operand rule
/// this house's note states for its whole roster: a crossing says which FORM an operand takes and asks nothing about who parses that form, so it is a fact
/// about `Timebase` rather than a piece of the GraphQL binding. The binding's half — the
/// [`ScalarType`] that reads the three arms and writes the canonical one — is in `graphql`, behind
/// the feature.
///
/// [`ScalarType`]: https://docs.rs/async-graphql/latest/async_graphql/trait.ScalarType.html
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TimebaseOperand(Timebase);

impl TimebaseOperand {
  /// Wrap a [`Timebase`] as an operand.
  #[inline]
  #[must_use]
  pub const fn new(timebase: Timebase) -> Self {
    Self(timebase)
  }

  /// The wrapped [`Timebase`].
  #[inline]
  #[must_use]
  pub const fn get(&self) -> Timebase {
    self.0
  }
}

impl From<Timebase> for TimebaseOperand {
  #[inline]
  fn from(timebase: Timebase) -> Self {
    Self(timebase)
  }
}

impl From<TimebaseOperand> for Timebase {
  #[inline]
  fn from(operand: TimebaseOperand) -> Self {
    operand.0
  }
}

/// Infallible, because the validation is the scalar's: what this crossing is handed is a
/// [`TimebaseOperand`], and one of those cannot exist holding a value the door refused.
impl ToGraphqlInput for Timebase {
  type Input = TimebaseOperand;
  type Error = core::convert::Infallible;

  #[inline]
  fn cross(input: Self::Input) -> Result<Self, Self::Error> {
    Ok(input.into())
  }

  #[inline]
  fn carry(operand: &Self) -> Self::Input {
    TimebaseOperand::new(*operand)
  }
}
/// What guards a [`Timebase`] column, and it is the same predicate at both host kinds.
///
/// The two seats part where a declaration's STORED field set is narrower than its declared one — a
/// field taken out of the row has no query-time value to compare. A timebase has no such subset:
/// both columns are stored wherever the value is, so [`TimebaseFilter`] is the honest answer to both
/// questions and naming it twice is the honest way to say so.
impl CompositeFilterMarker for Timebase {
  type Filter = TimebaseFilter;
  type ColumnFilter = TimebaseFilter;
}

/// The interpretation a [`Timebase`] field is read under: the framework's COMPOSITE reading, which
/// is the VALUE family's member for one value occupying columns of its own.
///
/// This crate used to MINT the marker here — a local `TimebaseMarker<T>` with its own
/// [`Marker`](crate::Marker) row — because the framework's family words each named one of ITS
/// filter kinds and a timebase's filter is none of them. [`CompositeMarker`] is the family that was
/// missing, and the row above is the answer the mint existed to supply, so the reading is the
/// framework's now and the FILTER stays this crate's.
///
/// Its [`Marker::UnderOption`] is [`NullableMarker`] and not the collection reading, which is the
/// property the mint had to state by hand: a timebase occupies two columns OF ITS OWN, so both can
/// be `NULL` together and the null state is a real observable.
///
/// [`Marker::UnderOption`]: crate::Marker::UnderOption
/// [`NullableMarker`]: crate::NullableMarker
impl DefaultMarker for Timebase {
  type Marker = CompositeMarker<Timebase>;
}

/// The filter that guards a [`Timebase`] column: three FACETS of one value, which is what a rational
/// tag stored in two columns can honestly be asked about.
///
/// A timebase is a rational TAG naming the units a stream counts in, not a magnitude, and the
/// whole-value operator set is `eq`/`ne`/`in`/`not_in` to say so: `1/1000 > 1/90000` is not a
/// question with an answer, and the stored pair could not answer it if it were, because two columns
/// order lexicographically on `(num, den)` while the rationals order the other way round. There is
/// therefore no ordering over the whole value — no slot here takes one — while the two halves keep
/// the orderings they genuinely have, because "numerator above 1000" IS a question with an answer.
///
/// # The three facets
///
/// | facet | slots | asks about |
/// |---|---|---|
/// | VALUE | `eq`, `ne`, `in_`, `not_in` | the whole timebase, as a value |
/// | RENDER | `starts_with`, `ends_with`, `contains` | the `num/den` TEXT the two columns spell |
/// | COMPONENT | `numerator`, `denominator` | one half alone, with its own ordering |
///
/// **The value facet holds `Timebase`s and not spellings**, which is the difference from the
/// `rational` text slot this replaced: `1/2` and `2/4` are one operand here rather than two, because
/// the wire crossed them into the domain type before they reached a slot. Where the divergence used
/// to live on the wire and be closed at the crossing, there is now no divergence to close.
///
/// Three shapes reach that facet and one comes back — WIDE IN, STRICT OUT. A client may send the
/// structure `{ numerator: 1001, denominator: 30000 }`, the text `"1001/30000"`, or the roster NAME
/// `"NTSC_VIDEO"` (case-folded, as `mediatime`'s own `from_name` folds it); all three name one
/// value, and the one spelling written back is the canonical text. A bare NUMBER is refused, and
/// the refusal is the reason the two shapes are the two they are: `30000` could be a numerator, a
/// denominator or a tick rate, and no rule picks one that is not a guess about what the client
/// meant. See [`Timebase`]'s wire face for where the refusals are made.
///
/// **The render facet asks about the STORED spelling**, which is the reduced one — see
/// [`Timebase::reduced`]. `contains: "/90000"` finds a stream that declared `2/180000`, because that
/// is the row the write path wrote. It is a narrow facet by construction: the subject is two decimal
/// integers and a slash, so the operand alphabet is `[0-9/]` and an operand outside it is refused at
/// the crossing rather than matched against a rendering that cannot contain it. There are three
/// operators and not the twelve a text column carries — no negations, and no case-folding twins,
/// because a rendering with no letters in it has no case to fold.
///
/// **The component facet names the REDUCED halves**, for the same reason: `numerator: { eq: 2 }`
/// selects the timebases whose lowest-terms numerator is two, so it finds a stream that declared
/// `2/3` and not one that declared `2/4`.
///
/// # The wire face is DECLARED, not written
///
/// As at [`RateFilter`](super::RateFilter), and for the same reason: `#[ingraph(composed)]` reads
/// the nine slots below once and emits the registration, the parse and the render from them.
#[derive(Debug, Clone, PartialEq, ingraph::Filter)]
#[ingraph(composed)]
pub struct TimebaseFilter {
  eq: Option<Timebase>,
  ne: Option<Timebase>,
  in_: Option<Box<[Timebase]>>,
  not_in: Option<Box<[Timebase]>>,
  starts_with: Option<Utf8Bytes>,
  ends_with: Option<Utf8Bytes>,
  contains: Option<Utf8Bytes>,
  numerator: Option<ScalarFilter<i32>>,
  denominator: Option<ScalarFilter<NonZeroI32>>,
}

impl TimebaseFilter {
  /// The empty filter — no operator set on any facet.
  #[inline]
  pub const fn new() -> Self {
    Self {
      eq: None,
      ne: None,
      in_: None,
      not_in: None,
      starts_with: None,
      ends_with: None,
      contains: None,
      numerator: None,
      denominator: None,
    }
  }

  /// True while NO operator slot is set on ANY facet — so a lowering would emit nothing for this
  /// field.
  ///
  /// Inherent as well as [`GraphqlFilter::is_empty`], and the inherent one wins method resolution:
  /// "is anything set" is a property of the FILTER, identical on every backend, and asking it
  /// should not make a caller name one.
  ///
  /// A component slot FOLDS IN rather than counting as set: an absent one and a present one asking
  /// nothing are the same predicate, which is the emptiness law every nested filter slot answers by.
  #[inline]
  pub const fn is_empty(&self) -> bool {
    self.eq.is_none()
      && self.ne.is_none()
      && self.in_.is_none()
      && self.not_in.is_none()
      && self.starts_with.is_none()
      && self.ends_with.is_none()
      && self.contains.is_none()
      && match &self.numerator {
        Some(numerator) => numerator.is_empty(),
        None => true,
      }
      && match &self.denominator {
        Some(denominator) => denominator.is_empty(),
        None => true,
      }
  }

  /// The numerator's own filter, over the REDUCED half — absent where the component was never
  /// asked about.
  #[inline]
  pub const fn numerator(&self) -> Option<&ScalarFilter<i32>> {
    self.numerator.as_ref()
  }

  /// The denominator's own filter, over the REDUCED half — absent where the component was never
  /// asked about.
  #[inline]
  pub const fn denominator(&self) -> Option<&ScalarFilter<NonZeroI32>> {
    self.denominator.as_ref()
  }

  opt_accessor!(eq: Timebase => with_eq, set_eq, maybe_eq, update_eq);
  opt_accessor!(ne: Timebase => with_ne, set_ne, maybe_ne, update_ne);
  opt_accessor!(in_: [Timebase] => with_in_, set_in_, maybe_in_, update_in_);
  opt_accessor!(not_in: [Timebase] => with_not_in, set_not_in, maybe_not_in, update_not_in);
  opt_accessor!(
    starts_with: Utf8Bytes => with_starts_with, set_starts_with, maybe_starts_with,
    update_starts_with
  );
  opt_accessor!(
    ends_with: Utf8Bytes => with_ends_with, set_ends_with, maybe_ends_with, update_ends_with
  );
  opt_accessor!(contains: Utf8Bytes => with_contains, set_contains, maybe_contains, update_contains);

  /// Replace the numerator's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_numerator(mut self, numerator: ScalarFilter<i32>) -> Self {
    self.set_numerator(numerator);
    self
  }

  /// Replace the numerator's filter (in place).
  #[inline]
  pub fn set_numerator(&mut self, numerator: ScalarFilter<i32>) -> &mut Self {
    self.numerator = Some(numerator);
    self
  }

  /// Replace the denominator's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_denominator(mut self, denominator: ScalarFilter<NonZeroI32>) -> Self {
    self.set_denominator(denominator);
    self
  }

  /// Replace the denominator's filter (in place).
  #[inline]
  pub fn set_denominator(&mut self, denominator: ScalarFilter<NonZeroI32>) -> &mut Self {
    self.denominator = Some(denominator);
    self
  }
}

impl Default for TimebaseFilter {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}