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
//! [`Rate`]'s wire faces: the OBJECT a client reads and the SCALAR one whole-value operand crosses
//! on. The INPUT OBJECT the three facets are published as is DECLARED rather than written — see
//! [`RateFilter`](super::RateFilter), whose field list is the whole of it.
//!
//! ```text
//! type Rate {                        input RateFilter {
//!   numerator: Int!                    eq: RateOperand           ─┐
//!   denominator: Int!                  ne: RateOperand            │ VALUE
//!   name: String                       in: [RateOperand!]         │
//!   text: String!                      notIn: [RateOperand!]     ─┘
//!   hz: Int                            startsWith: String        ─┐
//!   perSecond: Float!                  endsWith: String           │ RENDER
//!   timebase: Timebase                 contains: String          ─┘
//! }                                    numerator: I32Filter      ─┐ COMPONENT
//!                                      denominator: …Filter      ─┘
//! scalar RateOperand                 }
//! ```
//!
//! # WIDE IN, STRICT OUT — three shapes, and no bare number
//!
//! [`RateOperand`] reads the structure `{ numerator: 30000, denominator: 1001 }`, the text
//! `"30000/1001"`, and the roster NAME `"FPS_29_97"` (case-folded, as `mediatime`'s own `from_name`
//! folds it). What comes back out is always the canonical text, so a value read from this schema and
//! sent back to it is the same value by the shortest route.
//!
//! **A bare number is refused, and not for the timebase's reason.** A timebase refuses `30` because
//! it reads three ways; a rate has no such trap, `30/1` and "thirty a second" being one rational.
//! It is refused because the next thing a client writes is `29.97`, and that is a DIFFERENT RATE
//! from the `30000/1001` they mean — so a door taking integers would have to take the decimal beside
//! them or explain why not, and taking it means guessing at a roster entry or storing a rate no
//! stream declares. Refusing both is one rule. See [`RateFilter`](super::RateFilter), where the
//! whole argument is.
//!
//! # The fan publishes two stored fields and five readings of them
//!
//! `numerator` and `denominator` are the value, as DECLARED. The other five are derived and each
//! says something the pair does not say on its own:
//!
//! | field | exact? | says |
//! |---|---|---|
//! | `name` | exact | the roster entry this rate equals, or null off-roster |
//! | `text` | exact | the canonical `num/den` — the form an operand takes |
//! | `hz` | EXACT | the whole-number reading, or null where the rate is fractional |
//! | `perSecond` | lossy | the same rate as a double, for every rate |
//! | `timebase` | exact | the RECIPROCAL reading, as a whole [`Timebase`] — null for a zero rate |
//!
//! `hz` and `perSecond` are not two names for one number. `hz` is `mediatime`'s own integral
//! constructor read backwards and is null for 29.97; `perSecond` is the division and is total. A
//! client asking "is this exactly 30" reads the first and gets a yes or a null; one asking "how fast"
//! reads the second and gets a number it can format.
//!
//! `timebase` is the one field that publishes another citizen, and it is why a client never has to
//! know that `to_timebase` swaps the pair — the reciprocal arrives with its own name, its own fan
//! and its own roster entry.
//!
//! # Why the OBJECT is still written where the type is DECLARED
//!
//! [`Rate`] carries `#[crate::fields(…)]` without the `graphql` word, and the word is absent for a
//! reason the compiler states rather than for a preference taken here. The face is ALL OR NOTHING —
//! a fragment's `#[Object]` is one the expansion writes, and a second `#[Object] impl Rate` beside
//! it is two impls of one trait for one type — so activating it means the emission must publish all
//! seven fields below. It cannot publish even the two DECLARED ones:
//!
//! - **`NonZeroI32` answers no `ToGraphqlOutput`.** The emitted object crosses every field through
//!   this framework's own output map, and the denominator's type has no row in it — measured as
//!   `E0277` at the declaration. async-graphql's own map does have one, which is what the hand
//!   resolver below reaches and why `denominator: Int!` is spellable at all here.
//! - **The five DERIVED readings have one door and it does not reach them.** `delegate(fn …)` is the
//!   only seat that puts a field on a fragment's object beyond its columns, and in REWRITE mode the
//!   method it emits forwards to `(&self.0).m()` — the WRAPPED value's method. `per_second`, the
//!   exact `hz` rule and the reciprocal-as-[`Timebase`] are this crate's own readings of
//!   `mediatime`'s pair, so each is `E0599` on `mediatime::Rate` and the two that also name a method
//!   this newtype already has are `E0592` beside it. `name` fails one step further out:
//!   `&'static str` answers no `ToGraphqlOutput` either.

use crate::ToGraphqlOutput;
use async_graphql::{
  InputValueError, InputValueResult, Name, Object, Scalar, ScalarType, Value, indexmap::IndexMap,
};
use core::num::NonZeroI32;
use mediatime as mt;

use super::{super::Timebase, Rate, RateOperand};

/// A rate as a filter operand: the structure `{ numerator, denominator }`, the text `"30000/1001"`,
/// or a well-known name such as `"FPS_29_97"`.
///
/// Written back as the canonical text, whichever of the three it arrived as.
#[Scalar(name = "RateOperand")]
impl ScalarType for RateOperand {
  fn parse(value: Value) -> InputValueResult<Self> {
    read(&value).map(Self).map_err(InputValueError::custom)
  }

  /// The SOLE notion of validity, shared with `parse` — see [`TimebaseOperand`]'s own note for what
  /// sharing it costs a client and why the trade runs this way.
  ///
  /// [`TimebaseOperand`]: super::super::TimebaseOperand
  fn is_valid(value: &Value) -> bool {
    read(value).is_ok()
  }

  /// STRICT OUT: the canonical `num/den`.
  ///
  /// Not the roster name even where there is one — a name is a fact about the VALUE and is published
  /// as [`Rate`]'s own `name` field; writing it here would make the operand's round trip depend on
  /// whether a value happened to be on a list.
  fn to_value(&self) -> Value {
    Value::String(self.0.to_string())
  }
}

/// The three arms: a structure, the canonical text, and a roster name.
fn read(value: &Value) -> Result<Rate, String> {
  match value {
    Value::Object(object) => structured(object),
    Value::String(text) => spelled(text),
    Value::Number(_) => Err(String::from(
      "a rate is a rational: send {numerator, denominator}, \"num/den\" or a well-known name — \
       a bare number cannot spell 30000/1001, and `29.97` is a different rate from the one it looks \
       like",
    )),
    _ => Err(String::from("a rate is an object or a string")),
  }
}

/// The STRUCTURED arm: both halves, required, and no other key.
///
/// Strict about extra keys because a filter operand is not a place to be forgiving — a typo that a
/// lenient reader turns into `30000/1` returns the wrong rows rather than an error.
fn structured(object: &IndexMap<Name, Value>) -> Result<Rate, String> {
  const NUMERATOR: &str = "numerator";
  const DENOMINATOR: &str = "denominator";

  if let Some(unknown) = object
    .keys()
    .find(|key| !matches!(key.as_str(), NUMERATOR | DENOMINATOR))
  {
    return Err(format!(
      "a rate object holds `{NUMERATOR}` and `{DENOMINATOR}`, not `{unknown}`"
    ));
  }

  let half = |key: &str| -> Result<i32, String> {
    match object.get(key) {
      Some(Value::Number(number)) => number
        .as_i64()
        .and_then(|wide| i32::try_from(wide).ok())
        .ok_or_else(|| format!("`{key}` is a 32-bit integer")),
      Some(_) => Err(format!("`{key}` is a number")),
      None => Err(format!(
        "a rate object states both halves; `{key}` is missing"
      )),
    }
  };

  let numerator = half(NUMERATOR)?;
  let denominator = half(DENOMINATOR)?;
  let denominator =
    NonZeroI32::new(denominator).ok_or_else(|| String::from("the denominator must not be zero"))?;

  mt::Rate::try_fps(numerator, denominator)
    .map(Rate::new)
    .ok_or_else(|| String::from("neither half may be negative"))
}

/// The two STRING arms, told apart by the slash.
///
/// The slash decides rather than a try-and-fall-back, and that is what keeps each arm's error its
/// own: `"30000 / 1001"` hears that a rate is spelled `num/den` — the rational parser's own refusal,
/// naming the rule it broke — where a fall-back would report that it is not a well-known name, which
/// is true and useless. No rate name contains a slash, so the split is total.
///
/// The two ROSTERS are disjoint on purpose, which this arm inherits: `"MPEG_90K"` is not a rate and
/// `"FPS_24"` is not a timebase, and each door refuses the other's names. A door that read both
/// would silently answer `1/24` where `24/1` was written.
fn spelled(text: &str) -> Result<Rate, String> {
  if text.contains('/') {
    return text.parse::<Rate>().map_err(|refused| refused.to_string());
  }

  mt::Rate::from_name(text)
    .map(Rate::new)
    .ok_or_else(|| format!("`{text}` is not a well-known rate name; a rational is spelled num/den"))
}

/// The OUTPUT row: a rate is returned as ITSELF, by reference, through the object below.
impl ToGraphqlOutput for Rate {
  type Output<'a> = &'a Self;

  #[inline]
  fn to_graphql_output(rate: &Self) -> Self::Output<'_> {
    rate
  }
}

/// A frame or sample rate: the rational `numerator / denominator` events per second that the stream
/// declares.
#[Object]
impl Rate {
  /// Numerator; never negative. The pair as DECLARED, not reduced.
  #[doc(hidden)]
  #[graphql(name = "numerator")]
  async fn __async_graphql_numerator__(&self) -> i32 {
    self.get().num()
  }

  /// Denominator; always positive.
  #[doc(hidden)]
  #[graphql(name = "denominator")]
  async fn __async_graphql_denominator__(&self) -> NonZeroI32 {
    self.get().den()
  }

  /// The well-known name this rate equals — `FPS_29_97`, `FPS_60` — or null for a rational no
  /// convention has named. Matched by VALUE, so `60000/2002` answers to `FPS_29_97`.
  #[doc(hidden)]
  #[graphql(name = "name")]
  async fn __async_graphql_name__(&self) -> Option<&'static str> {
    self.get().well_known_name()
  }

  /// The canonical `num/den` spelling, exact and unreduced — the form a filter operand takes.
  #[doc(hidden)]
  #[graphql(name = "text")]
  async fn __async_graphql_text__(&self) -> String {
    self.to_string()
  }

  /// The whole-number reading: 30 for exactly thirty a second, null for 29.97. EXACT — a rate whose
  /// denominator does not divide its numerator has no whole-number reading, and null says so rather
  /// than rounding to one.
  #[doc(hidden)]
  #[graphql(name = "hz")]
  async fn __async_graphql_hz__(&self) -> Option<i32> {
    let (num, den) = (self.get().num(), self.get().den().get());

    (num % den == 0).then_some(num / den)
  }

  /// The rate as a count of events per second — 29.97002997 for NTSC video. LOSSY, and total: the
  /// exact value is the two integers above.
  #[doc(hidden)]
  #[graphql(name = "perSecond")]
  async fn __async_graphql_per_second__(&self) -> f64 {
    self.per_second()
  }

  /// The RECIPROCAL reading, as a whole timebase — `1001/30000` for NTSC video, with its own name
  /// and its own fan. Null for a zero rate, which has no reciprocal.
  #[doc(hidden)]
  #[graphql(name = "timebase")]
  async fn __async_graphql_timebase__(&self) -> Option<Timebase> {
    self.get().checked_to_timebase().map(Timebase::new)
  }
}

// The FILTER's wire face is not here, and that is the point: `RateFilter` carries
// `#[ingraph(composed)]`, so its nine slots are read off the struct's own field list and the
// registration, the parse and the render are emitted from that one table. What this module still
// owns is the OPERAND — the scalar those slots register, whose grammar is `mediatime`'s and is no
// derive's business.