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
//! What a duration column renders, and the range past which it renders nothing at all.

use bson::{Bson, Document, doc};
use jiff::SignedDuration;

use super::MongoDurationComparison;
use crate::{
  At, ComplexComparison, DurationFilter, DurationOutOfRange, FieldName, Mongo, RecordAddress,
  ToDatabaseComparison, TryFromFilter, comparison::mongo::MongoConjunction,
};

/// The row every address below names. Nothing here is correlated, so no test reads it.
const ROW: RecordAddress = RecordAddress::new(FieldName::new("media"), &[FieldName::new("id")]);

/// `i64::MAX` nanoseconds exactly — the largest duration this backend stores.
const CEILING: SignedDuration = SignedDuration::new(9_223_372_036, 854_775_807);

/// `i64::MIN` nanoseconds exactly — the smallest. One nanosecond further from zero than [`CEILING`],
/// because two's complement is not symmetric, so the two ends need separate constants and separate
/// assertions.
const FLOOR: SignedDuration = SignedDuration::new(-9_223_372_036, -854_775_808);

/// Lower one comparison at one column of [`ROW`] and finish the filter.
fn rendered<C: ComplexComparison<Mongo>>(comparison: &C, column: &str) -> Document {
  let frame = At::new(&ROW).frame(FieldName::new(column));
  comparison
    .apply(frame.at(), MongoConjunction::new())
    .expect("a MongoDB lowering cannot refuse")
    .into_document()
}

/// All eight operators under one key, and the mapping onto `$eq`, `$ne`, `$gt`, `$gte`, `$lt`,
/// `$lte`, `$in` and `$nin` is the scalar kind's — a duration compares its operand rather than
/// reading it, so nothing about the lowering is a duration's.
#[test]
fn every_operator_maps_one_to_one_and_merges() {
  let comparison = MongoDurationComparison::<i64>::try_from_filter(
    DurationFilter::new()
      .with_eq(SignedDuration::from_secs(1))
      .with_ne(SignedDuration::from_secs(2))
      .with_gt(SignedDuration::from_secs(3))
      .with_gte(SignedDuration::from_secs(4))
      .with_lt(SignedDuration::from_secs(5))
      .with_lte(SignedDuration::from_secs(6))
      .with_in_([SignedDuration::from_secs(7), SignedDuration::from_secs(8)])
      .with_not_in([SignedDuration::from_secs(9)]),
  )
  .expect("every operand is well inside the ceiling");

  assert_eq!(comparison.conjuncts(), 8);
  assert_eq!(
    rendered(&comparison, "len"),
    doc! {
      "len": {
        "$eq": 1_000_000_000_i64,
        "$ne": 2_000_000_000_i64,
        "$gt": 3_000_000_000_i64,
        "$gte": 4_000_000_000_i64,
        "$lt": 5_000_000_000_i64,
        "$lte": 6_000_000_000_i64,
        "$in": [7_000_000_000_i64, 8_000_000_000_i64],
        "$nin": [9_000_000_000_i64],
      }
    }
  );
}

/// The stored form is `Int64` NANOSECONDS, and the BSON ARM is the assertion rather than the number:
/// an `Int32` or a `Double` holding the same count would compare against a stored `Int64` field
/// under MongoDB's type bracketing rather than as the same type, and a `Double` could not even hold
/// it — an `f64` has 53 significand bits, which nanoseconds exhaust after about 104 days.
#[test]
fn an_operand_reaches_bson_as_an_int64_of_nanoseconds() {
  let comparison = MongoDurationComparison::<i64>::try_from_filter(
    DurationFilter::new().with_eq(SignedDuration::from_secs(3600) + SignedDuration::from_nanos(1)),
  )
  .expect("an hour is well inside the ceiling");

  let filter = rendered(&comparison, "len");
  let operand = filter
    .get_document("len")
    .expect("the field holds an operator document")
    .get("$eq")
    .expect("the operator is present");

  assert_eq!(operand, &Bson::Int64(3_600_000_000_001));
}

/// The nanosecond a duration column cannot hold, and the one before it.
///
/// The refusal lands at the CROSSING because there is nowhere later: this backend's
/// `Backend::Error` is `Infallible`, so a lowering has no way to say no — where a truncating cast
/// would turn `292 years + 1ns` into a small negative count and match documents nobody asked about.
#[test]
fn the_ceiling_is_a_refusal_and_not_a_truncation() {
  let crossed =
    MongoDurationComparison::<i64>::try_from_filter(DurationFilter::new().with_eq(CEILING))
      .expect("i64::MAX nanoseconds is storable");
  assert_eq!(crossed.eq(), Some(&i64::MAX));

  let over = CEILING + SignedDuration::from_nanos(1);
  assert_eq!(
    MongoDurationComparison::<i64>::try_from_filter(DurationFilter::new().with_eq(over))
      .unwrap_err(),
    DurationOutOfRange
  );

  // What the refusal is instead of: the cast that would have made the operand look ordinary. A
  // signed operand makes this the worse half of the trade — the wrap does not merely change the
  // magnitude, it changes the SIGN, so `292 years + 1ns` would have matched documents about the
  // deep past.
  assert_eq!(over.as_nanos() as i64, i64::MIN);
}

/// The NEGATIVE end, which the unsigned operand had no way to reach — and it is not the ceiling
/// mirrored: `i64::MIN` is one nanosecond further from zero than `i64::MAX`, so a guard written as
/// `abs() <= CEILING` would refuse the one legal value at the very bottom.
///
/// The wrap this refuses is the ceiling's read backwards, and just as wrong.
#[test]
fn the_floor_is_a_refusal_and_the_last_legal_value_below_zero_is_not() {
  let crossed =
    MongoDurationComparison::<i64>::try_from_filter(DurationFilter::new().with_eq(FLOOR))
      .expect("i64::MIN nanoseconds is storable");
  assert_eq!(crossed.eq(), Some(&i64::MIN));

  // The asymmetry, stated as a value rather than as prose: negating the floor is already over the
  // ceiling.
  assert_eq!(
    MongoDurationComparison::<i64>::try_from_filter(DurationFilter::new().with_eq(-FLOOR))
      .unwrap_err(),
    DurationOutOfRange
  );

  let under = FLOOR - SignedDuration::from_nanos(1);
  assert_eq!(
    MongoDurationComparison::<i64>::try_from_filter(DurationFilter::new().with_eq(under))
      .unwrap_err(),
    DurationOutOfRange
  );
  assert_eq!(under.as_nanos() as i64, i64::MAX);
}

/// A negative operand IS storable, and it renders as a negative `Int64` — the whole point of the
/// signed operand reaching the document.
///
/// MongoDB's numeric bracket is signed, so `$lt: -2000000000` is a question about documents whose
/// stored count is further below zero, and the four ordering operators mean over negatives exactly
/// what they mean over positives.
#[test]
fn a_negative_operand_crosses_and_stays_negative() {
  let comparison = MongoDurationComparison::<i64>::try_from_filter(
    DurationFilter::new()
      .with_gte(SignedDuration::from_secs(-2))
      .with_in_([SignedDuration::from_secs(-1), SignedDuration::from_secs(1)]),
  )
  .expect("a negative duration is well inside the floor");

  assert_eq!(
    rendered(&comparison, "offset"),
    doc! {
      "offset": {
        "$gte": -2_000_000_000_i64,
        "$in": [-1_000_000_000_i64, 1_000_000_000_i64],
      }
    }
  );
}

/// Every slot in `slots` that CROSSED, by name.
///
/// A list rather than a `for` loop of assertions, so a guard that covers some slots and not others
/// reports ALL the ones it missed instead of stopping at the first — which is the difference between
/// learning that a guard is incomplete and learning where.
fn leaked(slots: impl IntoIterator<Item = (&'static str, DurationFilter)>) -> Vec<&'static str> {
  slots
    .into_iter()
    .filter(|(_, filter)| MongoDurationComparison::<i64>::try_from_filter(filter.clone()).is_ok())
    .map(|(slot, _)| slot)
    .collect()
}

/// The SIX single-operand slots, each refused on its own AND AT BOTH ENDS — a guard reached through
/// `eq` alone would pass a test that stopped there and leave five operators storing a wrapped count,
/// and one written against the ceiling alone would leave all six storing a wrapped NEGATIVE count.
#[test]
fn every_inline_slot_refuses_an_out_of_range_operand() {
  let over = CEILING + SignedDuration::from_nanos(1);
  let under = FLOOR - SignedDuration::from_nanos(1);
  let crossed = leaked([
    ("eq+", DurationFilter::new().with_eq(over)),
    ("ne+", DurationFilter::new().with_ne(over)),
    ("gt+", DurationFilter::new().with_gt(over)),
    ("gte+", DurationFilter::new().with_gte(over)),
    ("lt+", DurationFilter::new().with_lt(over)),
    ("lte+", DurationFilter::new().with_lte(over)),
    ("eq-", DurationFilter::new().with_eq(under)),
    ("ne-", DurationFilter::new().with_ne(under)),
    ("gt-", DurationFilter::new().with_gt(under)),
    ("gte-", DurationFilter::new().with_gte(under)),
    ("lt-", DurationFilter::new().with_lt(under)),
    ("lte-", DurationFilter::new().with_lte(under)),
  ]);

  assert!(
    crossed.is_empty(),
    "these slots let an unstorable operand through: {crossed:?}"
  );
}

/// **The two membership slots are guarded per ELEMENT**, which is the half a slot walk is most
/// likely to miss: dropping the element that does not fit would silently NARROW `in_` and silently
/// WIDEN `not_in`, and both are wrong result sets reported as right ones.
///
/// It is its own test rather than a third loop in the one above, so that a guard covering the
/// inline six and not these two fails HERE and says which half it lost.
#[test]
fn a_membership_slot_refuses_the_whole_filter_for_one_element() {
  let over = CEILING + SignedDuration::from_nanos(1);
  let under = FLOOR - SignedDuration::from_nanos(1);
  let one = SignedDuration::from_secs(1);

  // The element is neither first nor last, so a walk that checked only an end would pass it.
  let crossed = leaked([
    ("in+", DurationFilter::new().with_in_([one, over, one])),
    (
      "notIn+",
      DurationFilter::new().with_not_in([one, over, one]),
    ),
    ("in-", DurationFilter::new().with_in_([one, under, one])),
    (
      "notIn-",
      DurationFilter::new().with_not_in([one, under, one]),
    ),
  ]);

  assert!(
    crossed.is_empty(),
    "these slots dropped an unstorable element instead of refusing the filter: {crossed:?}"
  );

  // …and a list whose every element fits still crosses whole, from one end of the range to the
  // other.
  let crossed = MongoDurationComparison::<i64>::try_from_filter(
    DurationFilter::new().with_in_([FLOOR, one, CEILING]),
  )
  .expect("every element is storable");
  assert_eq!(
    crossed.in_(),
    Some(&[i64::MIN, 1_000_000_000, i64::MAX][..])
  );
}

/// A PRESENT membership operator with an empty list asks for no documents, and an ABSENT one asks
/// for every document — the same truth table every other kind of this family reaches.
#[test]
fn an_empty_membership_list_is_the_operator_present() {
  let empty = MongoDurationComparison::<i64>::try_from_filter(
    DurationFilter::new().with_in_(Vec::<SignedDuration>::new()),
  )
  .expect("no operand is no refusal");
  assert_eq!(empty.conjuncts(), 1);
  assert_eq!(rendered(&empty, "len"), doc! { "len": { "$in": [] } });

  let absent = MongoDurationComparison::<i64>::new();
  assert!(absent.is_empty());
  assert!(rendered(&absent, "len").is_empty());
}

/// The projection an expansion writes for a duration field, resolved — and the ANNOTATION is the
/// assertion: the crossing must land on this kind, and the kind must be the one that lowers for this
/// backend.
#[test]
fn the_codegen_projection_resolves_for_a_duration_field() {
  type Crossed = <DurationFilter as ToDatabaseComparison<i64, Mongo>>::Comparison;

  let comparison: Crossed = MongoDurationComparison::<i64>::new();
  assert!(comparison.is_empty());
}

/// `V` is a real parameter and not decoration: a column that declares its own converter reaches a
/// different carrier, and with it a different RANGE — in both directions, since the converter is what
/// decides.
///
/// [`BeU64`] nanoseconds hold about 584 years where `i64` holds 292, and its blob is order-preserving
/// — `carrier`'s big-endian rows are what make `$lt` answer over one. It is also UNSIGNED, so a
/// column declaring it gives up the negative half of the operand entirely. The range check belongs to
/// the row rather than to this kind, which is what the differing ends show.
#[test]
fn a_declared_carrier_brings_its_own_ceiling() {
  use bson::{Binary, spec::BinarySubtype};

  use crate::BeU64;

  /// The declared converter: nanoseconds into the wide-integer escape.
  fn wide_nanos(value: SignedDuration) -> Result<BeU64, DurationOutOfRange> {
    u64::try_from(value.as_nanos())
      .map(BeU64)
      .map_err(|_| DurationOutOfRange)
  }

  let over_i64 = CEILING + SignedDuration::from_nanos(1);
  let crossed = MongoDurationComparison::<BeU64>::try_from_filter_with(
    DurationFilter::new().with_gt(over_i64),
    wide_nanos,
  )
  .expect("292 years fits a u64 of nanoseconds");

  assert_eq!(
    rendered(&crossed, "len"),
    doc! {
      "len": {
        "$gt": Binary {
          subtype: BinarySubtype::Generic,
          bytes: BeU64(9_223_372_036_854_775_808).to_blob().to_vec(),
        },
      }
    }
  );

  // Its own ceiling is still a refusal rather than a wrap. `u64::MAX` nanoseconds is past what
  // `SignedDuration::from_nanos` takes, so the boundary is spelled in seconds and nanoseconds.
  let u64_ceiling = SignedDuration::new(18_446_744_073, 709_551_615);
  assert_eq!(u64::try_from(u64_ceiling.as_nanos()), Ok(u64::MAX));
  assert_eq!(
    MongoDurationComparison::<BeU64>::try_from_filter_with(
      DurationFilter::new().with_gt(u64_ceiling + SignedDuration::from_nanos(1)),
      wide_nanos,
    )
    .unwrap_err(),
    DurationOutOfRange
  );

  // …and its FLOOR is zero, which is the half a declared carrier can decline outright: the `i64` row
  // stores this operand and this one cannot.
  let negative = SignedDuration::from_secs(-1);
  assert_eq!(
    MongoDurationComparison::<i64>::try_from_filter(DurationFilter::new().with_gt(negative))
      .expect("the default carrier is signed")
      .gt(),
    Some(&-1_000_000_000)
  );
  assert_eq!(
    MongoDurationComparison::<BeU64>::try_from_filter_with(
      DurationFilter::new().with_gt(negative),
      wide_nanos,
    )
    .unwrap_err(),
    DurationOutOfRange
  );
}