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 CRON SEAM, runtime side: when is a calendar expression next due?
//!
//! # The seam existed because the implementation was temporary — and it has been replaced
//!
//! The ruling that put cron in v1 said what rides underneath it: a third-party crate FIRST, and the
//! user's own implementation later. The later has arrived. What changed is what this module calls;
//! what did not change is a single word an author writes, a single variant of
//! [`Recurrence`](super::Recurrence), or a single engine — which is what the seam was built to make
//! possible, and this swap is the measurement that it did.
//!
//! Its twin is `ingraph-codegen`'s `cron`, which refuses a garbage expression AT EXPANSION. Two
//! halves rather than one because the build order forbids one: this crate expands THROUGH the
//! derive, which is built on that one, so it cannot reach it. A swap touches both, and the
//! FIVE-FIELD rule is stated in both for the same reason.
//!
//! # What the crate does, and what THIS MODULE does
//!
//! `cronp` PARSES and does not evaluate. It reads an expression into a bitset per field, takes its
//! dialect as a type parameter, and answers *does this field admit this value* — and, for the two
//! day fields, whose combination is a rule of the dialect rather than an `and`, *does this calendar
//! match this civil datetime*. There is still no next-occurrence call to make, and that is the point
//! rather than a shortfall: **the walk from a civil datetime to an instant is where every DST
//! decision lives**, so a seam that owns the walk owns the decisions, where one that delegated it
//! could only record whatever the delegate chose.
//!
//! The DIALECT is `Vixie`, and its own constants are the pins this framework used to state by hand:
//! five fields, no seconds field, no year field, and day-of-month against day-of-week the classic
//! `Union` — `0 3 1 * MON` fires on the first AND on every Monday. The five-field count is still
//! checked here, because the useful sentence is not *that parses as six fields* but *a timezone is
//! not a sixth field, there is a word for it*.
//!
//! # THE TWO RULED DST PINS ARE HONOURED
//!
//! They were recorded as deviations while the evaluator belonged to somebody else. They are law now,
//! and each is one arm of `Calendar::instant_of`:
//!
//!   * a NONEXISTENT local time — the spring-forward gap — FIRES ONCE, AT THE GAP'S END. `30 2 * *
//!     *` in `America/New_York` has no 02:30 on 2026-03-08, and the schedule fires at 03:00-04:00,
//!     the first instant that exists after the gap. Every civil minute inside the gap maps to that
//!     same instant, so a schedule naming several of them still fires once: the walk answers
//!     strictly after what it was given, and an instant already passed is not offered twice.
//!   * a REPEATED local time — the fall-back fold — FIRES ONCE, AT THE FIRST OCCURRENCE. The same
//!     schedule at `30 1 * * *` fires at 01:30-04:00 on 2026-11-01 and not again at 01:30-05:00.
//!     Which of the two is *the* one is the ruled half; what makes it structural rather than a
//!     filter is that the walk enumerates CIVIL times and maps each to exactly one instant, so the
//!     second pass of a repeated hour is never a candidate at all.
//!
//! The second pin has a consequence worth meeting here rather than in production: a schedule firing
//! several times inside a repeated hour — `*/15 * * * *` — loses that hour's second pass, four
//! firings once a year. That is what *a repeated local time fires once* MEANS, and the poll
//! doctrine's own requirement that a sweep be idempotent is what makes it affordable.
//!
//! # The zone is the RUNNING machine's, never the building machine's
//!
//! `tz = "<IANA>"` names a zone and the absence of it means the system's, and both are resolved
//! HERE — expansion happens wherever the build happens, and a schedule that meant three in the
//! morning meant it where the program runs.

use core::time::Duration;

use std::sync::Arc;

use cronp::{CivilDateTime, Schedule, Vixie};
use jiff::{
  Timestamp, Zoned, civil,
  tz::{AmbiguousOffset, TimeZone},
};

/// How many fields a cron expression has here: the classic five — minute, hour, day of month,
/// month, day of week.
///
/// Checked by THIS framework even though the dialect now states it too, and the reason is the
/// SENTENCE rather than the rule: `Vixie` would refuse a sixth field as a parse error, and what a
/// reader needs to be told is that a timezone is not a sixth field because there is a word for it.
/// Stated in `ingraph-codegen`'s half of the seam as well, since the build order gives the two no
/// way to share it.
const FIELDS: usize = 5;

/// How far ahead a walk looks before it answers *never*.
///
/// FOUR YEARS, which is the leap cycle: `0 0 29 2 *` is the sparsest expression this dialect can
/// write, and four years is what it takes to be sure one exists. An expression that names no day in
/// four years — `0 0 30 2 *`, February the thirtieth — names none ever, and a clock told *never*
/// stops asking instead of waking forever on a schedule that will not fire.
const HORIZON_DAYS: i32 = 366 * 4;

/// ONE calendar expression, read, with the zone it is evaluated in.
///
/// Constructed once at wiring time and asked for its next due date forever after, which is why the
/// parse is fallible and the asking is not.
///
/// BEHIND A POINTER, and that is about the two things holding one: a
/// [`Recurrence`](super::Recurrence) is an enum whose other arm is a [`Duration`], and a schedule is
/// CLONED once per entry to mint its cadences. A parsed expression and a time zone are neither small
/// nor cheap to copy, so they are shared instead — the value is immutable once read, which is what
/// makes sharing it indistinguishable from owning it.
#[derive(Debug, Clone)]
pub struct Calendar {
  read: Arc<Read>,
}

/// A calendar's contents, behind the pointer.
#[derive(Debug)]
struct Read {
  expression: String,
  calendar: cronp::Calendar<Vixie>,
  zone: TimeZone,
  /// The clock the DAY question is asked at — see [`admits_day`], which is its only reader.
  ///
  /// The first hour and the first minute the expression admits. Held rather than searched for per
  /// day because neither can change: the expression is read once and never again.
  probe: (u8, u8),
}

impl Calendar {
  /// Read `expression` in the SYSTEM's zone — what a schedule with no zone word means.
  ///
  /// The desktop posture the design record names: *three in the morning* means the user's three in
  /// the morning, and the machine that answers what that is is the one running the program.
  ///
  /// # Errors
  /// [`CalendarError`], carrying the expression with the offending run under a caret.
  pub fn parse(expression: &str) -> Result<Self, CalendarError> {
    Self::read(expression, TimeZone::system())
  }

  /// Read `expression` in `zone`, an IANA name — what `tz = "…"` beside a cron word means.
  ///
  /// # Errors
  /// [`CalendarError`], carrying the expression's own diagnosis or the zone's. A zone this machine's
  /// database does not have is refused here, which is the honest place: a schedule that cannot be
  /// evaluated must not silently become one that never fires.
  pub fn parse_in(expression: &str, zone: &str) -> Result<Self, CalendarError> {
    let zone = TimeZone::get(zone).map_err(|refusal| CalendarError(refusal.to_string()))?;
    Self::read(expression, zone)
  }

  /// The five-field guard, then the parse, then the zone it is bound to.
  fn read(expression: &str, zone: TimeZone) -> Result<Self, CalendarError> {
    let written = expression.split_ascii_whitespace().count();
    if written != FIELDS {
      return Err(CalendarError(format!(
        "a cron expression is the classic {FIELDS} fields — minute, hour, day of month, month, day \
         of week — and this one has {written}"
      )));
    }
    let schedule = Schedule::<Vixie>::parse(expression)
      .map_err(|refusal| CalendarError(caret(expression, &refusal)))?;
    // A NICKNAME reaches no calendar, and the five-field count has already excluded every one of
    // them — `@reboot` and `@daily` are one field each. The arm is WRITTEN rather than unwrapped, so
    // that a dialect admitting a five-field nickname would be a refusal here instead of a panic
    // inside a wiring walk.
    let Some(calendar) = schedule.calendar() else {
      return Err(CalendarError(format!(
        "`{expression}` names no set of calendar instants, so there is no next occurrence for a \
         clock to wait for"
      )));
    };
    // A restricted field writes at least one bit and an unrestricted one admits every value, so both
    // searches find something. The fallback is not load-bearing: a calendar admitting no hour names
    // no instant, and a probe at an hour it refuses makes every day refuse, which is the same
    // *never* the hour loop below would have walked to.
    let probe = (
      (0..24u8)
        .find(|&hour| calendar.admits_hour(hour))
        .unwrap_or(0),
      (0..60u8)
        .find(|&minute| calendar.admits_minute(minute))
        .unwrap_or(0),
    );
    Ok(Self {
      read: Arc::new(Read {
        expression: expression.to_owned(),
        calendar: *calendar,
        zone,
        probe,
      }),
    })
  }

  /// The expression as it was written.
  #[inline]
  #[must_use]
  pub fn expression(&self) -> &str {
    &self.read.expression
  }

  /// How long from NOW until this expression is next due, or `None` where it never is again.
  ///
  /// `None` is a real answer rather than a failure to compute one: an expression can name a date the
  /// calendar never reaches — February the thirtieth — and a clock told *never* stops asking instead
  /// of waking forever on a schedule that will not fire.
  #[must_use]
  pub fn until_next(&self) -> Option<Duration> {
    let now = Timestamp::now();
    let next = self.next_after(now)?;
    let wait = next.timestamp() - now;
    // Saturating at zero rather than refusing. The door below answers STRICTLY after what it was
    // given, so a negative gap needs a clock that moved backwards between the two lines — and a due
    // date in the past is due NOW, which is what a zero wait says to all three engines.
    if wait.is_negative() {
      return Some(Duration::ZERO);
    }
    Duration::try_from(wait).ok()
  }

  /// The next occurrence strictly after `from`, in this calendar's own zone.
  ///
  /// THE WHOLE EVALUATOR, and it is this framework's rather than a crate's — which is what lets the
  /// two ruled DST pins be law instead of measurements. It takes its `from` rather than reading the
  /// clock so that the suite beside this module can drive it across a transition and pin what it
  /// does.
  ///
  /// # The walk is by DAY and then by time, which is what keeps it cheap
  ///
  /// A sparse expression — `0 0 29 2 *` — is four years of days away, and a minute-by-minute scan
  /// would be two million steps to find it. A day is answered by ONE [`admits_day`] probe — a fixed
  /// handful of bitset reads — so a day the month or the day rule refuses costs that and nothing
  /// more; only an admitted day pays for its hours and minutes.
  ///
  /// # It compares INSTANTS and never civil times
  ///
  /// A candidate is offered when the instant it maps to is after `from`. That is what makes both DST
  /// pins fall out of the walk rather than being filtered for: every civil minute inside a gap maps
  /// to one instant, so a `from` already at that instant skips all of them, and a repeated hour's
  /// second pass is not a candidate because no civil time maps to it.
  fn next_after(&self, from: Timestamp) -> Option<Zoned> {
    let read = &*self.read;
    let calendar = &read.calendar;
    let mut date = from.to_zoned(read.zone.clone()).date();
    for _ in 0..HORIZON_DAYS {
      if admits_day(read, date) {
        for hour in 0..24u8 {
          if !calendar.admits_hour(hour) {
            continue;
          }
          for minute in 0..60u8 {
            if !calendar.admits_minute(minute) {
              continue;
            }
            // `i8` is jiff's own spelling for a civil clock field, and the two values are bounded by
            // the loops above — so the cast is a change of spelling rather than a narrowing.
            #[expect(
              clippy::cast_possible_wrap,
              reason = "0..24 and 0..60 are inside i8 by construction"
            )]
            let civil = date.at(hour as i8, minute as i8, 0, 0);
            let Some(when) = self.instant_of(civil) else {
              continue;
            };
            if when > from {
              return Some(when.to_zoned(read.zone.clone()));
            }
          }
        }
      }
      date = date.tomorrow().ok()?;
    }
    None
  }

  /// WHICH INSTANT a civil datetime is, in this calendar's zone — and the whole of the DST law.
  ///
  /// Three answers for three shapes, and the two interesting ones are the ruled pins:
  ///
  ///   * UNAMBIGUOUS — the overwhelming majority — is the offset applied.
  ///   * a FOLD takes the offset in effect BEFORE it, which is the FIRST of the two occurrences. The
  ///     second is not filtered out; it is never named, one civil time yielding one instant.
  ///   * a GAP is the TRANSITION itself, which is the gap's end. It is computed rather than
  ///     approximated: interpreting the civil time with the AFTER offset lands strictly before the
  ///     transition — the gap being exactly as wide as the two offsets differ — so the next
  ///     transition from there is the instant the gap ends at.
  ///
  /// `None` only where the arithmetic leaves what an instant can hold, which is a date near jiff's
  /// own ±9999 limit; a clock told *never* is the honest answer there too.
  fn instant_of(&self, civil: civil::DateTime) -> Option<Timestamp> {
    match self.read.zone.to_ambiguous_timestamp(civil).offset() {
      AmbiguousOffset::Unambiguous { offset } => offset.to_timestamp(civil).ok(),
      AmbiguousOffset::Fold { before, .. } => before.to_timestamp(civil).ok(),
      AmbiguousOffset::Gap { after, .. } => {
        let probe = after.to_timestamp(civil).ok()?;
        self
          .read
          .zone
          .following(probe)
          .next()
          .map(|transition| transition.timestamp())
      }
    }
  }
}

/// Whether this DATE is one the expression names — ASKED OF THE DIALECT rather than spelled here.
///
/// The dom/dow rule used to be written out in this function, off four accessors the dialect no
/// longer offers. That it is applied inside the dialect now is a correction and not only a tidying:
/// the hand-spelling could not see WHERE the wildcard sat, and Vixie's union rule turns on exactly
/// that. `10,*` and `*,10` name one set of days — every one of them — and land on opposite sides of
/// the rule, while the restricted-flags the old arm read share one value across the pair, so both
/// spellings could only ever be given one answer here. `wildcard.rs` beside this module is where the
/// two are pinned apart.
///
/// # ONE probe answers the whole day
///
/// [`cronp::Calendar::matches`] asks a civil datetime where this asks a date, so the day question is
/// put to it at [`Read::probe`] — a time the expression admits. Every term `matches` adds beyond the
/// date is then either passed by that construction (hour, minute, second) or is a test this walk
/// wanted anyway (year, month), so the answer belongs to the day rather than to the clock it was
/// asked at, and a day still costs a fixed handful of bitset reads.
///
/// A date `cronp` cannot NAME is not a day. Its calendar runs year 1 to 9999 where jiff's runs -9999
/// to 9999, so the LOW end is the only one a walk can reach, and a walk that has left the range
/// answers *never* — the same answer [`Calendar::instant_of`] gives where the arithmetic leaves what
/// an instant can hold.
fn admits_day(read: &Read, date: civil::Date) -> bool {
  // jiff spells a civil year signed, so this is a real question rather than a change of spelling: a
  // year before the common era is not one cronp's calendar has, and `try_from` refuses it where a
  // cast would wrap it into one that looks legal.
  let Ok(year) = u16::try_from(date.year()) else {
    return false;
  };
  #[expect(
    clippy::cast_sign_loss,
    reason = "a civil month is 1..=12 and a day 1..=31; jiff spells both signed"
  )]
  let (month, day) = (date.month() as u8, date.day() as u8);
  let (hour, minute) = read.probe;
  CivilDateTime::new(year, month, day, hour, minute, 0)
    .is_ok_and(|when| read.calendar.matches(when))
}

/// A parse refusal with the expression under it and a caret on the offending run.
///
/// The TWIN of `ingraph-codegen`'s `cron::caret`, written out twice because the build order gives
/// the two crates no way to share one — the reason [`FIELDS`] is stated twice. Kept identical by
/// `the_two_halves_render_one_caret` in the suite beside this module.
///
/// The caret is at least one column wide, because an empty span is a real answer: a parser that ran
/// out of input points AT the end, and a marker with no width would point at nothing.
fn caret(expression: &str, refusal: &cronp::ParseError) -> String {
  let span = refusal.span();
  // BYTE offsets from the parser, COLUMNS on the page. The two differ the moment an expression
  // carries a non-ASCII byte — which a garbage one may — so the pad is counted in characters over
  // the text actually printed rather than assumed equal to the offset.
  let start = expression
    .get(..span.start())
    .map_or(0, |before| before.chars().count());
  let width = expression
    .get(span.start()..span.end())
    .map_or(1, |marked| marked.chars().count().max(1));
  format!(
    "{refusal}\n  {expression}\n  {pad}{caret}",
    pad = " ".repeat(start),
    caret = "^".repeat(width),
  )
}

/// Why a calendar expression could not be read.
///
/// It carries TEXT rather than a taxonomy, and that is the seam's doing rather than laziness: the
/// categories a cron parser refuses in are the implementation's, so a typed error here would be the
/// one part of this module a swap could not replace without changing a public type. What the text
/// is, is the implementation's own sentence with the expression under it and a caret on the run that
/// broke.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CalendarError(String);

impl core::fmt::Display for CalendarError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.write_str(&self.0)
  }
}

impl core::error::Error for CalendarError {}

#[cfg(test)]
mod tests;
#[cfg(test)]
mod wildcard;