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 second citizen: [`TimeRanged<T>`], a payload beside the stretch of timeline it occupies, and
//! the filter that guards one.

use core::fmt;

use crate::{
  CompositeFilterMarker, CompositeMarker, DefaultMarker, DefaultVecMarker, GraphqlFilter,
  QuantifiedMarker,
};

use super::{PayloadFilter, TimeRange, TimeRangeFilter};

/// A `T` and WHEN it was — the shape a timed analysis emits, with the timing held once and the
/// payload left alone.
///
/// ```text
///   Vec<TimeRanged<DetectedLanguage>>   which language was spoken, span by span
///   Vec<TimeRanged<()>>                 where the speech was, and nothing about it
/// ```
///
/// # The RANGE is a [`TimeRange`] and not two instants, which is the whole point of the pair
///
/// A payload with `start` and `end` fields of its own carries the invariant nowhere: nothing stops
/// the two being written in the wrong order, and every reader has to decide again what to do about
/// it. Holding a [`TimeRange`] makes `start <= end` a property of the value rather than a rule about
/// it, and it makes the four columns, the sub-document, the cursor and the three interval words the
/// range's own rather than this type's.
///
/// # `T` IS THE PARAMETER, and this type asks nothing of it
///
/// No bound on the struct. What a payload owes is asked at each FACE and nowhere else — a stored one
/// owes [`ColumnKind`](crate::ColumnKind) and its carriers, a crossed one owes the wire rows, a
/// filtered one owes a default marker — so a `TimeRanged<T>` over a payload with none of them is
/// still a value a caller can build, hold and match on. That is the same posture
/// [`Confidence<S>`](crate::Confidence) takes with a difference worth naming: a confidence's width
/// vocabulary is SEALED because each member is a measurement, and a payload vocabulary is OPEN
/// because a payload is whatever a declaration holds.
///
/// # Equality is the PAIR's, and there is NO order
///
/// [`Eq`] and [`Hash`] are derived and compose the two halves. [`Ord`] is NOT, and the reason is
/// [`TimeRange`]'s: that type declines it because a stretch has three candidate orders and no
/// single one to derive, so a pair holding one cannot manufacture the order its half refuses. The
/// KEYSET's order is a storage fact stated at [`CursorValue`](crate::CursorValue)'s row in this
/// house's `storage` module, where a page's need for *an* order does not become a claim about
/// *the* order.
///
/// # Examples
///
/// ```
/// use ingraph::{TimeRange, TimeRanged, Timestamp};
///
/// let start: Timestamp = "2026-08-28T09:00:00Z".parse().unwrap();
/// let end: Timestamp = "2026-08-28T09:01:00Z".parse().unwrap();
/// let minute = TimeRange::new(start, end).unwrap();
///
/// let spoken = TimeRanged::new(minute, "zh");
/// assert_eq!(spoken.range().start(), start);
/// assert_eq!(*spoken.data(), "zh");
///
/// // The payload moves without the timing being rebuilt.
/// let upper = spoken.map(str::to_uppercase);
/// assert_eq!(upper.range(), &minute);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TimeRanged<T> {
  range: TimeRange,
  data: T,
}

impl<T> TimeRanged<T> {
  /// A payload at a stretch.
  ///
  /// Infallible, because the only invariant either half has is already kept: a [`TimeRange`] cannot
  /// hold a pair its own door refused, and a payload's own invariants are the payload's.
  #[inline]
  #[must_use]
  pub const fn new(range: TimeRange, data: T) -> Self {
    Self { range, data }
  }

  /// The stretch of timeline this payload occupies.
  #[inline]
  #[must_use]
  pub const fn range(&self) -> &TimeRange {
    &self.range
  }

  /// The payload.
  #[inline]
  #[must_use]
  pub const fn data(&self) -> &T {
    &self.data
  }

  /// The two halves, taken apart.
  ///
  /// The one door that MOVES the payload out, for the reason every `into_parts` on a composite here
  /// is written: a caller that owns the pair should not have to clone the half it wants.
  #[inline]
  #[must_use]
  pub fn into_parts(self) -> (TimeRange, T) {
    (self.range, self.data)
  }

  /// The same stretch, with the payload replaced by `f`'s answer.
  ///
  /// What a decoding or an enrichment pass actually does: the timing is already right and only the
  /// payload changes, so rebuilding the range would be a second chance to get it wrong.
  #[inline]
  #[must_use]
  pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> TimeRanged<U> {
    TimeRanged {
      range: self.range,
      data: f(self.data),
    }
  }
}

/// The payload, then its stretch in brackets — `zh (2026-08-28T09:00:00Z/2026-08-28T09:01:00Z)`.
///
/// A RENDERING rather than a round trip, exactly as
/// [`DetectedLanguage`](crate::DetectedLanguage)'s is and for its reason: the pair has no spelling
/// any standard defines.
impl<T: fmt::Display> fmt::Display for TimeRanged<T> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "{} ({})", self.data, self.range)
  }
}

/// What guards a [`TimeRanged<T>`] column: the RANGE's own filter, and the PAYLOAD's own filter.
///
/// | facet | slot | operand | asks about |
/// |---|---|---|---|
/// | RANGE | `range` | [`TimeRangeFilter`] | the stretch — three interval words and two ends |
/// | PAYLOAD | `data` | `T`'s own filter | whatever the payload's own family asks |
///
/// # The two guard ONE value, and that is why they share a filter
///
/// It is [`DetectedLanguageFilter`](crate::DetectedLanguageFilter)'s argument at a different pair. A
/// track carries several timed detections; asked separately, *Chinese* and *in the first minute*
/// would be answered by a track speaking English in the first minute and Chinese in the tenth — each
/// half true of a different span. Holding both in one filter over ONE span makes that
/// unrepresentable rather than merely wrong, and the quantified reading below is what carries it to a
/// collection.
///
/// # NEITHER facet flattens, and the reason is that `T` is a PARAMETER
///
/// [`DetectedLanguageFilter`] splices its identity because it knows what that identity's slots are
/// called. This face cannot know: `TF`'s slot names are the payload family's, so a splice would put
/// two independent field sets in one namespace with nothing able to say whether they collide. Both
/// facets therefore keep their names, on the wire and — for the payload — in the columns as well.
///
/// The RANGE's columns are the one place the two answers differ, and the argument is made where the
/// segments are: see this house's `storage` module.
///
/// # `TF` rather than `T`, and the alias that resolves one from the other
///
/// The parameter is the payload's FILTER because that is what this struct holds, which is
/// [`ListFilter`](crate::ListFilter)'s own shape. A caller naming the payload instead spells
/// [`PayloadFilter<T>`](super::PayloadFilter), which is the path the marker rows below take.
pub struct TimeRangedFilter<TF> {
  pub(crate) range: Option<TimeRangeFilter>,
  pub(crate) data: Option<TF>,
}

impl<TF> TimeRangedFilter<TF> {
  /// The empty filter — no operator set on either facet.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self {
      range: None,
      data: None,
    }
  }

  /// The stretch's filter.
  #[inline]
  #[must_use]
  pub const fn range(&self) -> Option<&TimeRangeFilter> {
    self.range.as_ref()
  }

  /// The payload's filter.
  #[inline]
  #[must_use]
  pub const fn data(&self) -> Option<&TF> {
    self.data.as_ref()
  }

  /// Replace the stretch's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_range(mut self, range: TimeRangeFilter) -> Self {
    self.set_range(range);
    self
  }

  /// Replace the stretch's filter (in place).
  #[inline]
  pub fn set_range(&mut self, range: TimeRangeFilter) -> &mut Self {
    self.range = Some(range);
    self
  }

  /// Replace the payload's filter (consuming).
  #[must_use]
  #[inline]
  pub fn with_data(mut self, data: TF) -> Self {
    self.set_data(data);
    self
  }

  /// Replace the payload's filter (in place).
  #[inline]
  pub fn set_data(&mut self, data: TF) -> &mut Self {
    self.data = Some(data);
    self
  }
}

impl<TF: GraphqlFilter> TimeRangedFilter<TF> {
  /// True while NO operator slot is set on EITHER facet.
  ///
  /// The bound is on this ONE method rather than on the type, which is the arrangement every generic
  /// filter kind here takes: what emptiness MEANS for the payload is the payload filter's own
  /// answer, and a filter whose payload family does not publish one is still a filter a caller can
  /// build.
  pub fn is_empty(&self) -> bool {
    self.range.as_ref().is_none_or(TimeRangeFilter::is_empty)
      && self.data.as_ref().is_none_or(GraphqlFilter::is_empty)
  }
}

/// The bound's row: [`is_empty`](TimeRangedFilter::is_empty), reached where the kind is a parameter
/// rather than a spelling.
impl<TF: GraphqlFilter> GraphqlFilter for TimeRangedFilter<TF> {
  #[inline]
  fn is_empty(&self) -> bool {
    Self::is_empty(self)
  }
}

impl<TF> Default for TimeRangedFilter<TF> {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

// `Debug`, `Clone` and `PartialEq` are written out rather than derived, for the reason
// `ScalarFilter`'s are: a derive puts its bound on EVERY parameter, and here that is the same bound
// this file wants — but writing them out keeps the three consistent with the rest of the filter
// family and leaves the door open for a parameter that carries no such row.
impl<TF: fmt::Debug> fmt::Debug for TimeRangedFilter<TF> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("TimeRangedFilter")
      .field("range", &self.range)
      .field("data", &self.data)
      .finish()
  }
}

impl<TF: Clone> Clone for TimeRangedFilter<TF> {
  fn clone(&self) -> Self {
    Self {
      range: self.range.clone(),
      data: self.data.clone(),
    }
  }
}

impl<TF: PartialEq> PartialEq for TimeRangedFilter<TF> {
  fn eq(&self, other: &Self) -> bool {
    self.range == other.range && self.data == other.data
  }
}

/// What guards a [`TimeRanged<T>`] column — its own filter at both seats, the same reading
/// [`TimeRange`]'s row takes.
///
/// The payload's filter is resolved through [`PayloadFilter<T>`](super::PayloadFilter) rather than
/// listed, which is what keeps this row FRAMEWORK-OPEN: a payload type declared in a downstream
/// crate reaches this filter by having a default marker, which every column type already has.
impl<T> CompositeFilterMarker for TimeRanged<T>
where
  T: DefaultMarker,
{
  type Filter = TimeRangedFilter<PayloadFilter<T>>;
  type ColumnFilter = TimeRangedFilter<PayloadFilter<T>>;
}

/// The interpretation a [`TimeRanged<T>`] field is read under — the COMPOSITE reading, for
/// [`TimeRange`]'s reason: the value occupies columns of its own, all of which can be absent
/// together.
///
/// The bound is the PAYLOAD's own default, and it is the membership rule spelled as a bound exactly
/// as [`Confidence<S>`](crate::Confidence)'s width rows spell theirs: a timed payload has a default
/// interpretation wherever its payload has one. A payload with none reaches `E0277` naming ITSELF,
/// which is the sentence a declaration's author can act on — where a row without the bound would
/// have named this wrapper and left them to work out which half was missing.
impl<T: DefaultMarker> DefaultMarker for TimeRanged<T> {
  type Marker = CompositeMarker<TimeRanged<T>>;
}

/// **A COLLECTION of timed payloads is asked through the QUANTIFIERS alone** — [`TimeRange`]'s row,
/// and its argument holds here with one clause added.
///
/// `any` carries the whole [`TimeRangedFilter`], so *some Chinese was spoken in the first minute* is
/// one element question: `any: { range: { overlaps: … }, data: { language: { eq: "zh" } } }`. That
/// is the shape this whole house was ruled for, and the seven operators a list reading would add
/// each hold a WHOLE timed payload — an operand pairing an exact nanosecond span with an exact
/// payload value, which is a row a caller can seldom spell and never means as a question.
impl<T: DefaultMarker> DefaultVecMarker for TimeRanged<T> {
  type Marker = QuantifiedMarker<Vec<TimeRanged<T>>>;
}