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 CHANNELS BLOCK: what a deployment says about a node's own edges, and how the three layers
//! that can say it are resolved into one.
//!
//! `[node.channels]` is the second entry of the rack [`NodeSection`] is — `options` is the node
//! author's type, this is the framework's own — and the two are read the same way: a block nobody
//! wrote states an absence, and an absence is what the layer under it fills.
//!
//! # The precedence is UNIFORM, kind included
//!
//! ```text
//! config  >  macro-declared  >  shipped
//! ```
//!
//! A deployment's word wins over the author's default, which wins over the framework's constant —
//! for the KIND exactly as for the depth, so a upstream an author shipped as `bounded(512)` can be
//! made unbounded by a document and an unbounded one can be bounded back. There is no frozen axis:
//! presence already lets a document decide which nodes exist, and retuning the edges between them is
//! the same hand.
//!
//! # A POSITION, not a name, is what reaches this layer
//!
//! The document's keys are the emitted shelf's FIELDS — one per declared upstream, named by the
//! upstream the declaration wrote — and the shelf hands this layer a table in DECLARATION ORDER.
//! That is the same convention a [`PollUpstream`](crate::PollUpstream) position already follows, and the
//! same one [`Wiring::source_of`](super::Wiring::source_of) reads off the graph, so a upstream's
//! channel and a upstream's tick are numbered by one rule and no map from string to edge exists to
//! fall out of step.
//!
//! # The contradiction row reads the resolution, and only the resolution
//!
//! An UNBOUNDED edge with a DROPPING [`OverflowPolicy`](crate::OverflowPolicy) is a contradiction —
//! nothing can overflow a queue nothing bounds — and its refusal is at launch validate, on the
//! RESOLVED kind rather than on what any one layer declared. What lands here is that resolution;
//! the row itself is [`Refusal::DroppingUnbounded`](super::Refusal::DroppingUnbounded), which reads
//! this table beside the deployment's own policy set.

use std::collections::BTreeMap;

use smol_bytes::Utf8Bytes;

use crate::{arrange::ChannelGraph, drive::ChannelOptions};

use super::{NodeSection, UpstreamWiring, Wiring};

#[cfg(test)]
mod tests;

/// WHAT A PER-NODE CHANNELS BLOCK CAN BE ASKED, whoever emitted it.
///
/// The emitted shelf is a struct with one field per declared upstream — typed, `deny_unknown_fields`,
/// and named by the declaration rather than by a string — so this layer cannot read its fields by
/// name and does not want to: what it needs is the table, in declaration order, which is the one
/// thing every shelf can say.
pub trait ChannelShelf {
  /// One entry per declared upstream, in DECLARATION ORDER — `None` where this deployment said nothing
  /// about that upstream, which leaves the layer under it in force.
  fn tuning(&self) -> impl Iterator<Item = Option<ChannelOptions>>;
}

/// The shelf of a node that declares NO upstreams — the rack's default, and the only shelf a document
/// can write nothing into.
///
/// It exists so that [`NodeSection`]'s second parameter has an answer for every node whose
/// declaration named no upstream, and so that a document writing `channels` for such a node is
/// refused by name at deserialization rather than accepted and ignored.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct Unchanneled {}

impl ChannelShelf for Unchanneled {
  #[inline]
  fn tuning(&self) -> impl Iterator<Item = Option<ChannelOptions>> {
    core::iter::empty()
  }
}

/// What a deployment TUNED, node by node — the config layer of the channel precedence.
///
/// [`Enablement`](super::Enablement)'s sibling and deliberately its shape: the names in it are the
/// arrangement's own node names, the bridge from the emitted spine is one call per mount, and a
/// deployment assembled in code reaches the same door with strings because nothing else can carry a
/// name a program computes.
///
/// # Examples
///
/// ```
/// use ingraph::{ChannelOptions, Channels};
///
/// // A deployment that widens one node's second upstream and says nothing about the rest.
/// let channels = Channels::new().tuned("captions", [None, Some(ChannelOptions::Unbounded)]);
///
/// assert_eq!(channels.spec("captions", 1), Some(ChannelOptions::Unbounded));
/// // Said nothing about, so whatever the declaration and the framework say stands.
/// assert_eq!(channels.spec("captions", 0), None);
/// assert_eq!(channels.spec("decode", 0), None);
/// ```
#[derive(Debug, Clone, Default)]
pub struct Channels {
  nodes: BTreeMap<Utf8Bytes, Vec<Option<ChannelOptions>>>,
}

impl Channels {
  /// A deployment that has tuned nothing — every edge at whatever its declaration and the framework
  /// say.
  #[inline]
  #[must_use]
  pub fn new() -> Self {
    Self {
      nodes: BTreeMap::new(),
    }
  }

  /// `node`'s upstreams, tuned in DECLARATION ORDER — `None` at a position this deployment said
  /// nothing about.
  ///
  /// The general door: a shelf hands its table through it, and so does a deployment assembled in
  /// code. A second call for one node REPLACES the first, a node's table being one statement rather
  /// than an accumulation.
  #[must_use]
  pub fn tuned(
    mut self,
    node: impl Into<Utf8Bytes>,
    upstreams: impl IntoIterator<Item = Option<ChannelOptions>>,
  ) -> Self {
    self
      .nodes
      .insert(node.into(), upstreams.into_iter().collect());
    self
  }

  /// WHAT THE SPINE HOLDS at the mount `node`, read for its channels block.
  ///
  /// [`Enablement::mounted`](super::Enablement::mounted)'s twin, and the same sentence about
  /// absence: a node this deployment did not name tunes nothing, and a section that wrote no
  /// `channels` block leaves every one of its edges to the layers under this one.
  #[must_use]
  pub fn mounted<O, C, P>(
    self,
    node: impl Into<Utf8Bytes>,
    section: Option<&NodeSection<O, C, P>>,
  ) -> Self
  where
    C: ChannelShelf,
  {
    match section.and_then(NodeSection::channels) {
      Some(shelf) => self.tuned(node, shelf.tuning()),
      None => self,
    }
  }

  /// What this deployment said about `node`'s upstream at `upstream`, or `None` where it said nothing.
  #[must_use]
  pub fn spec(&self, node: &str, upstream: usize) -> Option<ChannelOptions> {
    self
      .nodes
      .get(node)
      .and_then(|table| table.get(upstream).copied())
      .flatten()
  }

  /// Every node name this deployment's channels mention — what an unknown-name check reads.
  #[inline]
  pub fn names(&self) -> impl Iterator<Item = &str> {
    self.nodes.keys().map(Utf8Bytes::as_str)
  }
}

/// THE PRECEDENCE, in one place: config over macro-declared over shipped.
///
/// Uniform for the kind as well as the depth, which is what makes it one function rather than two
/// rules that could disagree: a layer either speaks about this edge or it does not, and the first
/// one that does is the answer.
#[inline]
#[must_use]
pub(super) const fn resolved(
  config: Option<ChannelOptions>,
  declared: Option<ChannelOptions>,
  shipped: ChannelOptions,
) -> ChannelOptions {
  match (config, declared) {
    (Some(spec), _) | (None, Some(spec)) => spec,
    (None, None) => shipped,
  }
}

/// EVERY EDGE'S ANSWER, resolved once at the validate walk: one row per node, one entry per inbound
/// channel upstream, in the graph's own edge order.
///
/// The order is the convention, not a choice made here: a node's inbound channel edges are numbered
/// as [`Wiring::source_of`](super::Wiring::source_of) numbers them, which is the declaration order
/// the emitted shelf's fields are written in and the same rule a `PollUpstream` position follows. So a
/// document's `ocr = "unbounded"` and the edge it tunes meet at a POSITION, with no map from string
/// to edge in between to fall out of step.
///
/// Non-channel upstreams are skipped for the reason they are skipped everywhere else: a changes
/// listener reads its producer's store, a poll edge carries no messages, and a transient edge is a
/// door — none of the three is opened as a data channel, so none has a channel to resolve.
pub(super) fn resolve_channels(
  graph: &ChannelGraph,
  upstreams: &[UpstreamWiring],
  config: &Channels,
) -> Vec<Vec<ChannelOptions>> {
  let mut tables: Vec<Vec<ChannelOptions>> = vec![Vec::new(); graph.nodes().len()];
  for (index, edge) in graph.edges().iter().enumerate() {
    let Some(upstream) = upstreams.get(index) else {
      continue;
    };
    if !upstream.listen().is_channel() {
      continue;
    }
    let consumer = edge.to().index();
    let Some(name) = graph.nodes().get(consumer).map(crate::Node::name) else {
      continue;
    };
    let Some(table) = tables.get_mut(consumer) else {
      continue;
    };
    let position = table.len();
    table.push(resolved(
      config.spec(name, position),
      upstream.channel(),
      Wiring::SHIPPED,
    ));
  }
  tables
}