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::SignedDuration;

use super::{
  Backpressure, CatchUp, Coalesce, Concern, DeadlinePolicy, DropNewest, DropOldest, Missed,
  NoDeadline, NoRetry, Occupancy, OverflowDecision, OverflowPolicy, Policies, PollUpstream,
  QueryDeadline, RetryDecision, RetryPolicy, ShedKey, TickDecision, TickPolicy,
};
// THE WIRE SIDE OF THE SAME NUMBER, reached where it now lives. The two CONTRAST assertions below
// are this module's and stay here — the arithmetic's own suite moved with the function, and what a
// reader needs at THIS seat is the pair asserted side by side so a later round cannot quietly align
// them.
use crate::retrieve::tightened_budget;

/// The first poll upstream, which is what every one-entry fixture here means.
fn first() -> PollUpstream {
  PollUpstream::new(0)
}

/// An error a policy hands back when it will not decide.
#[derive(Debug, derive_more::Display)]
#[display("the advisor has no opinion")]
struct NoOpinion;

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

#[test]
fn the_four_concerns_render_as_a_report_names_them() {
  assert_eq!(Concern::Tick.as_str(), "tick");
  assert_eq!(Concern::Retry.as_str(), "retry");
  assert_eq!(Concern::Overflow.as_str(), "overflow");
  assert_eq!(Concern::Deadline.as_str(), "deadline");
  assert_eq!(Concern::Overflow.to_string(), "overflow");
  assert!(Concern::Deadline.is_deadline());
}

/// **THE SHIPPED FOUR ARE TODAY'S BEHAVIOUR.** Each one is asked directly, because *the seam is a
/// pure widening* is a claim about exactly these four answers.
#[test]
fn the_shipped_policies_answer_what_the_framework_already_did() {
  assert_eq!(
    Coalesce
      .on_missed(Missed::new(first(), 9))
      .expect("the shipped tick policy never refuses"),
    TickDecision::Coalesce
  );
  assert_eq!(
    NoRetry
      .on_failure(3, &NoOpinion)
      .expect("the shipped retry policy never refuses"),
    RetryDecision::GiveUp
  );
  assert_eq!(
    Backpressure
      .on_full(Occupancy::bounded(32, 32))
      .expect("the shipped overflow policy never refuses"),
    OverflowDecision::Block
  );
  assert_eq!(
    NoDeadline
      .deadline()
      .expect("the shipped deadline policy never refuses"),
    None
  );
}

/// **BLOCK IS THE ONE POLICY THAT CAN SAY IT NEVER SHEDS**, and the default answer is the
/// conservative one — which is what makes the launch walk's contradiction row catch a third-party
/// policy rather than only the two shipped ones.
#[test]
fn only_a_policy_that_cannot_drop_says_so_and_the_default_is_conservative() {
  assert!(!Backpressure.sheds());
  assert!(DropOldest.sheds());
  assert!(DropNewest.sheds());

  /// A third-party policy that says nothing about itself.
  struct Opaque;

  impl OverflowPolicy for Opaque {
    fn on_full(&self, _occupancy: Occupancy) -> Result<OverflowDecision, crate::BoxedError> {
      Ok(OverflowDecision::Block)
    }
  }

  assert!(
    Opaque.sheds(),
    "a policy that did not override `sheds` is assumed to be able to, so the contradiction is \
     caught rather than missed"
  );
}

#[test]
fn the_two_shed_policies_answer_their_own_names() {
  assert_eq!(
    DropOldest
      .on_full(Occupancy::bounded(4, 4))
      .expect("shipped"),
    OverflowDecision::DropOldest
  );
  assert_eq!(
    DropNewest
      .on_full(Occupancy::bounded(4, 4))
      .expect("shipped"),
    OverflowDecision::DropNewest
  );
  assert_eq!(OverflowDecision::DropOldest.as_str(), "drop_oldest");
  assert_eq!(OverflowDecision::Block.to_string(), "block");
  assert!(OverflowDecision::DropNewest.is_shed());
  assert!(!OverflowDecision::Block.is_shed());
}

#[test]
fn catch_up_is_the_counter_case_and_says_so_whatever_it_is_shown() {
  assert_eq!(
    CatchUp.on_missed(Missed::new(first(), 2)).expect("shipped"),
    TickDecision::CatchUp
  );
  assert!(
    TickDecision::CatchUp.is_catch_up() && !TickDecision::Coalesce.is_catch_up(),
    "the two arms are distinguishable without a match"
  );
}

/// **A MISSED COUNT CARRIES ITS SOURCE**, because a node may declare several poll entries and they
/// need not share a posture.
#[test]
fn a_missed_count_names_which_source_owes_the_ticks() {
  let missed = Missed::new(PollUpstream::new(2), 48);
  assert_eq!(missed.upstream(), PollUpstream::new(2));
  assert_eq!(missed.missed(), 48);

  /// A policy that caps its own catch-up, which is the whole reason the count is shown.
  struct Capped;

  impl TickPolicy for Capped {
    fn on_missed(&self, missed: Missed) -> Result<TickDecision, crate::BoxedError> {
      if missed.missed() > 10 {
        return Ok(TickDecision::Coalesce);
      }
      Ok(TickDecision::CatchUp)
    }
  }

  assert_eq!(
    Capped
      .on_missed(Missed::new(first(), 48))
      .expect("the cap decides"),
    TickDecision::Coalesce,
    "forty-eight owed ticks after a long sleep is what a cap exists to refuse"
  );
  assert_eq!(
    Capped.on_missed(Missed::new(first(), 3)).expect("decides"),
    TickDecision::CatchUp
  );
}

#[test]
fn occupancy_reads_full_only_where_something_bounds_it() {
  let bounded = Occupancy::bounded(32, 32);
  assert_eq!(bounded.queued(), 32);
  assert_eq!(bounded.capacity(), Some(32));
  assert!(bounded.is_full());
  assert!(!Occupancy::bounded(31, 32).is_full());

  let unbounded = Occupancy::unbounded(4_000_000);
  assert_eq!(unbounded.capacity(), None);
  assert!(
    !unbounded.is_full(),
    "nothing overflows a queue nothing bounds, which is the whole of the contradiction row"
  );
}

/// **THE AMBIENT BUDGET IS A VALUE**, and [`QueryDeadline`] is `take_within`'s knob said once for
/// every silent caller.
#[test]
fn the_query_deadline_hands_out_the_budget_it_was_built_with() {
  let deadline = QueryDeadline::of(SignedDuration::from_secs(5));
  assert_eq!(deadline.budget(), SignedDuration::from_secs(5));
  assert_eq!(
    deadline.deadline().expect("shipped"),
    Some(SignedDuration::from_secs(5))
  );
}

/// **THE COMPLETE ITEM KEY, and never the root alone** — the obituary names which of a root's many
/// items died, and hands the type back to a tap that knows it.
#[test]
fn a_shed_key_keeps_both_the_type_and_the_rendering() {
  /// A node's own key: a root and the item under it.
  #[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::Display)]
  #[display("segment({media}, {seg})")]
  struct SegmentKey {
    media: u64,
    seg: u32,
  }

  let key = ShedKey::new(SegmentKey { media: 7, seg: 41 });
  assert_eq!(
    key.key::<SegmentKey>(),
    Some(&SegmentKey { media: 7, seg: 41 }),
    "a tap that knows the type gets the whole key back"
  );
  assert_eq!(
    key.key::<u64>(),
    None,
    "and the ROOT alone is not what it carries — asking for one gets nothing"
  );
  assert_eq!(key.rendered(), "segment(7, 41)");
  assert_eq!(key.to_string(), "segment(7, 41)");
}

/// **THE ASSEMBLED SET STARTS AT THE SHIPPED FOUR**, and a `with_*_policy` replaces exactly one.
#[test]
fn assembling_replaces_one_concern_and_leaves_the_other_three() {
  let policies = Policies::new().with_tick_policy(Box::new(CatchUp));

  assert_eq!(
    policies
      .tick_policy()
      .on_missed(Missed::new(first(), 4))
      .expect("decides"),
    TickDecision::CatchUp,
    "the one that was replaced"
  );
  assert_eq!(
    policies
      .retry_policy()
      .on_failure(1, &NoOpinion)
      .expect("decides"),
    RetryDecision::GiveUp
  );
  assert_eq!(
    policies
      .overflow_policy()
      .on_full(Occupancy::bounded(1, 1))
      .expect("decides"),
    OverflowDecision::Block
  );
  assert_eq!(
    policies.deadline_policy().deadline().expect("decides"),
    None
  );
  assert!(
    !policies.overflow_policy().sheds(),
    "and the launch walk can still read the overflow half off the set"
  );
}

#[test]
fn the_default_set_is_the_shipped_one() {
  let default = Policies::default();
  assert!(!default.overflow_policy().sheds());
  assert_eq!(
    default
      .tick_policy()
      .on_missed(Missed::new(first(), 2))
      .expect("decides"),
    TickDecision::Coalesce
  );
  assert_eq!(
    format!("{default:?}"),
    "Policies { overflow_sheds: false, .. }"
  );
}

/// A backoff is a DECISION, so the number travels and the sleeping does not.
#[test]
fn a_retry_decision_carries_the_backoff_the_policy_computed() {
  /// Exponential-ish, and entirely the policy's own arithmetic.
  struct Backoff;

  impl RetryPolicy for Backoff {
    fn on_failure(
      &self,
      attempt: u32,
      _error: &(dyn core::error::Error + 'static),
    ) -> Result<RetryDecision, crate::BoxedError> {
      if attempt >= 3 {
        return Ok(RetryDecision::GiveUp);
      }
      Ok(RetryDecision::Retry {
        after: Some(SignedDuration::from_millis(i64::from(attempt) * 100)),
      })
    }
  }

  assert_eq!(
    Backoff.on_failure(1, &NoOpinion).expect("decides"),
    RetryDecision::Retry {
      after: Some(SignedDuration::from_millis(100))
    }
  );
  assert_eq!(
    Backoff.on_failure(3, &NoOpinion).expect("decides"),
    RetryDecision::GiveUp
  );
}

/// **THE ABSENT PAIR IS `NoDeadline`'s ANSWER**, and the two agree by construction rather than by
/// coincidence: neither side named a budget, so there is none.
#[test]
fn a_budget_nobody_named_is_the_shipped_no_deadline() {
  assert_eq!(tightened_budget(None, None), None);
  assert_eq!(NoDeadline.deadline().expect("shipped"), None);
}

/// **THE COMPOSE IS THE OPPOSITE OF `Deadlines::resolve`, AND THE DIFFERENCE IS THE TRUST BOUNDARY.**
///
/// The same two numbers: an in-process call site's explicit budget BEATS the ambient one even when it
/// is longer, because a caller inside the deployment is trusted with its own patience. A wire
/// requester's is capped. Asserted side by side so a later round cannot quietly align them.
#[test]
fn an_in_process_caller_may_wait_longer_where_a_wire_requester_may_not() {
  let (ambient, patient) = (
    SignedDuration::from_secs(30),
    SignedDuration::from_secs(300),
  );

  // The WIRE side: capped at the deployment's.
  assert_eq!(
    tightened_budget(Some(patient), Some(ambient)),
    Some(ambient)
  );

  // The CALL-SITE side: the policy answers the silent caller and nobody else, so a caller that
  // named a longer budget keeps it. `QueryDeadline` is that ambient value.
  assert_eq!(
    QueryDeadline::of(ambient).deadline().expect("shipped"),
    Some(ambient),
  );
}