Skip to main content

ingraph/primitives/mediatime/timebase/
graphql.rs

1//! [`Timebase`]'s wire faces: the OBJECT a client reads, the SCALAR one whole-value operand crosses
2//! on, and the INPUT OBJECT the three filter facets are published as.
3//!
4//! The resolver naming rule is stated once in [`primitives`](crate::primitives) and the general shape of
5//! these faces in [`time`](super::super), where all four types share them. What is stated HERE is
6//! the one thing a timebase does that its siblings do not: it accepts a value on the way IN.
7//!
8//! ```text
9//! type Timebase {                    input TimebaseFilter {
10//!   numerator: Int!                    eq: TimebaseOperand         ─┐
11//!   denominator: Int!                  ne: TimebaseOperand          │ VALUE
12//!   name: String                       in: [TimebaseOperand!]       │
13//!   text: String!                      notIn: [TimebaseOperand!]   ─┘
14//!   hz: Float                          startsWith: String          ─┐
15//!   secondsPerTick: Float!             endsWith: String             │ RENDER
16//! }                                    contains: String            ─┘
17//!                                      numerator: I32Filter        ─┐ COMPONENT
18//! scalar TimebaseOperand               denominator: …Filter        ─┘
19//!                                    }
20//! ```
21//!
22//! # WIDE IN, STRICT OUT — and the two shapes are the whole of "wide"
23//!
24//! [`TimebaseOperand`] reads three spellings of one value and writes back one. A client may send
25//! the STRUCTURE `{ numerator: 1001, denominator: 30000 }`, the TEXT `"1001/30000"`, or a roster
26//! NAME `"NTSC_VIDEO"` — and what comes back out is always the canonical text, so a value read from
27//! this schema and sent back to it is the same value by the shortest route.
28//!
29//! Everything else is refused, and the refusals are the point rather than the leftovers:
30//!
31//! - **A bare NUMBER is refused because it is ambiguous three ways.** `30000` could be the numerator
32//!   (`30000/1`), the denominator (`1/30000`) or a tick rate meant as its reciprocal — and the three
33//!   are three different timebases. A parser that picked one would be guessing at what a client
34//!   meant, and would guess silently.
35//! - **A list is refused** where a whole-value operand is expected, because `in` is an explicit key.
36//!   That is the framework's own shorthand law rather than a rule invented here.
37//! - **An object with any other key is refused**, both halves being required: `{ numerator: 1 }` is
38//!   not `1/1`, for the reason a bare number is not — the missing half is a value nobody wrote.
39//!
40//! The two STRING arms are told apart by the SLASH, which is total: no roster name contains one,
41//! which `mediatime` states as the property its own two-armed parser relies on. So a text operand
42//! reaches the rational parser and a name operand reaches the roster, and neither can shadow the
43//! other. Case folding comes with the roster door rather than being added here — `mediatime`'s
44//! `from_name` folds ASCII case, so `"ntsc_video"` names the same constant as `"NTSC_VIDEO"`.
45//!
46//! # `Timebase` publishes SIX fields where the wrapped struct has two
47//!
48//! The four beyond `numerator`/`denominator` are DERIVED, and the module docs one level up rule
49//! derived fields out for the OTHER time types — a lossy `seconds` beside an exact `pts` only
50//! invites a client to read the wrong one. A timebase is where that reasoning stops applying, and it
51//! is worth saying why rather than treating the exception as an oversight:
52//!
53//! - **`name` and `text` are EXACT.** A roster name is a lookup on the value and the canonical text
54//!   is the pair itself, so neither loses anything a client would then have to reconstruct.
55//! - **`hz` and `secondsPerTick` are lossy, and they are what a client asks a timebase for.** The
56//!   question "how fast is this stream counting" has no exact answer in a JSON number, and a client
57//!   computing it from the two integers computes exactly this — in whatever precision ITS language
58//!   affords, which is rarely better than a double and is sometimes worse. The exact form is right
59//!   there beside them, which is the condition the rule one level up actually states.
60//!
61//! Both derived numbers are NULLABLE where the value has no answer rather than reporting a
62//! plausible one: `hz` is the reciprocal reading, and a `0/d` timebase has no reciprocal.
63
64use core::num::NonZeroI32;
65
66use crate::ToGraphqlOutput;
67use async_graphql::{
68  InputValueError, InputValueResult, Name, Object, Scalar, ScalarType, Value, indexmap::IndexMap,
69};
70use mediatime as mt;
71
72use super::{Timebase, TimebaseOperand};
73
74/// A timebase as a filter operand: the structure `{ numerator, denominator }`, the text
75/// `"1001/30000"`, or a well-known name such as `"NTSC_VIDEO"`.
76///
77/// Written back as the canonical text, whichever of the three it arrived as.
78// The GraphQL name is SPELLED rather than derived from the Rust one, as `SoundEventCode`'s is: a
79// wire name is a schema commitment, and a Rust rename is not a schema change.
80#[Scalar(name = "TimebaseOperand")]
81impl ScalarType for TimebaseOperand {
82  fn parse(value: Value) -> InputValueResult<Self> {
83    match &value {
84      Value::Object(object) => refused(structured(object)),
85      Value::String(text) => refused(spelled(text)),
86      // Named rather than lumped in with the rest, because this is the refusal a client is most
87      // likely to hit and the least likely to guess the reason for.
88      Value::Number(_) => Err(InputValueError::custom(
89        "a timebase is two numbers: send {numerator, denominator}, \"num/den\" or a well-known name \
90         — a bare number could be either half or a tick rate",
91      )),
92      _ => Err(InputValueError::expected_type(value.clone())),
93    }
94  }
95
96  /// The SOLE notion of validity, shared with [`parse`](ScalarType::parse) so that a query which
97  /// validates is a query which parses. async-graphql's default answers `true` for every value, so
98  /// a scalar narrowing in `parse` alone ships a validator admitting what its own parser rejects.
99  ///
100  /// # What sharing it COSTS, stated
101  ///
102  /// A `bool` carries no sentence. async-graphql's validation phase runs before any resolver and
103  /// reads THIS, so a client sending a bad operand — as a literal or through a variable — is told
104  /// the type its value could not become and not which rule it broke. The reasons `parse` writes
105  /// below are what a caller holding a value gets, and what a refusal one layer further in — the
106  /// CROSSING's — reaches a client with.
107  ///
108  /// The trade is worth making in this direction: a validator admitting what the parser rejects
109  /// turns a query that VALIDATES into one that fails during execution, which is the worse answer.
110  fn is_valid(value: &Value) -> bool {
111    match value {
112      Value::Object(object) => structured(object).is_ok(),
113      Value::String(text) => spelled(text).is_ok(),
114      _ => false,
115    }
116  }
117
118  /// STRICT OUT: the canonical `num/den`, whichever of the three shapes came in.
119  ///
120  /// Not the roster name even where there is one. A name is a fact about the VALUE and is published
121  /// as [`Timebase`]'s own `name` field; writing it here would make the operand's round trip depend
122  /// on whether a value happened to be on a list.
123  fn to_value(&self) -> Value {
124    Value::String(self.0.to_string())
125  }
126}
127
128/// The STRUCTURED arm: both halves, required, and no other key.
129///
130/// Strict about extra keys because a filter operand is not a place to be forgiving — `{ numerator:
131/// 1, denominato: 30000 }` is a typo that a lenient reader turns into a query for `1/1` that returns
132/// the wrong rows rather than an error.
133fn structured(object: &IndexMap<Name, Value>) -> Result<Timebase, String> {
134  const NUMERATOR: &str = "numerator";
135  const DENOMINATOR: &str = "denominator";
136
137  if let Some(unknown) = object
138    .keys()
139    .find(|key| !matches!(key.as_str(), NUMERATOR | DENOMINATOR))
140  {
141    return Err(format!(
142      "a timebase object holds `{NUMERATOR}` and `{DENOMINATOR}`, not `{unknown}`"
143    ));
144  }
145
146  let half = |key: &str| -> Result<i32, String> {
147    match object.get(key) {
148      Some(Value::Number(number)) => number
149        .as_i64()
150        .and_then(|wide| i32::try_from(wide).ok())
151        .ok_or_else(|| format!("`{key}` is a 32-bit integer")),
152      Some(_) => Err(format!("`{key}` is a number")),
153      None => Err(format!(
154        "a timebase object states both halves; `{key}` is missing"
155      )),
156    }
157  };
158
159  let numerator = half(NUMERATOR)?;
160  let denominator = half(DENOMINATOR)?;
161  let denominator =
162    NonZeroI32::new(denominator).ok_or_else(|| String::from("the denominator must not be zero"))?;
163
164  mt::Timebase::try_new(numerator, denominator)
165    .map(Timebase::new)
166    .ok_or_else(|| String::from("neither half may be negative"))
167}
168
169/// The two STRING arms, told apart by the slash.
170///
171/// The slash decides rather than a try-and-fall-back, and that is what keeps each arm's error its
172/// own: `"1 / 90000"` hears that a timebase is spelled `num/den` — the rational parser's own
173/// refusal, naming the rule it broke — where a fall-back would report that it is not a well-known
174/// name, which is true and useless. No roster name contains a slash, so the split is total.
175fn spelled(text: &str) -> Result<Timebase, String> {
176  if text.contains('/') {
177    return text
178      .parse::<Timebase>()
179      .map_err(|refused| refused.to_string());
180  }
181
182  mt::Timebase::from_name(text)
183    .map(Timebase::new)
184    .ok_or_else(|| {
185      format!("`{text}` is not a well-known timebase name; a rational is spelled num/den")
186    })
187}
188
189/// A read arm's answer as the scalar's: the value wrapped, or the sentence put in front of a client.
190///
191/// The two arms answer with a MESSAGE rather than with an `InputValueError` so that
192/// [`is_valid`](ScalarType::is_valid) can call the same two functions `parse` does — an error type
193/// carrying the operand would make the validator's call site have to name one, and the whole point
194/// of sharing them is that a query which validates is a query which parses.
195fn refused(read: Result<Timebase, String>) -> InputValueResult<TimebaseOperand> {
196  read
197    .map(TimebaseOperand::new)
198    .map_err(InputValueError::custom)
199}
200
201/// The OPERAND's own crossing — the row a COLLECTION face reads to learn what one element of a
202/// `[Timebase]` looks like on the wire.
203///
204/// The OUTPUT row: a timebase is returned as ITSELF, by reference, through the object below.
205///
206/// The identity arm rather than a carrier, which is what the lifetime on `Output` exists to make
207/// free: a type that already has a wire face is rendered through async-graphql's own blanket over
208/// `&T`, and a clone per field of every response is exactly what a lifetime-free seat would have
209/// cost.
210impl ToGraphqlOutput for Timebase {
211  type Output<'a> = &'a Self;
212
213  #[inline]
214  fn to_graphql_output(timebase: &Self) -> Self::Output<'_> {
215    timebase
216  }
217}
218
219/// A media timebase: the rational `numerator / denominator` seconds per tick that the stream itself
220/// carries.
221#[Object]
222impl Timebase {
223  /// Numerator; never negative. The pair as DECLARED, not reduced.
224  #[doc(hidden)]
225  #[graphql(name = "numerator")]
226  async fn __async_graphql_numerator__(&self) -> i32 {
227    self.get().num()
228  }
229
230  /// Denominator; always positive.
231  #[doc(hidden)]
232  #[graphql(name = "denominator")]
233  async fn __async_graphql_denominator__(&self) -> NonZeroI32 {
234    self.get().den()
235  }
236
237  /// The well-known name this timebase equals — `MPEG_90K`, `NTSC_VIDEO` — or null for a rational
238  /// no convention has named. Matched by VALUE, so `2/2000` answers to `MILLIS`.
239  #[doc(hidden)]
240  #[graphql(name = "name")]
241  async fn __async_graphql_name__(&self) -> Option<&'static str> {
242    self.get().well_known_name()
243  }
244
245  /// The canonical `num/den` spelling, exact and unreduced — the form a filter operand takes.
246  #[doc(hidden)]
247  #[graphql(name = "text")]
248  async fn __async_graphql_text__(&self) -> String {
249    self.to_string()
250  }
251
252  /// Ticks per second, the reciprocal reading — 29.97002997 for NTSC video. Null for a degenerate
253  /// `0/d` timebase, which has no reciprocal. LOSSY: the exact value is the two integers above.
254  #[doc(hidden)]
255  #[graphql(name = "hz")]
256  async fn __async_graphql_hz__(&self) -> Option<f64> {
257    self
258      .get()
259      .checked_recip()
260      .map(|rate| f64::from(rate.num()) / f64::from(rate.den().get()))
261  }
262
263  /// Seconds per tick — what a timebase IS, as one number. LOSSY, for `hz`'s reason; total, because
264  /// the denominator cannot be zero.
265  #[doc(hidden)]
266  #[graphql(name = "secondsPerTick")]
267  async fn __async_graphql_seconds_per_tick__(&self) -> f64 {
268    f64::from(self.get().num()) / f64::from(self.get().den().get())
269  }
270}
271
272// The FILTER's wire face is not here, and that is the point: `TimebaseFilter` carries
273// `#[ingraph(composed)]`, so its nine slots are read off the struct's own field list and the
274// registration, the parse and the render are emitted from that one table. What this module still
275// owns is the OPERAND's grammar — the three arms a client may write and the one canonical form that
276// comes back.