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
//! The framework's own instant: [`Timestamp`], and the two columns it occupies.

use core::{fmt, str::FromStr};
use std::time::SystemTime;

use crate::{ColumnShape, FieldName};

/// The WHOLE SECONDS column, named as the ruling names it.
pub(crate) const SECOND: &FieldName = FieldName::new("secs");

/// The FRACTION column, in nanoseconds.
pub(crate) const NANOSECOND: &FieldName = FieldName::new("nanos");

/// **The two columns an instant occupies, and the ONE authority every lane reads them from.**
///
/// A width for [`ColumnKind`](crate::ColumnKind), a pair of binds for
/// [`Carrier`](crate::Carrier), a pair of reads for [`Assemble`](crate::Assemble), and two
/// sub-document keys for the MongoDB family — five rows in four modules, and a rename here moves
/// all of them together. That is the arrangement a DECLARED composite already has (the derive
/// corpus's `Timebase` keeps one `const SEGMENTS` its predicate and its row both read); what is new
/// is that the composite is the FRAMEWORK's, so the authority sits with the type rather than in a
/// declarer's module.
///
/// The names are unprefixed here because a segment is named BENEATH its field: a field called `at`
/// renders `at_secs` and `at_nanos`, and the join is the renderer's — see
/// [`ColumnShape`](crate::ColumnShape), where the prefixing rule is stated once for every
/// composite.
/// **BOTH leaves are the VALUE, and the census is worth stating because the name invites the other
/// reading.** `nanos` here is the SUBSECOND component of the instant — half of what
/// [`from_parts`](Timestamp::from_parts) rebuilds it from, read by the decode, and exact for every
/// instant in the range. It is not the `nanos` the media-time citizens carry, which is a DERIVED
/// position on a timeline and is [`Nullable`](ColumnShape::Nullable) for it.
///
/// So this type declares no self-nullable leaf: a required `at: Timestamp` renders both of its
/// columns `NOT NULL`, and an optional one is absent in both or in neither. There is nothing here
/// the write path can fail to place.
pub(crate) const SEGMENTS: &[ColumnShape] = &[
  ColumnShape::Plain(crate::ColumnName::of(SECOND)),
  ColumnShape::Plain(crate::ColumnName::of(NANOSECOND)),
];

/// An instant on the UTC timeline, to the NANOSECOND, from `-9999-01-02T01:59:59Z` to
/// `9999-12-30T22:00:00.999999999Z`.
///
/// The framework's own temporal citizen, present in EVERY build: [`jiff`] is a required dependency
/// here rather than a vocabulary feature, so a record the FRAMEWORK ships can stamp a time without
/// the build having asked for a temporal vocabulary first.
///
/// `Temporal<T>` is the other temporal name in this crate and answers the other question — it is the
/// storage WRAPPER a user-declared jiff or `time` value crosses into, behind the `jiff` and `time`
/// features, where this type is the framework's own instant and stands whatever the features say.
///
/// # Why a newtype and not `jiff::Timestamp` itself
///
/// The orphan rule, at the one place it actually bites. A filter registration would not have needed
/// this — `to_filter!`'s two traits are local, so jiff's own types are registered here already — but
/// the WIRE FACE cannot be written for a foreign type: `impl async_graphql::ScalarType for
/// jiff::Timestamp` is `E0117`, both halves foreign, which is the same wall `graphql::filter::
/// duration` hit and answered with a newtype of its own. A citizen this crate is going to give a
/// scalar, a comparison and a storage shape to has to be a type this crate owns.
///
/// It is also what keeps the SHAPE the framework's decision rather than jiff's: the range and the
/// precision above are promises made here, and the columns an instant occupies are chosen here.
///
/// # The range, and what refuses
///
/// [`MIN`](Self::MIN) and [`MAX`](Self::MAX) are jiff's own bounds and they are not the `i64`
/// nanosecond ceiling a Unix timestamp usually carries: there is no 2262 problem here, and no
/// 1677 one either. What they ARE is ±9999 years, chosen by jiff so that either bound combined with
/// any legal zone offset still lands on a representable civil date.
///
/// So the one lossy direction is a [`SystemTime`] from outside that span, and it REFUSES —
/// [`TryFrom`] rather than a saturating [`From`], because an instant substituted for the one a
/// caller handed over is a wrong answer reported as a right one. Nothing else about that crossing is
/// lossy: nanoseconds survive it in both directions.
///
/// # Ordering, equality and hashing are the INSTANT's
///
/// All three are derived, and on a one-field newtype a derive IS the delegation. What makes it the
/// right delegation is that an instant has nothing to normalise: this type holds no zone and no
/// offset, so two spellings of one moment — `2026-08-09T21:14:03+09:00` and
/// `2026-08-09T12:14:03Z` — parse to one value that compares, hashes and renders as one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Timestamp(jiff::Timestamp);

impl Timestamp {
  /// `1970-01-01T00:00:00Z`, the zero of the timeline.
  pub const UNIX_EPOCH: Self = Self(jiff::Timestamp::UNIX_EPOCH);
  /// The earliest representable instant, `-9999-01-02T01:59:59Z`.
  pub const MIN: Self = Self(jiff::Timestamp::MIN);
  /// The latest representable instant, `9999-12-30T22:00:00.999999999Z`.
  pub const MAX: Self = Self(jiff::Timestamp::MAX);

  /// The instant as jiff's own type — the whole of jiff's arithmetic, zone and calendar surface,
  /// reached rather than re-exposed.
  ///
  /// By VALUE because [`jiff::Timestamp`] is [`Copy`], so a reference would buy an indirection and
  /// no ownership.
  #[inline]
  pub const fn get(&self) -> jiff::Timestamp {
    self.0
  }

  /// The WHOLE seconds since the epoch — the first of the two columns this type occupies.
  ///
  /// jiff's own name for jiff's own answer. It TRUNCATES towards zero rather than flooring, so a
  /// pre-epoch instant answers a negative second and a negative fraction beside it: `-0.5s` is
  /// `(0, -500_000_000)` and not `(-1, 500_000_000)`. That is the pairing
  /// [`from_parts`](Self::from_parts) reads back, and the two halves therefore never disagree in
  /// sign.
  #[inline]
  #[must_use]
  pub fn as_second(&self) -> i64 {
    self.0.as_second()
  }

  /// The FRACTION, in nanoseconds — the second of the two columns.
  ///
  /// Signed, and the sign is the instant's: see [`as_second`](Self::as_second) for the pairing the
  /// two answers make together. Its magnitude is always below one second.
  #[inline]
  #[must_use]
  pub fn subsec_nanosecond(&self) -> i32 {
    self.0.subsec_nanosecond()
  }

  /// The instant those two columns hold — the read half of the pair
  /// [`as_second`](Self::as_second) and [`subsec_nanosecond`](Self::subsec_nanosecond) write.
  ///
  /// # It REFUSES what it would otherwise have NORMALISED, and that is the whole of the check
  ///
  /// `jiff::Timestamp::new` accepts a pair whose halves disagree in sign and quietly resolves it:
  /// `(2, -999_999_999)` becomes `(1, 1)`, the same instant spelled another way. Read from a column
  /// that is exactly the failure this crate refuses everywhere else — a stored value nothing here
  /// wrote, silently turned into one that could have been. So the pair is built through jiff and
  /// then held against what it answers: a pair that survives unchanged is the pair this encoding
  /// writes, and every other one is [`Unnormalised`](TimestampPartsError::Unnormalised).
  ///
  /// It is the round trip [`MongoExtract`](crate::query::mongo::MongoExtract)'s `f32` row already
  /// makes for the same reason — narrow, widen, and compare — applied to a value of two integers
  /// rather than to one float.
  ///
  /// # Errors
  ///
  /// [`TimestampPartsError::Range`] carries jiff's own refusal: a nanosecond outside
  /// `-999_999_999..=999_999_999`, or a pair naming an instant outside the ±9999-year span.
  /// [`TimestampPartsError::Unnormalised`] is the check above, and carries the pair that failed it.
  ///
  /// # Examples
  ///
  /// ```
  /// use ingraph::Timestamp;
  ///
  /// let at: Timestamp = "2026-08-09T21:14:03.123456789Z".parse().unwrap();
  /// assert_eq!(
  ///   Timestamp::from_parts(at.as_second(), at.subsec_nanosecond()).unwrap(),
  ///   at
  /// );
  ///
  /// // The sign-crossing spelling of the same instant is REFUSED rather than resolved.
  /// assert!(Timestamp::from_parts(2, -999_999_999).is_err());
  /// assert_eq!(
  ///   Timestamp::from_parts(1, 1).unwrap(),
  ///   "1970-01-01T00:00:01.000000001Z".parse::<Timestamp>().unwrap()
  /// );
  /// ```
  pub fn from_parts(second: i64, nanosecond: i32) -> Result<Self, TimestampPartsError> {
    let instant = jiff::Timestamp::new(second, nanosecond).map_err(TimestampPartsError::Range)?;
    if instant.as_second() != second || instant.subsec_nanosecond() != nanosecond {
      return Err(TimestampPartsError::Unnormalised { second, nanosecond });
    }
    Ok(Self(instant))
  }
}

/// Why a stored `(secs, nanos)` pair is not an instant.
///
/// Both variants are REFUSALS of a stored value rather than of a caller's arithmetic, which is what
/// puts them on a decode path: [`Assemble`](crate::Assemble) turns one into
/// [`sqlx::Error::ColumnDecode`] naming the `nanos` column, and the MongoDB family turns it into
/// [`MongoTypeError::Range`](crate::query::mongo::MongoTypeError::Range). A column pair this type
/// cannot hold is the same situation as a blob of the wrong width or an integer past its type, and
/// it is answered the same way — loudly, at the row that holds it.
///
/// No [`PartialEq`], deliberately: [`jiff::Error`] has none, so an equality here would either
/// compare rendered text — which is jiff's to change — or ignore the half that carries the reason.
/// A test asserts on the VARIANT and on the pair, which is what a caller can act on.
#[derive(Debug, Clone)]
pub enum TimestampPartsError {
  /// jiff refused the pair outright: a nanosecond outside `-999_999_999..=999_999_999`, or an
  /// instant outside the ±9999-year span.
  ///
  /// Carries jiff's own error, which names what it refused and why — more than a wrapper of this
  /// crate's would say, and the reason [`FromStr`] keeps jiff's message too.
  Range(jiff::Error),
  /// The pair is not one this encoding writes: its two halves disagree in sign, so jiff would have
  /// resolved it into another spelling of the same instant.
  ///
  /// Carries the pair that was stored, because the two numbers together are the fact a reader needs
  /// — either alone is unremarkable.
  Unnormalised {
    /// The `secs` column's value.
    second: i64,
    /// The `nanos` column's value.
    nanosecond: i32,
  },
}

impl fmt::Display for TimestampPartsError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::Range(cause) => write!(f, "the stored pair is not an instant: {cause}"),
      Self::Unnormalised { second, nanosecond } => write!(
        f,
        "the stored pair ({second}, {nanosecond}) disagrees in sign, so it is not the spelling an \
         instant is written as"
      ),
    }
  }
}

impl std::error::Error for TimestampPartsError {
  fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
    match self {
      Self::Range(cause) => Some(cause),
      Self::Unnormalised { .. } => None,
    }
  }
}

impl From<jiff::Timestamp> for Timestamp {
  #[inline]
  fn from(instant: jiff::Timestamp) -> Self {
    Self(instant)
  }
}

/// Legal though [`jiff::Timestamp`] is foreign and [`From`] is: the trait's PARAMETER is this
/// crate's type, which is what the orphan rule asks for.
impl From<Timestamp> for jiff::Timestamp {
  #[inline]
  fn from(instant: Timestamp) -> Self {
    instant.0
  }
}

/// Fallible in this direction alone, and by RANGE rather than by precision — see the type's note.
/// jiff's own crossing has the same shape and the same reason, so this is a delegation rather than a
/// second policy.
impl TryFrom<SystemTime> for Timestamp {
  type Error = jiff::Error;

  #[inline]
  fn try_from(time: SystemTime) -> Result<Self, Self::Error> {
    jiff::Timestamp::try_from(time).map(Self)
  }
}

/// [`From`] and not [`TryFrom`], because jiff's own crossing is a [`From`] and this delegates to it
/// rather than inventing a second policy. What that impl assumes is a platform time wide enough for
/// the whole span, which is true where this crate runs — a `timespec`'s `i64` seconds hold ±9999
/// years many times over — and is not a universal fact: a `FILETIME`-based [`SystemTime`] begins at
/// 1601, and an instant before it would panic inside jiff. Recorded rather than guarded, since a
/// guard here would be this crate answering for a conversion it does not own.
impl From<Timestamp> for SystemTime {
  #[inline]
  fn from(instant: Timestamp) -> Self {
    Self::from(instant.0)
  }
}

/// RFC 3339, with the fewest fractional digits that render the value exactly — `2026-08-09T21:14:03Z`
/// for a whole second, `2026-08-09T21:14:03.123456789Z` for one carrying nanoseconds. Never a bare
/// integer, which is the form a client cannot read.
///
/// A NEGATIVE year has no RFC 3339 spelling and takes ISO 8601's expanded form instead
/// (`-009999-01-02T01:59:59Z`, which is [`MIN`](Self::MIN)); every instant from the epoch onwards is
/// RFC 3339 exactly.
///
/// The [`Formatter`](fmt::Formatter) is PASSED THROUGH rather than written into, so jiff's own
/// precision option survives the newtype: `{:.3}` still asks for milliseconds and `{:.0}` still
/// truncates the fraction away. A `write!(f, "{}", …)` here would drop both in silence.
impl fmt::Display for Timestamp {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    fmt::Display::fmt(&self.0, f)
  }
}

/// The inverse of [`Display`](fmt::Display), and jiff's parser rather than a second one: an offset
/// spelling is accepted and NORMALISED to the instant it names, and a string with no offset at all is
/// refused — a civil datetime is not an instant, and guessing UTC for it would invent the one fact it
/// is missing.
///
/// The error is jiff's own, kept rather than re-worded: it names the component it refused and where
/// in the input, which is more than a wrapper of this crate's would say.
impl FromStr for Timestamp {
  type Err = jiff::Error;

  #[inline]
  fn from_str(text: &str) -> Result<Self, Self::Err> {
    text.parse().map(Self)
  }
}

/// The WALL-CLOCK reading of the same house — an instant's local twin, and the first citizen here
/// whose value may decline to name an instant at all.
///
/// Gated on `time` because its wall-clock leaf reaches a column through
/// [`Temporal<time::PrimitiveDateTime>`](crate::Temporal), and on `derive` because its filter is
/// DECLARED through `#[ingraph(composed)]` as the media-time house's five are. Neither is the
/// framework's own instant's situation, which is why that type stands in every build and this one
/// stands where a build has asked for a date library.
#[cfg(all(feature = "time", feature = "derive"))]
mod local;

#[cfg(all(feature = "time", feature = "derive"))]
pub use local::{
  LocalTimestamp, LocalTimestampFilter, LocalTimestampLeaf, LocalTimestampOperand,
  LocalTimestampPartsError, NoUtcPosition,
};

#[cfg(all(feature = "time", feature = "derive", feature = "sqlx"))]
pub use local::SqlLocalTimestampComparison;

#[cfg(test)]
mod tests;