ic-relay 0.2.0

A bounded durable channel for a fixed pair of Internet Computer canisters
Documentation
//! Durable FIFO delivery between fixed peers. Use one dedicated stable memory per peer.

use ic_platform_types::Principal;
use ic_storage::{Memory, RuntimeMemory, adapter::StableCell, stable_cell_payload_length};
use ic_wire::{
    Encoding, Limits,
    evolution::{decode_projected, encode_closed_core},
};
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;

/// Maximum application payload in one frame, in bytes.
pub const MAX_PAYLOAD: usize = 4096;

/// Upper bound on frames retained in either direction of a batched channel.
pub const MAX_QUEUE_ITEMS: usize = 16;

/// Per-peer queue depth and maximum number of frames selected per call.
#[derive(Clone, Copy, Debug)]
pub struct BatchConfig {
    /// Frames retained per direction. Each frame is bounded by MAX_PAYLOAD.
    pub queue_items: usize,
    /// Frames selected for one delivery attempt.
    pub batch_items: usize,
}

impl Default for BatchConfig {
    fn default() -> Self {
        Self {
            queue_items: MAX_QUEUE_ITEMS,
            batch_items: 8,
        }
    }
}

const FIFO_FORMAT: [u8; 4] = *b"RLY1";

// Account for two full queues, sequence counters and per-frame overhead.
const STATE_LIMITS: Limits = Limits {
    bytes: 2 * MAX_QUEUE_ITEMS * (MAX_PAYLOAD + 16) + 128,
    allocation: 8 * 1024 * 1024,
    nodes: 4096,
    depth: 8,
};

///
/// Frame
///
/// One sequenced application payload.
///

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Frame {
    /// Monotonic sequence starting at one.
    pub sequence: u64,
    /// Opaque application bytes.
    #[serde(with = "serde_bytes")]
    pub payload: Vec<u8>,
}

///
/// Error
///
/// A refused channel operation.
///

#[derive(Debug, PartialEq, Eq)]
pub enum Error {
    /// Principal differs from the configured peer.
    WrongPeer,
    /// The required slot is occupied.
    Full,
    /// Payload exceeds the channel limit.
    TooLarge,
    /// Sequence is outside the admitted range.
    UnexpectedSequence,
    /// The sender has used every sequence number.
    Exhausted,
    /// Stored bytes do not describe a supported channel.
    InvalidStorage,
    /// The queue or batch limit is outside its supported range.
    InvalidConfig,
}

///
/// State
///
/// Durable cursors and slots for one peer.
///

#[derive(Clone, Serialize, Deserialize)]
struct State {
    format: [u8; 4],
    peer: Principal,
    sent: u64,
    received: u64,
    outbound: VecDeque<Frame>,
    inbound: VecDeque<Frame>,
}

///
/// Channel
///
/// Owns the exclusive Storage lease for one peer channel.
///

pub struct Channel<M: Memory> {
    cell: StableCell<Vec<u8>, M>,
    state: State,
    config: BatchConfig,
}

impl<M: Memory> Channel<M> {
    /// Creates a fresh channel or opens the same peer's retained state.
    pub fn open(memory: RuntimeMemory<M>, peer: Principal) -> Result<Self, Error> {
        Self::open_batched(
            memory,
            peer,
            BatchConfig {
                queue_items: 1,
                batch_items: 1,
            },
        )
    }

    /// Open a FIFO channel for one fixed destination. A smaller configuration
    /// must still accommodate all retained work.
    pub fn open_batched(
        memory: RuntimeMemory<M>,
        peer: Principal,
        config: BatchConfig,
    ) -> Result<Self, Error> {
        if !(1..=MAX_QUEUE_ITEMS).contains(&config.queue_items)
            || !(1..=config.queue_items).contains(&config.batch_items)
        {
            return Err(Error::InvalidConfig);
        }
        let cell = if memory.size() == 0 {
            let initial = State {
                format: FIFO_FORMAT,
                peer,
                sent: 0,
                received: 0,
                outbound: VecDeque::new(),
                inbound: VecDeque::new(),
            };
            let bytes = encode_closed_core(&initial, Encoding::Payload, STATE_LIMITS)
                .map_err(|_| Error::InvalidStorage)?;
            StableCell::create(memory, bytes)
        } else {
            stable_cell_payload_length(&memory, STATE_LIMITS.bytes)
                .map_err(|_| Error::InvalidStorage)?;
            StableCell::load(memory).map_err(|_| Error::InvalidStorage)?
        };
        let bytes = cell.get().as_slice();
        if !bytes.starts_with(&FIFO_FORMAT) {
            return Err(Error::InvalidStorage);
        }
        let state: State =
            decode_projected(bytes, Encoding::Payload, STATE_LIMITS, |record, context| {
                record
                    .extensions
                    .visit(context, |_, _| Err(ic_wire::Error::Trailing))?;
                Ok(record.core)
            })
            .map_err(|_| Error::InvalidStorage)?;
        if state.peer != peer {
            return Err(Error::WrongPeer);
        }

        if state.outbound.len().max(state.inbound.len()) > config.queue_items {
            return Err(Error::InvalidConfig);
        }

        Ok(Self {
            cell,
            state,
            config,
        })
    }

    fn persist(&mut self) {
        self.cell.set(
            encode_closed_core(&self.state, Encoding::Payload, STATE_LIMITS)
                .expect("encode relay state"),
        );
    }

    /// Retain bytes for delivery and return the assigned sequence.
    pub fn enqueue(&mut self, payload: Vec<u8>) -> Result<u64, Error> {
        if payload.len() > MAX_PAYLOAD {
            return Err(Error::TooLarge);
        }
        if self.state.outbound.len() >= self.config.queue_items {
            return Err(Error::Full);
        }
        let sequence = self.state.sent.checked_add(1).ok_or(Error::Exhausted)?;
        self.state.outbound.push_back(Frame { sequence, payload });
        self.state.sent = sequence;
        self.persist();

        Ok(sequence)
    }

    /// Retry this exact frame until the peer acknowledges its sequence.
    #[must_use]
    pub fn outbound(&self) -> Option<&Frame> {
        self.state.outbound.front()
    }

    /// Supply the authenticated IC caller. Success returns the sequence to acknowledge.
    pub fn accept(&mut self, caller: Principal, frame: Frame) -> Result<u64, Error> {
        self.accept_batch(caller, vec![frame])
    }

    /// Snapshot the oldest pending frames for one peer call.
    #[must_use]
    pub fn outbound_batch(&self) -> Vec<Frame> {
        self.state
            .outbound
            .iter()
            .take(self.config.batch_items)
            .cloned()
            .collect()
    }

    /// Durably accept the longest FIFO prefix that fits and return its cumulative receipt.
    /// Replayed frames leave the inbox unchanged. A wholly blocked new batch returns Full.
    pub fn accept_batch(&mut self, caller: Principal, frames: Vec<Frame>) -> Result<u64, Error> {
        if caller != self.state.peer {
            return Err(Error::WrongPeer);
        }
        if frames.is_empty() || frames.len() > MAX_QUEUE_ITEMS {
            return Err(Error::InvalidConfig);
        }
        let mut previous = None;
        for frame in &frames {
            if frame.payload.len() > MAX_PAYLOAD {
                return Err(Error::TooLarge);
            }
            if frame.sequence == 0
                || previous.is_some_and(|n: u64| n.checked_add(1) != Some(frame.sequence))
            {
                return Err(Error::UnexpectedSequence);
            }
            previous = Some(frame.sequence);
        }
        if frames[0].sequence > self.state.received.saturating_add(1) {
            return Err(Error::UnexpectedSequence);
        }
        let last = previous.ok_or(Error::UnexpectedSequence)?;
        let before = self.state.received;
        let starts_with_replay = frames[0].sequence <= before;
        for frame in frames
            .into_iter()
            .filter(|frame| frame.sequence > before)
            .take(self.config.queue_items - self.state.inbound.len())
        {
            self.state.received = frame.sequence;
            self.state.inbound.push_back(frame);
        }
        if before != self.state.received {
            self.persist();
        } else if last > before && !starts_with_replay {
            return Err(Error::Full);
        }

        Ok(last.min(self.state.received))
    }

    /// Use the authenticated responding peer and the sequence in its reply.
    pub fn acknowledge(&mut self, peer: Principal, sequence: u64) -> Result<(), Error> {
        if peer != self.state.peer {
            return Err(Error::WrongPeer);
        }
        if sequence == 0 || sequence > self.state.sent {
            return Err(Error::UnexpectedSequence);
        }
        let count = self
            .state
            .outbound
            .partition_point(|frame| frame.sequence <= sequence);
        if count > 0 {
            self.state.outbound.drain(..count);
            self.persist();
        }

        Ok(())
    }

    /// Apply the payload synchronously within this IC message's rollback boundary.
    pub fn consume(&mut self) -> Option<Frame> {
        let frame = self.state.inbound.pop_front()?;
        self.persist();

        Some(frame)
    }
}