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
//! [`MediaTimeRange`]'s wire faces: the OBJECT a client reads, the THREE scalars the interval algebra's
//! operands cross on, and the input object its facets are published as.
//!
//! ```text
//! type MediaTimeRange {                    input MediaTimeRangeFilter {
//!   start: Int!                         exact: MediaTimeRangeOperand        IDENTITY
//!   end: Int!                           contains: MediaContainedOperand   ─┐
//!   end: Int!                           overlaps: MediaSpanBound           │ INTERVAL ALGEBRA
//!   timebase: Timebase!                 within: MediaSpanBound             │
//!   startInstant: MediaTimestamp!            before: MediaInstantBound          │
//!   endInstant: MediaTimestamp!              after: MediaInstantBound          ─┘
//!   durationNanos: Int                  duration: MediaSpanDurationFilter    LENGTH
//!   durationSeconds: Float              startPts: I64Filter          ─┐
//!   durationClock: String               endPts: I64Filter             │ COMPONENT
//! }                                     timebase: TimebaseFilter     ─┘  (a citizen, whole)
//!                                     }
//! scalar MediaTimeRangeOperand
//! scalar MediaSpanBound                     input MediaSpanDurationFilter {
//! scalar MediaContainedOperand
//! scalar MediaDurationBound                   gt / gte / lt / lte: MediaDurationBound
//!                                      }
//! ```
//!
//! # `contains` takes TWO shapes because it asks one question
//!
//! "Does this range hold that" is one thing to want, and whether *that* is a point or a span changes
//! how many endpoints the answer compares — not what was asked. So there is one operator and one
//! scalar that reads either, told apart by shape: a `[` or a `start`/`end` pair is a span, anything
//! else is an instant. Two operators would have made a client choose a NAME based on the shape of
//! its own operand.
//!
//! # A SPAN operand is a pair of positions, not a stored value
//!
//! `{ start, end }` lands in `mediatime`'s `NANOS`, because a bound has no declared unit to keep —
//! its halves are [`MediaInstantBound`]s and each may be a clock or a count of seconds. The exact text
//! form `"[100, 250) @ 1/90000"` keeps the timebase it names, and the crossing converts either the
//! same way. Both are refused when the endpoints run backwards, which is `mediatime`'s own rule and
//! not one invented here.
//!
//! # The fan nests a citizen and publishes a length
//!
//! `startInstant` and `endInstant` are whole [`MediaTimestamp`]s, so a client reads an endpoint's own
//! `nanos`, `seconds` and `clock` through the fan that type already has — the recursion the filter
//! has on the way in, on the way out. `start` and `end` stay the raw counts, which is what the two
//! columns hold.
//!
//! The three `duration*` fields are one derived quantity in three readings, NULLABLE together for
//! [`MediaTimestamp`]'s reason: a length needs both endpoints to have positions, and past ±292 years an
//! endpoint has none.

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

use super::{
  super::{MediaInstantBound, MediaTimestamp, Timebase, clock},
  MediaContained, MediaContainedOperand, MediaDurationBound, MediaSpanBound, MediaTimeRange,
  MediaTimeRangeOperand,
};

/// An exact range: the text `"[100, 250) @ MPEG_90K"`, or the structure
/// `{ start, end, timebase }` whose endpoints are the declared COUNTS.
///
/// Written back as the exact text — the same string [`MediaSpanBound`] writes, so one rendering serves
/// both doors and a range read off this schema can be sent back to either.
#[Scalar(name = "MediaTimeRangeOperand")]
impl ScalarType for MediaTimeRangeOperand {
  fn parse(value: Value) -> InputValueResult<Self> {
    exact(&value).map(Self).map_err(InputValueError::custom)
  }

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

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

/// The EXACT arms: the half-open text, and the `{ start, end, timebase }` structure.
///
/// The structure's endpoints are PTS COUNTS — plain integers in the timebase beside them — which is
/// what makes this the identity door: a `{ start, end }` of two BOUNDS is [`MediaSpanBound`]'s shape and
/// names positions rather than counts. The timebase half goes through
/// [`TimebaseOperand`](super::super::TimebaseOperand)'s own door, so a timebase spells the same three
/// ways here as it does anywhere else.
fn exact(value: &Value) -> Result<MediaTimeRange, String> {
  match value {
    Value::String(text) => text
      .parse::<mt::TimeRange>()
      .map(MediaTimeRange::new)
      .map_err(|_| {
        String::from(
          "an exact range is spelled `[start, end) @ num/den`, as in `[100, 250) @ MPEG_90K`",
        )
      }),
    Value::Object(object) => {
      const START: &str = "start";
      const END: &str = "end";
      const TIMEBASE: &str = "timebase";

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

      let count = |key: &str| -> Result<i64, String> {
        match object.get(key) {
          Some(Value::Number(number)) => number
            .as_i64()
            .ok_or_else(|| format!("`{key}` is a 64-bit integer")),
          Some(_) => Err(format!("`{key}` is a count in the timebase beside it")),
          None => Err(format!(
            "an exact range states both counts and a timebase; `{key}` is missing"
          )),
        }
      };

      let start = count(START)?;
      let end = count(END)?;
      let timebase = object.get(TIMEBASE).ok_or_else(|| {
        String::from("an exact range states both counts and a timebase; `timebase` is missing")
      })?;
      let timebase = <super::super::TimebaseOperand as InputType>::parse(Some(timebase.clone()))
        .map_err(|refused| {
          refused
            .into_server_error(async_graphql::Pos::default())
            .message
        })?;

      mt::TimeRange::try_new(start, end, Timebase::from(timebase).get())
        .map(MediaTimeRange::new)
        .ok_or_else(|| String::from("a range's end must not precede its start"))
    }
    Value::Number(_) => Err(String::from(
      "a range is two counts and a timebase: send {start, end, timebase} or \
       \"[start, end) @ num/den\"",
    )),
    _ => Err(String::from("a range is an object or a string")),
  }
}

/// A span: `{ start, end }`, whose halves are positions, or the exact `"[start, end) @ num/den"`.
#[Scalar(name = "MediaSpanBound")]
impl ScalarType for MediaSpanBound {
  fn parse(value: Value) -> InputValueResult<Self> {
    span(&value).map(Self).map_err(InputValueError::custom)
  }

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

  /// STRICT OUT: the exact half-open rendering, which is the form that reads back.
  fn to_value(&self) -> Value {
    Value::String(format!("{:#}", self.0.get()))
  }
}

/// An instant or a span — everything [`MediaInstantBound`] takes, and everything [`MediaSpanBound`] does.
#[Scalar(name = "MediaContainedOperand")]
impl ScalarType for MediaContainedOperand {
  fn parse(value: Value) -> InputValueResult<Self> {
    contained(&value).map(Self).map_err(InputValueError::custom)
  }

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

  fn to_value(&self) -> Value {
    match self.0 {
      MediaContained::Instant(instant) => Value::String(format!("{:#}", instant.get())),
      MediaContained::Span(span) => Value::String(format!("{:#}", span.get())),
    }
  }
}

/// A length: `{ seconds: 5 }`, `{ nanos: 5000000000 }`, `"0:00:05"`, or `"-1500 @ MILLIS"`.
///
/// The clock arm may carry the sign a length is allowed to have; a position is not signed differently
/// but a span backwards is a real span.
#[Scalar(name = "MediaDurationBound")]
impl ScalarType for MediaDurationBound {
  fn parse(value: Value) -> InputValueResult<Self> {
    duration(&value).map(Self).map_err(InputValueError::custom)
  }

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

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

/// The SPAN arms, told apart by shape: a `[` or a `start`/`end` pair.
fn span(value: &Value) -> Result<MediaTimeRange, String> {
  match value {
    Value::String(text) if text.trim_start().starts_with('[') => text
      .parse::<mt::TimeRange>()
      .map(MediaTimeRange::new)
      .map_err(|_| {
        String::from("a span is spelled `[start, end) @ num/den`, as in `[100, 250) @ MPEG_90K`")
      }),
    Value::Object(object) => {
      const START: &str = "start";
      const END: &str = "end";

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

      let half = |key: &str| -> Result<MediaTimestamp, String> {
        let sent = object
          .get(key)
          .ok_or_else(|| format!("a span states both endpoints; `{key}` is missing"))?;
        <MediaInstantBound as InputType>::parse(Some(sent.clone()))
          .map(MediaTimestamp::from)
          .map_err(|refused| {
            refused
              .into_server_error(async_graphql::Pos::default())
              .message
          })
      };

      // Both halves land in NANOS, because a pair of BOUNDS has no declared unit to keep — one may
      // be a clock and the other a count of seconds, and neither names a timebase.
      let start = half(START)?
        .to_nanos()
        .map_err(|overflow| overflow.to_string())?;
      let end = half(END)?
        .to_nanos()
        .map_err(|overflow| overflow.to_string())?;

      mt::TimeRange::try_new(start, end, mt::Timebase::NANOS)
        .map(MediaTimeRange::new)
        .ok_or_else(|| String::from("a span's end must not precede its start"))
    }
    Value::Number(_) => Err(String::from(
      "a span is two positions: send {start, end} or \"[start, end) @ num/den\"",
    )),
    _ => Err(String::from("a span is an object or a string")),
  }
}

/// The two arms of `contains`, told apart before either is tried.
fn contained(value: &Value) -> Result<MediaContained, String> {
  let is_span = match value {
    Value::String(text) => text.trim_start().starts_with('['),
    Value::Object(object) => object.contains_key("start") || object.contains_key("end"),
    _ => false,
  };

  if is_span {
    span(value).map(MediaContained::Span)
  } else {
    <MediaInstantBound as InputType>::parse(Some(value.clone()))
      .map(|bound| MediaContained::Instant(bound.into()))
      .map_err(|refused| {
        refused
          .into_server_error(async_graphql::Pos::default())
          .message
      })
  }
}

/// The LENGTH arms: `{ seconds }`, `{ nanos }`, a clock, or the exact `ticks @ num/den`.
fn duration(value: &Value) -> Result<mt::SignedDuration, String> {
  let of_nanos = |nanos: i64| mt::SignedDuration::new(nanos, mt::Timebase::NANOS);

  match value {
    Value::String(text) if text.contains('@') => text.parse::<mt::SignedDuration>().map_err(|_| {
      String::from("an exact length is spelled `ticks @ num/den`, as in `-1500 @ MILLIS`")
    }),
    Value::String(text) => clock::nanos(text)
      .map(of_nanos)
      .map_err(|refused| refused.to_string()),
    Value::Object(_) => {
      // The `{ seconds }` and `{ nanos }` arms are the instant door's own, spent on a length: the
      // two shapes mean the same quantity whichever question is being asked, so reading them twice
      // would be two parsers to keep in step.
      <MediaInstantBound as InputType>::parse(Some(value.clone()))
        .map_err(|refused| {
          refused
            .into_server_error(async_graphql::Pos::default())
            .message
        })
        .and_then(|bound| {
          MediaTimestamp::from(bound)
            .to_nanos()
            .map(of_nanos)
            .map_err(|overflow| overflow.to_string())
        })
    }
    Value::Number(_) => Err(String::from(
      "a length is a count in a unit: send {seconds}, {nanos}, a clock, or \"ticks @ num/den\"",
    )),
    _ => Err(String::from("a length is an object or a string")),
  }
}

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

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

/// A half-open interval `[start, end)`, both endpoints in one timebase.
#[Object]
impl MediaTimeRange {
  /// Start PTS, in units of `timebase`.
  #[doc(hidden)]
  #[graphql(name = "start")]
  async fn __async_graphql_start__(&self) -> i64 {
    self.get().start_pts()
  }

  /// End PTS, in units of `timebase`; never before `start`.
  #[doc(hidden)]
  #[graphql(name = "end")]
  async fn __async_graphql_end__(&self) -> i64 {
    self.get().end_pts()
  }

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

  /// The start endpoint as a whole timestamp — its own `nanos`, `seconds` and `clock` included.
  #[doc(hidden)]
  #[graphql(name = "startInstant")]
  async fn __async_graphql_start_instant__(&self) -> MediaTimestamp {
    self.start()
  }

  /// The end endpoint as a whole timestamp. EXCLUDED from the interval.
  #[doc(hidden)]
  #[graphql(name = "endInstant")]
  async fn __async_graphql_end_instant__(&self) -> MediaTimestamp {
    self.end()
  }

  /// The span's length in nanoseconds — `end - start`, as the duration facet compares it. Null when
  /// either endpoint has no `i64` position.
  #[doc(hidden)]
  #[graphql(name = "durationNanos")]
  async fn __async_graphql_duration_nanos__(&self) -> Option<i64> {
    self.duration_nanos().ok()
  }

  /// The same length in seconds. LOSSY, and null wherever `durationNanos` is.
  #[doc(hidden)]
  #[graphql(name = "durationSeconds")]
  async fn __async_graphql_duration_seconds__(&self) -> Option<f64> {
    self.duration_nanos().ok().map(|nanos| nanos as f64 / 1e9)
  }

  /// The same length as a clock, `H:MM:SS.fffffffff` — the form a `MediaDurationBound` reads back. Null
  /// wherever `durationNanos` is.
  #[doc(hidden)]
  #[graphql(name = "durationClock")]
  async fn __async_graphql_duration_clock__(&self) -> Option<String> {
    self
      .duration_nanos()
      .ok()
      .map(|nanos| clock::render(nanos).as_str().to_owned())
  }
}

// The FILTER's wire face is not here: `MediaTimeRangeFilter` and `MediaSpanDurationFilter` both carry
// `#[ingraph(composed(shorthand = false))]`, so their slots are read off the structs' own field
// lists and the registration, the parse and the render are emitted from those. What this module
// still owns is the four operands' GRAMMAR — the identity door's two arms, the wide door's, the
// contained door's sum of both, and the length's four.