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 TERMINAL FATES: the three ways a delivery ends without ever reaching a station.
//!
//! A [`Station`](super::Station) is what a CONSUMER says about an item it was handed. A [`Fate`] is
//! what the FRAMEWORK says about a delivery no consumer will ever be handed: it was shed at a full
//! edge, its retries ran out, or the budget it was waiting under elapsed. Neither vocabulary can
//! stand in for the other — a shed item was never processed, so calling it
//! [`Skipped`](super::Station::Skipped) would claim an operator refused it, and calling it
//! [`Failed`](super::Station::Failed) would hold a window for work that is never coming back.
//!
//! # ONE vocabulary, two streams
//!
//! A fate is spoken on the delivery's own oneshot — which is what credits the sender's window and
//! keeps a terminal from surfacing as an anonymous *the consumer hung up* — and it is spoken again
//! to the [`LifecycleTap`](super::LifecycleTap)s, as an [`Observation`]. The two are the same words
//! because they are built from the same value: [`Fate::erase`] is the one crossing, and every
//! terminal the oneshot can speak is therefore a terminal the observation stream can see.
//!
//! # The extra message, and why it is a parameter
//!
//! `Fate<M>` carries whatever the party that ended the delivery wanted to say beyond the fact of the
//! ending, and `M` defaults to `()` because most endings have nothing to add. The framework's own
//! three sites all end deliveries at the default; the parameter is there for the deployment whose
//! shed carries a reason its own downstream knows how to read. It takes NO bound here — the single
//! bound is at the erased boundary, [`AckSender::fate`](super::AckSender::fate), exactly as
//! [`Lifecycle`](super::Lifecycle)'s own info parameter does and for the same reason.

use jiff::SignedDuration;

use super::{
  lifecycle::{Failure, Observation},
  policy::{Occupancy, OverflowDecision, ShedKey},
};

#[cfg(test)]
mod tests;

/// HOW A DELIVERY ENDED, where it ended without reaching a station.
///
/// # The terminals are CLOSED and the message is OPEN
///
/// The three variants are the whole table for the same reason
/// [`Lifecycle`](super::Lifecycle)'s four stations are: the framework MATCHES on them — the ack path
/// to decide what to answer, the tap path to decide what to say — so a fourth kind of ending would
/// be a thing neither knows how to perform. `M` is the opposite, and is whatever the party that
/// ended the delivery has to add.
///
/// `#[non_exhaustive]`, so a later concern's terminal is a widening: a matcher outside this crate
/// carries a wildcard and keeps compiling through it.
///
/// # Why it CLONES
///
/// One ending can be owed to SEVERAL senders. A keyed group's delivery is answered on the token of
/// every member that joined it — see [`Custody`](super::Custody) — and the ending they are told is
/// one ending, so it travels by value to each of them. `M: Clone` is the caller's to satisfy and the
/// framework's own three sites all end at `()`, which clones nothing.
// No `Unwrap`/`TryUnwrap` beside `IsVariant`, and it is the shape rather than a preference:
// `derive_more` refuses a struct variant ("cannot unwrap anonymous records"), and the payloads here
// are named fields because a shed carries three of them and a positional tuple would make the call
// site read `fate.0`. `terminal()` is the projection those derives would have been used for.
#[derive(Debug, Clone, derive_more::IsVariant)]
#[non_exhaustive]
pub enum Fate<M = ()> {
  /// The delivery was DROPPED at a full edge, because an
  /// [`OverflowPolicy`](super::OverflowPolicy) said to.
  ///
  /// A delivery is shed WHOLE — the eviction hand takes a message out, never an item out of a
  /// message — so `key` names the first item it carried and the answer's own released set names
  /// every one of them. The per-item obituaries are recorded beside this by
  /// [`Sheds::deliver`](super::Sheds::deliver), which is where a batch's other keys are spoken.
  Shed {
    /// The COMPLETE item key, and never the root id alone — see [`ShedKey`].
    key: ShedKey,
    /// Which shed this was.
    decision: OverflowDecision,
    /// How full the edge was when the policy answered.
    occupancy: Occupancy,
    /// What the shedding party had to add.
    message: M,
  },
  /// A [`RetryPolicy`](super::RetryPolicy) stopped trying.
  ///
  /// It is the counterpart of [`Observation::Retrying`] and the arm that was silent before this
  /// vocabulary existed: a retry that is scheduled is announced, and a retry that is NOT was the
  /// same event with nothing said about it.
  GivenUp {
    /// Which attempt was the last — the first is `1`.
    attempt: u32,
    /// What it failed with, where the failure travelled.
    ///
    /// `None` where the give-up was decided from a bare error rather than from a
    /// [`Failure`] — [`Retries::on_failure`](super::Retries::on_failure) is shown
    /// `&dyn Error`, which is neither owned nor `Send + Sync` and so cannot become one.
    /// [`Retries::settling`](super::Retries::settling) is handed the failure itself and passes it
    /// on.
    failure: Option<Failure>,
    /// What the giving-up party had to add.
    message: M,
  },
  /// A DEADLINE elapsed before the answer arrived.
  ///
  /// The budget is the one that was actually in force — a call site's own where it named one, the
  /// [`DeadlinePolicy`](super::DeadlinePolicy)'s where it did not. What the CALLER is told about
  /// the same moment is [`QueryError::TimedOut`](super::QueryError::TimedOut), and the two are not
  /// a duplication: one is the asker's answer and this is the arrangement's record, and neither
  /// can be computed from the other.
  Expired {
    /// How long the wait was allowed to be.
    budget: SignedDuration,
    /// What the timing-out party had to add.
    message: M,
  },
}

impl<M> Fate<M> {
  /// Which terminal this is, without the payload.
  #[inline]
  #[must_use]
  pub const fn terminal(&self) -> Terminal {
    match self {
      Self::Shed { .. } => Terminal::Shed,
      Self::GivenUp { .. } => Terminal::GivenUp,
      Self::Expired { .. } => Terminal::Expired,
    }
  }

  /// What the party that ended the delivery had to add.
  #[inline]
  #[must_use]
  pub const fn message(&self) -> &M {
    match self {
      Self::Shed { message, .. }
      | Self::GivenUp { message, .. }
      | Self::Expired { message, .. } => message,
    }
  }

  /// Split into WHAT BOTH STREAMS SPEAK and the extra message only an ack carries.
  ///
  /// The [`Observation`] is what a tap is shown and what the oneshot's answer states; the message
  /// travels BESIDE it rather than inside it, because no arm of the observation stream is widened
  /// to make room for it. A fate ends up in exactly two places and this is the one crossing to
  /// both.
  ///
  /// One rule for all three terminals, and no arm is a special case: the fate's own arm names the
  /// observation's arm, every other field crosses unchanged, and `message` is what is left in the
  /// caller's hand. [`Shed`](Observation::Shed) is the arm the stream carried before this
  /// vocabulary existed and the other two are shaped after it, so the crossing has nothing to
  /// decide.
  #[inline]
  #[must_use]
  pub fn erase(self) -> (Observation, M) {
    match self {
      Self::Shed {
        key,
        decision,
        occupancy,
        message,
      } => (
        Observation::Shed {
          key,
          decision,
          occupancy,
        },
        message,
      ),
      Self::GivenUp {
        attempt,
        failure,
        message,
      } => (Observation::GivenUp { attempt, failure }, message),
      Self::Expired { budget, message } => (Observation::Expired { budget }, message),
    }
  }
}

/// The terminal table on its own — what a tap counts and what an account balances against.
///
/// [`Station`](super::Station)'s sibling, and deliberately a separate word: a station is where an
/// item ARRIVED and a terminal is where a delivery ENDED, and an account that added them into one
/// column would be counting two different things.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, derive_more::Display, derive_more::IsVariant)]
#[display("{}", self.as_str())]
#[non_exhaustive]
pub enum Terminal {
  /// [`Fate::Shed`].
  Shed,
  /// [`Fate::GivenUp`].
  GivenUp,
  /// [`Fate::Expired`].
  Expired,
}

impl Terminal {
  /// A stable name for a tap, a journal and logs.
  #[inline]
  #[must_use]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Shed => "shed",
      Self::GivenUp => "given_up",
      Self::Expired => "expired",
    }
  }
}