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
//! [`Timebase`]'s wire faces: the OBJECT a client reads, the SCALAR one whole-value operand crosses
//! on, and the INPUT OBJECT the three filter facets are published as.
//!
//! The resolver naming rule is stated once in [`primitives`](crate::primitives) and the general shape of
//! these faces in [`time`](super::super), where all four types share them. What is stated HERE is
//! the one thing a timebase does that its siblings do not: it accepts a value on the way IN.
//!
//! ```text
//! type Timebase {                    input TimebaseFilter {
//!   numerator: Int!                    eq: TimebaseOperand         ─┐
//!   denominator: Int!                  ne: TimebaseOperand          │ VALUE
//!   name: String                       in: [TimebaseOperand!]       │
//!   text: String!                      notIn: [TimebaseOperand!]   ─┘
//!   hz: Float                          startsWith: String          ─┐
//!   secondsPerTick: Float!             endsWith: String             │ RENDER
//! }                                    contains: String            ─┘
//!                                      numerator: I32Filter        ─┐ COMPONENT
//! scalar TimebaseOperand               denominator: …Filter        ─┘
//!                                    }
//! ```
//!
//! # WIDE IN, STRICT OUT — and the two shapes are the whole of "wide"
//!
//! [`TimebaseOperand`] reads three spellings of one value and writes back one. A client may send
//! the STRUCTURE `{ numerator: 1001, denominator: 30000 }`, the TEXT `"1001/30000"`, or a roster
//! NAME `"NTSC_VIDEO"` — and 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.
//!
//! Everything else is refused, and the refusals are the point rather than the leftovers:
//!
//! - **A bare NUMBER is refused because it is ambiguous three ways.** `30000` could be the numerator
//!   (`30000/1`), the denominator (`1/30000`) or a tick rate meant as its reciprocal — and the three
//!   are three different timebases. A parser that picked one would be guessing at what a client
//!   meant, and would guess silently.
//! - **A list is refused** where a whole-value operand is expected, because `in` is an explicit key.
//!   That is the framework's own shorthand law rather than a rule invented here.
//! - **An object with any other key is refused**, both halves being required: `{ numerator: 1 }` is
//!   not `1/1`, for the reason a bare number is not — the missing half is a value nobody wrote.
//!
//! The two STRING arms are told apart by the SLASH, which is total: no roster name contains one,
//! which `mediatime` states as the property its own two-armed parser relies on. So a text operand
//! reaches the rational parser and a name operand reaches the roster, and neither can shadow the
//! other. Case folding comes with the roster door rather than being added here — `mediatime`'s
//! `from_name` folds ASCII case, so `"ntsc_video"` names the same constant as `"NTSC_VIDEO"`.
//!
//! # `Timebase` publishes SIX fields where the wrapped struct has two
//!
//! The four beyond `numerator`/`denominator` are DERIVED, and the module docs one level up rule
//! derived fields out for the OTHER time types — a lossy `seconds` beside an exact `pts` only
//! invites a client to read the wrong one. A timebase is where that reasoning stops applying, and it
//! is worth saying why rather than treating the exception as an oversight:
//!
//! - **`name` and `text` are EXACT.** A roster name is a lookup on the value and the canonical text
//!   is the pair itself, so neither loses anything a client would then have to reconstruct.
//! - **`hz` and `secondsPerTick` are lossy, and they are what a client asks a timebase for.** The
//!   question "how fast is this stream counting" has no exact answer in a JSON number, and a client
//!   computing it from the two integers computes exactly this — in whatever precision ITS language
//!   affords, which is rarely better than a double and is sometimes worse. The exact form is right
//!   there beside them, which is the condition the rule one level up actually states.
//!
//! Both derived numbers are NULLABLE where the value has no answer rather than reporting a
//! plausible one: `hz` is the reciprocal reading, and a `0/d` timebase has no reciprocal.

use core::num::NonZeroI32;

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

use super::{Timebase, TimebaseOperand};

/// A timebase as a filter operand: the structure `{ numerator, denominator }`, the text
/// `"1001/30000"`, or a well-known name such as `"NTSC_VIDEO"`.
///
/// Written back as the canonical text, whichever of the three it arrived as.
// The GraphQL name is SPELLED rather than derived from the Rust one, as `SoundEventCode`'s is: a
// wire name is a schema commitment, and a Rust rename is not a schema change.
#[Scalar(name = "TimebaseOperand")]
impl ScalarType for TimebaseOperand {
  fn parse(value: Value) -> InputValueResult<Self> {
    match &value {
      Value::Object(object) => refused(structured(object)),
      Value::String(text) => refused(spelled(text)),
      // Named rather than lumped in with the rest, because this is the refusal a client is most
      // likely to hit and the least likely to guess the reason for.
      Value::Number(_) => Err(InputValueError::custom(
        "a timebase is two numbers: send {numerator, denominator}, \"num/den\" or a well-known name \
         — a bare number could be either half or a tick rate",
      )),
      _ => 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. async-graphql's default answers `true` for every value, so
  /// a scalar narrowing in `parse` alone ships a validator admitting what its own parser rejects.
  ///
  /// # What sharing it COSTS, stated
  ///
  /// A `bool` carries no sentence. async-graphql's validation phase runs before any resolver and
  /// reads THIS, so a client sending a bad operand — as a literal or through a variable — is told
  /// the type its value could not become and not which rule it broke. The reasons `parse` writes
  /// below are what a caller holding a value gets, and what a refusal one layer further in — the
  /// CROSSING's — reaches a client with.
  ///
  /// The trade is worth making in this direction: a validator admitting what the parser rejects
  /// turns a query that VALIDATES into one that fails during execution, which is the worse answer.
  fn is_valid(value: &Value) -> bool {
    match value {
      Value::Object(object) => structured(object).is_ok(),
      Value::String(text) => spelled(text).is_ok(),
      _ => false,
    }
  }

  /// STRICT OUT: the canonical `num/den`, whichever of the three shapes came in.
  ///
  /// Not the roster name even where there is one. A name is a fact about the VALUE and is published
  /// as [`Timebase`]'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 STRUCTURED arm: both halves, required, and no other key.
///
/// Strict about extra keys because a filter operand is not a place to be forgiving — `{ numerator:
/// 1, denominato: 30000 }` is a typo that a lenient reader turns into a query for `1/1` that returns
/// the wrong rows rather than an error.
fn structured(object: &IndexMap<Name, Value>) -> Result<Timebase, 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 timebase 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 timebase 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::Timebase::try_new(numerator, denominator)
    .map(Timebase::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: `"1 / 90000"` hears that a timebase 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 roster name contains a slash, so the split is total.
fn spelled(text: &str) -> Result<Timebase, String> {
  if text.contains('/') {
    return text
      .parse::<Timebase>()
      .map_err(|refused| refused.to_string());
  }

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

/// A read arm's answer as the scalar's: the value wrapped, or the sentence put in front of a client.
///
/// The two arms answer with a MESSAGE rather than with an `InputValueError` so that
/// [`is_valid`](ScalarType::is_valid) can call the same two functions `parse` does — an error type
/// carrying the operand would make the validator's call site have to name one, and the whole point
/// of sharing them is that a query which validates is a query which parses.
fn refused(read: Result<Timebase, String>) -> InputValueResult<TimebaseOperand> {
  read
    .map(TimebaseOperand::new)
    .map_err(InputValueError::custom)
}

/// The OPERAND's own crossing — the row a COLLECTION face reads to learn what one element of a
/// `[Timebase]` looks like on the wire.
///
/// The OUTPUT row: a timebase is returned as ITSELF, by reference, through the object below.
///
/// The identity arm rather than a carrier, which is what the lifetime on `Output` exists to make
/// free: a type that already has a wire face is rendered through async-graphql's own blanket over
/// `&T`, and a clone per field of every response is exactly what a lifetime-free seat would have
/// cost.
impl ToGraphqlOutput for Timebase {
  type Output<'a> = &'a Self;

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

/// A media timebase: the rational `numerator / denominator` seconds per tick that the stream itself
/// carries.
#[Object]
impl Timebase {
  /// 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 timebase equals — `MPEG_90K`, `NTSC_VIDEO` — or null for a rational
  /// no convention has named. Matched by VALUE, so `2/2000` answers to `MILLIS`.
  #[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()
  }

  /// Ticks per second, the reciprocal reading — 29.97002997 for NTSC video. Null for a degenerate
  /// `0/d` timebase, which has no reciprocal. LOSSY: the exact value is the two integers above.
  #[doc(hidden)]
  #[graphql(name = "hz")]
  async fn __async_graphql_hz__(&self) -> Option<f64> {
    self
      .get()
      .checked_recip()
      .map(|rate| f64::from(rate.num()) / f64::from(rate.den().get()))
  }

  /// Seconds per tick — what a timebase IS, as one number. LOSSY, for `hz`'s reason; total, because
  /// the denominator cannot be zero.
  #[doc(hidden)]
  #[graphql(name = "secondsPerTick")]
  async fn __async_graphql_seconds_per_tick__(&self) -> f64 {
    f64::from(self.get().num()) / f64::from(self.get().den().get())
  }
}

// The FILTER's wire face is not here, and that is the point: `TimebaseFilter` 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's grammar — the three arms a client may write and the one canonical form that
// comes back.