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
use jiff::{Timestamp, Zoned, civil, tz, tz::TimeZone};

use super::TemporalStorage;

/// The measurement decision 1 of the plan rests on, kept as a test rather than as a sentence: jiff's
/// instant range sits INSIDE time's, so the crossing has no value to refuse.
///
/// The headroom is `Offset::MAX` — `25:59:59` at each end — and it is not a coincidence. jiff picks
/// `Timestamp::MIN`/`MAX` so that combining either with any legal offset still lands inside
/// `-9999-01-01 ..= 9999-12-31`, and time's default range is that same civil span in UTC.
#[test]
fn the_jiff_instant_range_sits_inside_times_own() {
  let time_min = time::OffsetDateTime::new_in_offset(
    time::Date::MIN,
    time::Time::MIDNIGHT,
    time::UtcOffset::UTC,
  )
  .unix_timestamp_nanos();
  let time_max =
    time::OffsetDateTime::new_in_offset(time::Date::MAX, time::Time::MAX, time::UtcOffset::UTC)
      .unix_timestamp_nanos();

  assert!(Timestamp::MIN.as_nanosecond() >= time_min);
  assert!(Timestamp::MAX.as_nanosecond() <= time_max);

  const OFFSET_MAX_NANOS: i128 = 93_599 * 1_000_000_000;
  assert_eq!(Timestamp::MIN.as_nanosecond() - time_min, OFFSET_MAX_NANOS);
  assert_eq!(time_max - Timestamp::MAX.as_nanosecond(), OFFSET_MAX_NANOS);
}

/// The intermediate the issue assumed, measured and rejected: `i64` nanoseconds top out at about
/// ±292 years, which is three orders of magnitude short of jiff's range. The crossing is total
/// BECAUSE it does not go through one — `as_nanosecond` is an `i128` and
/// `from_unix_timestamp_nanos` takes an `i128`.
#[test]
fn an_i64_nanosecond_intermediate_is_what_would_have_made_it_fallible() {
  assert!(i64::try_from(Timestamp::MIN.as_nanosecond()).is_err());
  assert!(i64::try_from(Timestamp::MAX.as_nanosecond()).is_err());
}

#[test]
fn a_timestamp_carries_its_extremes() {
  for instant in [Timestamp::MIN, Timestamp::MAX, Timestamp::UNIX_EPOCH] {
    assert_eq!(
      instant.to_storage().unix_timestamp_nanos(),
      instant.as_nanosecond(),
      "{instant} did not survive the crossing"
    );
  }
}

/// The precision pin. A conversion that dropped the subsecond component would still type-check and
/// still bind, and the only place it shows is the VALUE — so the assertion is on the nanosecond,
/// not on the second.
#[test]
fn a_timestamp_carries_its_subsecond_nanoseconds() {
  let instant: Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
  let stored = instant.to_storage();

  assert_eq!(stored.nanosecond(), 123_456_789);
  assert_eq!(stored.unix_timestamp_nanos(), instant.as_nanosecond());
}

/// The negative half is its own case: jiff reports `subsec_nanosecond()` with the SIGN of the
/// timestamp, so an implementation that split the instant into `(second, subsec)` and fed the pair
/// to a constructor expecting an unsigned remainder would be wrong here and right everywhere else.
#[test]
fn a_timestamp_before_the_epoch_carries_its_subsecond_nanoseconds() {
  let instant = Timestamp::from_nanosecond(-1).unwrap();
  assert_eq!(instant.subsec_nanosecond(), -1);

  let stored = instant.to_storage();
  assert_eq!(stored.unix_timestamp_nanos(), -1);
  assert_eq!(stored.nanosecond(), 999_999_999);
}

/// `Zoned` stores its INSTANT, normalized to UTC, and the zone takes no part. Three measurements
/// agree that this is the storage form rather than a simplification:
///
/// - `Zoned`'s `Ord`, `Eq` and `Hash` all delegate to `timestamp()`, so no operator this layer
///   renders can read the zone.
/// - sqlx's Postgres and MySQL encoders both call `to_offset(UTC)` before binding, so a preserved
///   offset would be normalized away one layer down anyway.
/// - sqlx's SQLite encoder formats RFC 3339 WITH the offset, so a preserved offset would be the one
///   dialect where the zone survives — as text that sorts against a UTC column wrongly. The dialect
///   that could keep it is the dialect where keeping it breaks the comparison.
#[test]
fn a_zoned_stores_its_instant_in_utc() {
  let instant: Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
  let tokyo = instant.to_zoned(TimeZone::fixed(jiff::tz::offset(9)));

  let stored = tokyo.to_storage();
  assert_eq!(stored.offset(), time::UtcOffset::UTC);
  assert_eq!(stored.unix_timestamp_nanos(), instant.as_nanosecond());
  assert_eq!(stored, instant.to_storage());
}

/// Two `Zoned`s that name the same instant in different zones store the same value, which is the
/// property that makes `gte` mean the same thing whichever zone the client sent.
///
/// The offsets are asserted separately and not folded into the value comparison, because
/// `time::OffsetDateTime`'s own [`PartialEq`] compares INSTANTS: two values with different offsets
/// and the same instant are `==` to it, so `assert_eq!` alone would pass against a row that kept
/// the zone. Measured, and the reason the offset gets a line of its own here.
#[test]
fn two_zones_over_one_instant_store_one_value() {
  let instant: Timestamp = "2024-05-06T07:08:09Z".parse().unwrap();
  let east = instant.to_zoned(TimeZone::fixed(jiff::tz::offset(9)));
  let west = instant.to_zoned(TimeZone::fixed(jiff::tz::offset(-8)));

  assert_ne!(east.datetime(), west.datetime());
  assert_eq!(east.to_storage(), west.to_storage());
  assert_eq!(east.to_storage().offset(), west.to_storage().offset());
  assert_eq!(east.to_storage().time(), west.to_storage().time());
}

#[test]
fn a_zoned_carries_its_extremes() {
  for instant in [Timestamp::MIN, Timestamp::MAX] {
    let zoned = instant.to_zoned(TimeZone::UTC);
    assert_eq!(
      zoned.to_storage().unix_timestamp_nanos(),
      instant.as_nanosecond()
    );
  }
}

/// jiff's `Zoned` may carry an offset up to `±25:59:59`, and its instant extremes are chosen so
/// that the CIVIL datetime stays inside `±9999` for every one of them. Both extremes are exercised
/// at the widest offsets because that is where a conversion preserving the offset would have run
/// out of range — the normalization to UTC is what makes the question moot, and the test says so by
/// still landing on the instant.
#[test]
fn a_zoned_at_the_widest_offsets_carries_its_extremes() {
  for (instant, offset) in [
    (Timestamp::MIN, jiff::tz::Offset::MIN),
    (Timestamp::MAX, jiff::tz::Offset::MAX),
  ] {
    let zoned = instant.to_zoned(TimeZone::fixed(offset));
    assert_eq!(
      zoned.to_storage().unix_timestamp_nanos(),
      instant.as_nanosecond()
    );
    assert_eq!(zoned.to_storage().offset(), time::UtcOffset::UTC);
  }
}

/// The two date ranges are not merely compatible, they are the SAME span — which is why this
/// crossing has nothing to check and no error to report.
#[test]
fn the_two_date_ranges_are_one_span() {
  assert_eq!(civil::Date::MIN.to_storage(), time::Date::MIN);
  assert_eq!(civil::Date::MAX.to_storage(), time::Date::MAX);
}

#[test]
fn a_date_carries_its_extremes() {
  for date in [
    civil::Date::MIN,
    civil::Date::MAX,
    civil::date(1970, 1, 1),
    civil::date(2024, 2, 29),
    // A proleptic-Gregorian leap day in the negative half: -4000 is divisible by 400, so both
    // crates must agree that February has 29 days there. They are the same calendar or they are
    // not, and a year like this is where a disagreement would show.
    civil::date(-4000, 2, 29),
  ] {
    let stored = date.to_storage();
    assert_eq!(i32::from(date.year()), stored.year());
    assert_eq!(
      u8::try_from(date.month()).unwrap(),
      u8::from(stored.month())
    );
    assert_eq!(u8::try_from(date.day()).unwrap(), stored.day());
  }
}

/// The two civil-time ranges are also one span, subsecond included.
#[test]
fn the_two_time_ranges_are_one_span() {
  assert_eq!(civil::Time::MIN.to_storage(), time::Time::MIDNIGHT);
  assert_eq!(civil::Time::MAX.to_storage(), time::Time::MAX);
}

/// The precision pin for the civil half. `23:59:59.999999999` is the value a microsecond-rounding
/// conversion turns into `23:59:59.999999`, and nothing but the nanosecond shows it.
#[test]
fn a_time_carries_its_subsecond_nanoseconds() {
  let noon = civil::Time::new(12, 34, 56, 123_456_789).unwrap();
  let stored = noon.to_storage();

  assert_eq!(stored.nanosecond(), 123_456_789);
  assert_eq!(civil::Time::MAX.to_storage().nanosecond(), 999_999_999);
}

#[test]
fn a_time_carries_its_extremes() {
  for at in [
    civil::Time::MIN,
    civil::Time::MAX,
    civil::Time::new(12, 34, 56, 0).unwrap(),
  ] {
    let stored = at.to_storage();
    assert_eq!(u8::try_from(at.hour()).unwrap(), stored.hour());
    assert_eq!(u8::try_from(at.minute()).unwrap(), stored.minute());
    assert_eq!(u8::try_from(at.second()).unwrap(), stored.second());
    assert_eq!(
      u32::try_from(at.subsec_nanosecond()).unwrap(),
      stored.nanosecond()
    );
  }
}

/// The signature, asserted as a type rather than as prose: a `Result` here would not compile.
/// Four total conversions and a method that returns the value is the whole finding, and this is
/// where it is pinned so that widening the signature later has to break a test first.
#[test]
fn the_crossing_returns_the_value_and_not_a_result() {
  fn total<T: TemporalStorage>(value: &T) -> T::Storage {
    value.to_storage()
  }

  let _: time::OffsetDateTime = total(&Timestamp::UNIX_EPOCH);
  let _: time::OffsetDateTime = total(&Zoned::new(Timestamp::UNIX_EPOCH, TimeZone::UTC));
  let _: time::Date = total(&civil::date(2024, 5, 6));
  let _: time::Time = total(&civil::Time::new(12, 0, 0, 0).unwrap());
}

/// The DATETIME crossing is the two civil ones PAIRED, so the claim is that neither half is
/// re-derived here — the stored date is the date's own crossing and the stored time is the time's.
///
/// Both extremes and the negative leap day are in the fixture for the reason the date's own test
/// gives: a disagreement between the two calendars would show there and nowhere else.
#[test]
fn a_wall_clock_crosses_as_its_two_halves() {
  for local in [
    civil::DateTime::MIN,
    civil::DateTime::MAX,
    civil::date(1970, 1, 1).at(0, 0, 0, 0),
    civil::date(2021, 8, 14).at(16, 45, 9, 123_456_789),
    civil::date(-4000, 2, 29).at(23, 59, 59, 999_999_999),
  ] {
    let stored = local.to_storage();
    assert_eq!(stored.date(), local.date().to_storage());
    assert_eq!(stored.time(), local.time().to_storage());
    assert_eq!(stored.nanosecond(), local.subsec_nanosecond() as u32);
  }
}

/// The two DATETIME ranges are the same span, which is the whole of why the row above cannot refuse.
#[test]
fn the_two_wall_clock_ranges_are_one_span() {
  assert_eq!(
    civil::DateTime::MIN.to_storage(),
    time::PrimitiveDateTime::new(time::Date::MIN, time::Time::MIDNIGHT)
  );
  assert_eq!(
    civil::DateTime::MAX.to_storage(),
    time::PrimitiveDateTime::new(time::Date::MAX, time::Time::MAX)
  );
}

/// The OFFSET crossing is the seconds and nothing else, and the fixture walks the whole domain's
/// edges — jiff's own `±25:59:59`, which is `±93_599`.
///
/// `UTC` and `ZERO` are the same number here deliberately: they are semantically distinct in jiff
/// and identical in storage, which is what this crossing is allowed to know about them.
#[test]
fn an_offset_crosses_as_its_seconds() {
  for (offset, seconds) in [
    (tz::Offset::MIN, -93_599),
    (tz::Offset::MAX, 93_599),
    (tz::Offset::UTC, 0),
    (tz::Offset::constant(9), 32_400),
    (tz::Offset::from_seconds(-16_200).unwrap(), -16_200),
  ] {
    assert_eq!(offset.to_storage(), seconds);
  }
}

/// The offset's whole domain fits `i32` with four orders of magnitude to spare, which is the
/// measurement that makes the row total — kept as a test so that a jiff release widening the offset
/// has to break something here first.
#[test]
fn the_offset_domain_sits_far_inside_an_i32() {
  assert_eq!(tz::Offset::MIN.seconds(), -93_599);
  assert_eq!(tz::Offset::MAX.seconds(), 93_599);
  assert!(i64::from(tz::Offset::MAX.seconds()) * 10_000 < i64::from(i32::MAX));
}

/// The two new rows join the totality claim above: six conversions, none of them a `Result`.
#[test]
fn the_two_new_crossings_return_the_value_too() {
  fn total<T: TemporalStorage>(value: &T) -> T::Storage {
    value.to_storage()
  }

  let _: time::PrimitiveDateTime = total(&civil::date(2021, 8, 14).at(16, 45, 9, 0));
  let _: i32 = total(&tz::Offset::constant(9));
}