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};
pub const MAX_PAYLOAD: usize = 4096;
const STATE_LIMITS: Limits = Limits {
bytes: 2 * MAX_PAYLOAD + 128,
allocation: 512 * 1024,
nodes: 512,
depth: 8,
};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Frame {
pub sequence: u64,
#[serde(with = "serde_bytes")]
pub payload: Vec<u8>,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Error {
WrongPeer,
Full,
TooLarge,
UnexpectedSequence,
Exhausted,
InvalidStorage,
}
#[derive(Clone, Serialize, Deserialize)]
struct State {
version: u8,
peer: Principal,
sent: u64,
received: u64,
outbound: Option<Frame>,
inbound: Option<Frame>,
}
pub struct Channel<M: Memory> {
cell: StableCell<Vec<u8>, M>,
state: State,
}
impl<M: Memory> Channel<M> {
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)?
};
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"),
);
}
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)
}
#[must_use]
pub fn outbound(&self) -> Option<&Frame> {
self.state.outbound.as_ref()
}
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)
}
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(())
}
pub fn consume(&mut self) -> Option<Frame> {
let frame = self.state.inbound.take()?;
self.persist();
Some(frame)
}
}