ic-relay 0.1.1

A bounded durable channel for a fixed pair of Internet Computer canisters
Documentation
//! A durable stop-and-wait relay. 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};

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

// Both slots plus sequence counters, peer identity and Wire framing overhead.
const STATE_LIMITS: Limits = Limits {
    bytes: 2 * MAX_PAYLOAD + 128,
    allocation: 512 * 1024,
    nodes: 512,
    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,
}

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

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

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

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

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> {
        let cell = if memory.size() == 0 {
            let initial = State {
                version: 2,
                peer,
                sent: 0,
                received: 0,
                outbound: None,
                inbound: None,
            };
            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)?
        };
        // V1 used the same positional core without Wire's final empty extension block.
        // Adapt it in memory. The next successful mutation writes V2.
        let mut upgraded;
        let bytes = match cell.get().first() {
            Some(1) => {
                upgraded = cell.get().clone();
                upgraded[0] = 2;
                upgraded.push(0);
                upgraded.as_slice()
            }
            Some(2) => cell.get().as_slice(),
            _ => 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);
        }

        Ok(Self { cell, state })
    }

    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.is_some() {
            return Err(Error::Full);
        }
        let sequence = self.state.sent.checked_add(1).ok_or(Error::Exhausted)?;
        self.state.outbound = Some(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.as_ref()
    }

    /// Supply the authenticated IC caller. Success returns the sequence to acknowledge.
    pub fn accept(&mut self, caller: Principal, frame: Frame) -> Result<u64, Error> {
        if caller != self.state.peer {
            return Err(Error::WrongPeer);
        }
        if frame.sequence == 0 {
            return Err(Error::UnexpectedSequence);
        }
        if frame.payload.len() > MAX_PAYLOAD {
            return Err(Error::TooLarge);
        }
        if frame.sequence <= self.state.received {
            return Ok(frame.sequence);
        }
        if self.state.received.checked_add(1) != Some(frame.sequence) {
            return Err(Error::UnexpectedSequence);
        }
        if self.state.inbound.is_some() {
            return Err(Error::Full);
        }
        self.state.received = frame.sequence;
        self.state.inbound = Some(frame);
        self.persist();

        Ok(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);
        }
        if self
            .outbound()
            .is_some_and(|frame| frame.sequence == sequence)
        {
            self.state.outbound = None;
            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.take()?;
        self.persist();

        Some(frame)
    }
}