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
//! [`LocalTimestamp`]'s wire faces: the OBJECT a client reads, the scalar its structural operand
//! crosses on, and the four facets the filter is published as.
//!
//! ```text
//! type LocalTimestamp {                 input LocalTimestampFilter {
//!   local: LocalDateTime!                 exact: LocalTimestampOperand    STRUCTURAL — the value
//!   offset: UtcOffset                     eq: DateTime                  ─┐
//!   zoned: Boolean!                       ne: DateTime                   │ SEMANTIC — the instant
//!   utc: DateTime                         in: [DateTime!]                │
//!   utcNanos: Int                         notIn: [DateTime!]            ─┘
//! }                                       gt: DateTime                  ─┐
//!                                         gte: DateTime                  │ BOUND
//! scalar LocalTimestampOperand            lt: DateTime                   │
//!                                         lte: DateTime                 ─┘
//!                                         local: LocalDateTimeFilter    ─┐
//!                                         offset: UtcOffsetFilter        │ COMPONENT
//!                                         zoned: Boolean                ─┘
//!                                       }
//! ```
//!
//! # ONE scalar, and its grammar IS the ISO 8601 one a camera writes
//!
//! `"2021-08-14T16:45:09"` is a value with no zone and `"2021-08-14T16:45:09+09:00"` is the same
//! wall clock with one. That is not a syntax invented here — it is exactly what
//! `DateTimeOriginal` and `OffsetTimeOriginal` spell when a reader concatenates them, so a client
//! holding EXIF has the operand already.
//!
//! | shape | reads as |
//! |---|---|
//! | `"2021-08-14T16:45:09"` | a wall clock, NO zone |
//! | `"2021-08-14T16:45:09.123+09:00"` | a wall clock in `+09:00`, to the millisecond |
//! | `"2021-08-14T16:45:09Z"` | a wall clock that STATED UTC — not the same value as the first row |
//! | `{ local: "…", offset: "+09:00" }` | the same pair, spelled as a structure |
//! | `{ local: "…" }` | the same as the first row |
//! | `1628926509` | REFUSED — a bare number names no clock face |
//!
//! **The first and third rows are different values and the schema keeps them apart**, which is the
//! whole reason this type exists: a file that said `+00:00` said something, and a file that said
//! nothing did not. Both are written back the way they came in.
//!
//! # The object publishes two stored fields, one bit, and two readings of the derived one
//!
//! `local` and `offset` are the value; `zoned` is the presence bit, which a client would otherwise
//! have to infer from `offset` being null and which the storage holds as a column of its own.
//! `utc` and `utcNanos` are two readings of ONE derived quantity and are NULL together — for a value
//! with no stated zone, and for one outside the ±292-year nanosecond ceiling. The stored fields
//! never go null: a value is a value however extreme.

use crate::{
  JiffCivilDateTime, JiffZoneOffset, ToGraphqlOutput,
  graphql::filter::temporal::{parse_offset, parse_wall_clock},
};
use async_graphql::{
  InputType, InputValueError, InputValueResult, Object, Scalar, ScalarType, Value,
};

use super::{LocalTimestamp, LocalTimestampOperand};

#[cfg(test)]
mod tests;

/// A capture time: `"2021-08-14T16:45:09"`, `"2021-08-14T16:45:09+09:00"`, or the structure
/// `{ local, offset }`.
///
/// Written back as the text form, with the offset present exactly when the value has one — so a
/// round trip through this scalar is the identity, which is what a STRUCTURAL operand has to be.
#[Scalar(
  name = "LocalTimestampOperand",
  specified_by_url = "https://en.wikipedia.org/wiki/ISO_8601"
)]
impl ScalarType for LocalTimestampOperand {
  fn parse(value: Value) -> InputValueResult<Self> {
    capture(&value).map(Self).map_err(InputValueError::custom)
  }

  /// The SOLE notion of validity, shared with `parse` — a second one is how a scalar comes to accept
  /// what it cannot read.
  fn is_valid(value: &Value) -> bool {
    capture(value).is_ok()
  }

  fn to_value(&self) -> Value {
    Value::String(render(self.0))
  }
}

/// The text form, and the ONE renderer: the wall clock, then the offset where there is one.
///
/// Shared by the scalar's `to_value` and by the object's own text reading, so the two faces cannot
/// come to spell one value two ways.
fn render(capture: LocalTimestamp) -> String {
  match capture.offset() {
    Some(offset) => format!("{}{offset}", capture.local()),
    None => capture.local().to_string(),
  }
}

/// The two arms: the ISO 8601 text and the `{ local, offset }` structure.
fn capture(value: &Value) -> Result<LocalTimestamp, String> {
  match value {
    Value::Object(object) => {
      const LOCAL: &str = "local";
      const OFFSET: &str = "offset";

      if let Some(unknown) = object
        .keys()
        .find(|key| !matches!(key.as_str(), LOCAL | OFFSET))
      {
        return Err(format!(
          "a capture time holds `{LOCAL}` and an optional `{OFFSET}`, not `{unknown}`"
        ));
      }

      let local = object
        .get(LOCAL)
        .ok_or_else(|| String::from("a capture time states its wall clock; `local` is missing"))?;
      let local =
        <JiffCivilDateTime as InputType>::parse(Some(local.clone())).map_err(|refused| {
          refused
            .into_server_error(async_graphql::Pos::default())
            .message
        })?;

      // A KEY WRITTEN AS NULL IS THE KEY ABSENT, which is GraphQL's own reading of an optional
      // input field and therefore the reading that keeps `{local, offset: null}` and `{local}` one
      // value rather than two.
      let offset = match object.get(OFFSET) {
        None | Some(Value::Null) => None,
        Some(offset) => Some(
          <JiffZoneOffset as InputType>::parse(Some(offset.clone())).map_err(|refused| {
            refused
              .into_server_error(async_graphql::Pos::default())
              .message
          })?,
        ),
      };

      Ok(LocalTimestamp::new(
        local.get(),
        offset.map(JiffZoneOffset::get),
      ))
    }
    Value::String(text) => parse_text(text),
    Value::Number(_) => Err(String::from(
      "a capture time is a clock reading: send \"2021-08-14T16:45:09\" or the same with an offset \
       — a bare number names no clock face",
    )),
    _ => Err(String::from("a capture time is a string or an object")),
  }
}

/// The TEXT arm, split at the offset rather than parsed twice.
///
/// # Finding the offset is the whole of the parse, and the search is deliberately narrow
///
/// A date carries `-` separators and a negative year OPENS with one, so a scan from the front would
/// read `-9999-01-01T00:00:00` as an offset of `9999`. The split therefore looks only AFTER the
/// date/time separator, where the sign characters that remain can be nothing else — a civil time has
/// no `+`, no `Z`, and no `-`.
///
/// Both halves then go through their own citizens' parsers: jiff's for the wall clock, and this
/// crate's [`parse_offset`] for the displacement. There is no third grammar here to drift from the
/// `LocalDateTime` and `UtcOffset` scalars a client reaches these values through separately.
fn parse_text(text: &str) -> Result<LocalTimestamp, String> {
  let (local, offset) = split_offset(text);

  let local = parse_wall_clock(local)?;

  let offset = offset.map(parse_offset).transpose()?;
  Ok(LocalTimestamp::new(local, offset))
}

/// The wall clock and the offset suffix, or the whole string and [`None`].
fn split_offset(text: &str) -> (&str, Option<&str>) {
  let Some(separator) = text.find(['T', 't', ' ']) else {
    // No separator at all is not this function's refusal: it hands the whole string to jiff, whose
    // error names the component that was missing and where.
    return (text, None);
  };

  match text[separator + 1..].find(['+', '-', 'Z', 'z']) {
    Some(at) => {
      let (local, offset) = text.split_at(separator + 1 + at);
      (local, Some(offset))
    }
    None => (text, None),
  }
}

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

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

/// A wall clock and the zone it was on, where the zone may not have been written down.
#[Object]
impl LocalTimestamp {
  /// The wall clock the source wrote — always present, and carrying no zone.
  #[doc(hidden)]
  #[graphql(name = "local")]
  async fn __async_graphql_local__(&self) -> JiffCivilDateTime {
    JiffCivilDateTime::from(LocalTimestamp::local(self))
  }

  /// The zone that clock was on, where the source said. Null where it did not.
  #[doc(hidden)]
  #[graphql(name = "offset")]
  async fn __async_graphql_offset__(&self) -> Option<JiffZoneOffset> {
    LocalTimestamp::offset(self).map(JiffZoneOffset::from)
  }

  /// Whether the source named a zone at all — the bit a stored column holds, published so that a
  /// client need not read it off `offset` being null.
  #[doc(hidden)]
  #[graphql(name = "zoned")]
  async fn __async_graphql_zoned__(&self) -> bool {
    self.is_zoned()
  }

  /// The UTC instant, where the two above compose into one. Null where no zone was stated — never
  /// guessed.
  #[doc(hidden)]
  #[graphql(name = "utc")]
  async fn __async_graphql_utc__(&self) -> Option<crate::Timestamp> {
    self.to_utc().ok().map(crate::Timestamp::from)
  }

  /// The same instant in nanoseconds since the epoch — the value ordering questions are answered on.
  /// Null wherever `utc` is, and additionally past ±292 years, where no `i64` position exists.
  #[doc(hidden)]
  #[graphql(name = "utcNanos")]
  async fn __async_graphql_utc_nanos__(&self) -> Option<i64> {
    self.to_utc_nanos().ok()
  }

  /// The whole value as the text a `LocalTimestampOperand` reads back — `2021-08-14T16:45:09+09:00`,
  /// or the wall clock alone where no zone was stated.
  #[doc(hidden)]
  #[graphql(name = "text")]
  async fn __async_graphql_text__(&self) -> String {
    render(*self)
  }
}

// The FILTER's wire face is not here: `LocalTimestampFilter` carries `#[ingraph(composed)]`, so its
// twelve 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 text arm's split and the structure arm's two keys.