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
//! [`MediaTimestamp`]'s wire faces: the OBJECT a client reads, the TWO scalars its whole-value operands
//! cross on, and the input object the four facets are published as.
//!
//! ```text
//! type MediaTimestamp {                   input MediaTimestampFilter {
//!   pts: Int!                          exact: MediaTimestampOperand     STRUCTURAL — the encoding
//!   timebase: Timebase!                eq: MediaTimestampOperand      ─┐
//!   nanos: Int                         ne: MediaTimestampOperand       │ SEMANTIC — the instant
//!   seconds: Float                     in: [MediaTimestampOperand!]    │
//!                                      notIn: [MediaTimestampOperand!]─┘
//!   clock: String                      gt: MediaInstantBound          ─┐
//! }                                    gte: MediaInstantBound          │ BOUND — wide
//!                                      lt: MediaInstantBound           │
//! scalar MediaTimestampOperand              lte: MediaInstantBound         ─┘
//! scalar MediaInstantBound                  pts: I64Filter            ─┐ COMPONENT
//!                                      timebase: TimebaseFilter  ─┘   (a citizen, whole)
//!                                    }
//! ```
//!
//! `exact` and `eq` take the SAME scalar and reach DIFFERENT columns — the structural identity and
//! the semantic one. Which is which is stated on [`MediaTimestampFilter`](super::MediaTimestampFilter); what
//! matters here is that one operand vocabulary serves both, so a client holding
//! `"12345 @ MPEG_90K"` can ask either question with it.
//!
//! # TWO scalars over ONE domain type, and that is the ruling
//!
//! Both operand types hold a [`MediaTimestamp`]. What differs is the door:
//!
//! | shape | `MediaTimestampOperand` | `MediaInstantBound` |
//! |---|---|---|
//! | `{ pts, timebase }` | ✔ | ✔ |
//! | `"12345 @ MPEG_90K"` | ✔ | ✔ |
//! | `{ seconds: 90.5 }` | ✘ | ✔ |
//! | `{ nanos: 90500000000 }` | ✘ | ✔ |
//! | `"0:01:30.5"` (a clock) | ✘ | ✔ |
//! | `90` (bare number) | ✘ | ✘ |
//!
//! The three forms only a BOUND takes are the three that name a POSITION without naming a VALUE. A
//! stored row's sort key is [`MediaTimestamp::to_nanos`] applied to the pair the stream declared, so an
//! operand that goes through that same function matches by construction; one that arrives at a
//! number another way matches by coincidence, on rounding nobody wrote. `mediatime` states the same
//! thing about its own clock rendering — it *is lossy and has no inverse*.
//!
//! As a bound, none of that matters: a boundary displaced by a fraction of a nanosecond admits the
//! same rows.
//!
//! A BARE NUMBER is refused by both, and it is the clearest refusal of the set: `90` could be a
//! `pts`, ninety seconds or ninety nanoseconds, and no rule picks one that is not a guess.
//!
//! # The fan publishes two stored fields and three derived ones
//!
//! `pts` and `timebase` are the value. `nanos`, `seconds` and `clock` are three readings of ONE
//! derived quantity — the position — and all three are NULLABLE together, because an instant past
//! ±292 years has no `i64` nanosecond position and a plausible number in its place would be worse
//! than none. The stored fields never go null: a value is a value however extreme.
//!
//! `clock` is rendered at NANOSECOND resolution rather than through `mediatime`'s millisecond one,
//! and the difference is the round trip: what this field publishes is a string `MediaInstantBound` reads
//! back to the same position. A face that published a bound its own door could not take would be
//! lying about its vocabulary.

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

use super::{
  super::{Timebase, TimebaseOperand, clock},
  MediaInstantBound, MediaTimestamp, MediaTimestampOperand,
};

/// An exact timestamp: the structure `{ pts, timebase }` or the text `"12345 @ MPEG_90K"`.
///
/// A clock string is deliberately NOT accepted — see [`MediaInstantBound`], which is where one is legal.
/// Written back as the exact text.
#[Scalar(name = "MediaTimestampOperand")]
impl ScalarType for MediaTimestampOperand {
  fn parse(value: Value) -> InputValueResult<Self> {
    exact(&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.
  fn is_valid(value: &Value) -> bool {
    exact(value).is_ok()
  }

  /// STRICT OUT: the exact `pts @ num/den`, which is the one form that reads back.
  fn to_value(&self) -> Value {
    Value::String(format!("{:#}", self.0.get()))
  }
}

/// A position: an exact timestamp, `{ seconds }`, `{ nanos }`, or a clock such as `"0:01:30.5"`.
///
/// Written back as the exact `pts @ num/den`, whichever of the five it arrived as.
#[Scalar(name = "MediaInstantBound")]
impl ScalarType for MediaInstantBound {
  fn parse(value: Value) -> InputValueResult<Self> {
    bound(&value).map(Self).map_err(InputValueError::custom)
  }

  fn is_valid(value: &Value) -> bool {
    bound(value).is_ok()
  }

  fn to_value(&self) -> Value {
    Value::String(format!("{:#}", self.0.get()))
  }
}

/// The EXACT arms: the `{ pts, timebase }` structure and the `pts @ num/den` text.
///
/// The structure's timebase half is read through [`TimebaseOperand`]'s own door rather than by a
/// second parser here, so the three shapes a timebase may take are the three it takes anywhere else
/// and no arm of this citizen can drift from the one below it.
fn exact(value: &Value) -> Result<MediaTimestamp, String> {
  match value {
    Value::Object(object) => {
      const PTS: &str = "pts";
      const TIMEBASE: &str = "timebase";

      if let Some(unknown) = object
        .keys()
        .find(|key| !matches!(key.as_str(), PTS | TIMEBASE))
      {
        return Err(format!(
          "an exact timestamp holds `{PTS}` and `{TIMEBASE}`, not `{unknown}`"
        ));
      }

      let pts = match object.get(PTS) {
        Some(Value::Number(number)) => number
          .as_i64()
          .ok_or_else(|| String::from("`pts` is a 64-bit integer"))?,
        Some(_) => return Err(String::from("`pts` is a number")),
        None => {
          return Err(String::from(
            "an exact timestamp states both halves; `pts` is missing",
          ));
        }
      };

      let timebase = object.get(TIMEBASE).ok_or_else(|| {
        String::from("an exact timestamp states both halves; `timebase` is missing")
      })?;
      let timebase =
        <TimebaseOperand as InputType>::parse(Some(timebase.clone())).map_err(|refused| {
          refused
            .into_server_error(async_graphql::Pos::default())
            .message
        })?;

      Ok(MediaTimestamp::new(mt::Timestamp::new(
        pts,
        Timebase::from(timebase).get(),
      )))
    }
    Value::String(text) if text.contains('@') => text
      .parse::<mt::Timestamp>()
      .map(MediaTimestamp::new)
      .map_err(|_| {
        String::from("an exact timestamp is spelled `pts @ num/den`, as in `12345 @ MPEG_90K`")
      }),
    Value::String(text) => Err(format!(
      "`{text}` names no exact timestamp: an identity is `pts @ num/den` or \
       {{pts, timebase}}, and a clock names a position rather than a value"
    )),
    Value::Number(_) => Err(String::from(
      "a timestamp is a count in a unit: send {pts, timebase} or \"pts @ num/den\" — \
       a bare number could be a pts, a second or a nanosecond",
    )),
    _ => Err(String::from("a timestamp is an object or a string")),
  }
}

/// Every arm [`exact`] takes, plus the three that name a POSITION: `{ seconds }`, `{ nanos }` and the
/// clock.
///
/// The object arms are told apart by their KEY and the string arms by the `@`, both of which are
/// total: an exact structure states `pts`, and no exact text is without an `@` while no clock has
/// one.
fn bound(value: &Value) -> Result<MediaTimestamp, String> {
  match value {
    Value::Object(object) if object.contains_key("seconds") => {
      if object.len() > 1 {
        return Err(String::from("`seconds` names a position on its own"));
      }
      match object.get("seconds") {
        Some(Value::Number(number)) => seconds(number),
        _ => Err(String::from("`seconds` is a number")),
      }
    }
    Value::Object(object) if object.contains_key("nanos") => {
      if object.len() > 1 {
        return Err(String::from("`nanos` names a position on its own"));
      }
      match object.get("nanos") {
        Some(Value::Number(number)) => number
          .as_i64()
          .map(|nanos| MediaTimestamp::new(mt::Timestamp::new(nanos, mt::Timebase::NANOS)))
          .ok_or_else(|| String::from("`nanos` is a 64-bit integer")),
        _ => Err(String::from("`nanos` is a number")),
      }
    }
    Value::String(text) if !text.contains('@') => clock::nanos(text)
      .map(|nanos| MediaTimestamp::new(mt::Timestamp::new(nanos, mt::Timebase::NANOS)))
      .map_err(|refused| refused.to_string()),
    other => exact(other),
  }
}

/// A count of SECONDS as a nanosecond position.
///
/// # What a `Float` gives up, stated
///
/// A double carries 53 bits of mantissa, so a second-count is exact to the nanosecond only up to
/// about 104 days — past that the value a client sends and the value that arrives differ, by more
/// the further out it goes. `{ nanos }` is the arm with no such ceiling, and a clock string is exact
/// to the last digit it writes. This arm exists because `{ seconds: 90.5 }` is how a person thinks
/// about a bound, and the rounding below is what keeps `90.5` from becoming `90.499999999`.
fn seconds(number: &async_graphql::Number) -> Result<MediaTimestamp, String> {
  let seconds = number
    .as_f64()
    .ok_or_else(|| String::from("`seconds` is a number"))?;

  if !seconds.is_finite() {
    return Err(String::from("`seconds` is a finite number"));
  }

  let nanos = (seconds * 1e9).round();
  if nanos < i64::MIN as f64 || nanos > i64::MAX as f64 {
    return Err(String::from(
      "the position is further from zero than 292 years of nanoseconds",
    ));
  }

  Ok(MediaTimestamp::new(mt::Timestamp::new(
    nanos as i64,
    mt::Timebase::NANOS,
  )))
}

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

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

/// A presentation timestamp: an integer PTS in units of its own timebase.
#[Object]
impl MediaTimestamp {
  /// Presentation timestamp, in units of `timebase`. May be negative.
  #[doc(hidden)]
  #[graphql(name = "pts")]
  async fn __async_graphql_pts__(&self) -> i64 {
    self.get().pts()
  }

  /// The timebase `pts` is counted in.
  #[doc(hidden)]
  #[graphql(name = "timebase")]
  async fn __async_graphql_timebase__(&self) -> Timebase {
    Timebase::new(self.get().timebase())
  }

  /// The position on the timeline, in nanoseconds — the value ordering questions are answered on.
  /// Null past ±292 years, where no `i64` position exists.
  #[doc(hidden)]
  #[graphql(name = "nanos")]
  async fn __async_graphql_nanos__(&self) -> Option<i64> {
    self.to_nanos().ok()
  }

  /// The same position in seconds. LOSSY — a double is exact to the nanosecond only to about 104
  /// days — and null wherever `nanos` is.
  #[doc(hidden)]
  #[graphql(name = "seconds")]
  async fn __async_graphql_seconds__(&self) -> Option<f64> {
    self.to_nanos().ok().map(|nanos| nanos as f64 / 1e9)
  }

  /// The same position as a clock, `H:MM:SS.fffffffff` — exact to the nanosecond, and the form a
  /// bound operand reads back. Null wherever `nanos` is.
  #[doc(hidden)]
  #[graphql(name = "clock")]
  async fn __async_graphql_clock__(&self) -> Option<String> {
    self
      .to_nanos()
      .ok()
      .map(|nanos| clock::render(nanos).as_str().to_owned())
  }
}

// The FILTER's wire face is not here: `MediaTimestampFilter` carries `#[ingraph(composed)]`, so its
// eleven 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 two operands' GRAMMAR
// — the exact door's two arms and the bound door's five.