use core::marker::PhantomData;
use heapless::Vec;
use crate::config::{AssertValid, Config};
use crate::im::{AttributeId, ClusterId, EndpointId, InteractionContext, Status};
use crate::msg::{FabricIndex, NodeId, NodeIdKind};
use crate::platform::{Duration, Instant};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RequestType {
BeginWrite = 0,
CommitWrite = 1,
RollbackWrite = 2,
}
impl RequestType {
#[must_use]
pub const fn from_value(value: u8) -> Option<Self> {
match value {
0 => Some(Self::BeginWrite),
1 => Some(Self::CommitWrite),
2 => Some(Self::RollbackWrite),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Writer {
pub node: NodeId,
pub fabric: FabricIndex,
}
impl Writer {
#[must_use]
pub fn from_context(ctx: &InteractionContext<'_>) -> Option<Self> {
let node = ctx.peer_node_id?;
if !matches!(node.kind(), NodeIdKind::Operational) {
return None;
}
let fabric = ctx.fabric_index?;
if fabric.0 == 0 {
return None;
}
Some(Self { node, fabric })
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Claim<const A: usize> {
pub endpoint: EndpointId,
pub cluster: ClusterId,
pub writer: Writer,
pub attributes: Vec<AttributeId, A>,
pub deadline: Instant,
}
impl<const A: usize> Claim<A> {
#[must_use]
pub fn as_ref(&self) -> ClaimRef<'_> {
ClaimRef {
endpoint: self.endpoint,
cluster: self.cluster,
attributes: &self.attributes,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClaimRef<'a> {
pub endpoint: EndpointId,
pub cluster: ClusterId,
pub attributes: &'a [AttributeId],
}
impl ClaimRef<'_> {
#[must_use]
pub fn covers(&self, endpoint: EndpointId, cluster: ClusterId, attribute: AttributeId) -> bool {
self.endpoint == endpoint && self.cluster == cluster && self.attributes.contains(&attribute)
}
}
#[derive(Debug)]
pub struct AtomicWrites<C: Config, const N: usize, const A: usize> {
claims: Vec<Claim<A>, N>,
_config: PhantomData<C>,
}
impl<C: Config, const N: usize, const A: usize> Default for AtomicWrites<C, N, A> {
fn default() -> Self {
Self::new()
}
}
impl<C: Config, const N: usize, const A: usize> AtomicWrites<C, N, A> {
#[must_use]
pub fn new() -> Self {
let () = AssertValid::<C>::CHECK;
Self {
claims: Vec::new(),
_config: PhantomData,
}
}
#[must_use]
pub fn len(&self) -> usize {
self.claims.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.claims.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = &Claim<A>> {
self.claims.iter()
}
pub fn begin(
&mut self,
endpoint: EndpointId,
cluster: ClusterId,
writer: Writer,
attributes: &[AttributeId],
timeout: Duration,
now: Instant,
) -> Result<(), Status> {
if attributes.is_empty() {
return Err(Status::InvalidCommand);
}
for (index, id) in attributes.iter().enumerate() {
if attributes
.get(index.saturating_add(1)..)
.is_some_and(|rest| rest.contains(id))
{
return Err(Status::InvalidCommand);
}
}
if self.find(endpoint, cluster, writer).is_some() {
return Err(Status::InvalidInState);
}
for id in attributes {
if self.holder(endpoint, cluster, *id).is_some() {
return Err(Status::Busy);
}
}
let mut held = Vec::new();
for id in attributes {
held.push(*id).map_err(|_| Status::ResourceExhausted)?;
}
self.claims
.push(Claim {
endpoint,
cluster,
writer,
attributes: held,
deadline: now.saturating_add(timeout),
})
.map_err(|_| Status::ResourceExhausted)
}
pub fn finish(
&mut self,
endpoint: EndpointId,
cluster: ClusterId,
writer: Writer,
attributes: &[AttributeId],
) -> Result<(), Status> {
let Some(index) = self
.claims
.iter()
.position(|c| c.endpoint == endpoint && c.cluster == cluster && c.writer == writer)
else {
return Err(Status::InvalidInState);
};
let matches = self
.claims
.get(index)
.is_some_and(|claim| same_set(&claim.attributes, attributes));
if !matches {
return Err(Status::InvalidInState);
}
self.claims.swap_remove(index);
Ok(())
}
#[must_use]
pub fn find(
&self,
endpoint: EndpointId,
cluster: ClusterId,
writer: Writer,
) -> Option<&Claim<A>> {
self.claims
.iter()
.find(|c| c.endpoint == endpoint && c.cluster == cluster && c.writer == writer)
}
#[must_use]
pub fn holder(
&self,
endpoint: EndpointId,
cluster: ClusterId,
attribute: AttributeId,
) -> Option<Writer> {
self.claims
.iter()
.find(|c| {
c.endpoint == endpoint && c.cluster == cluster && c.attributes.contains(&attribute)
})
.map(|c| c.writer)
}
pub fn check_write(
&self,
endpoint: EndpointId,
cluster: ClusterId,
writer: Option<Writer>,
attribute: AttributeId,
) -> Result<(), Status> {
let Some(writer) = writer else {
return Err(Status::InvalidInState);
};
match self.find(endpoint, cluster, writer) {
Some(claim) if claim.attributes.contains(&attribute) => Ok(()),
_ => Err(Status::InvalidInState),
}
}
pub fn reap(&mut self, now: Instant) -> usize {
let before = self.claims.len();
self.claims.retain(|claim| claim.deadline > now);
before.saturating_sub(self.claims.len())
}
pub fn remove_fabric(&mut self, fabric: FabricIndex) -> usize {
let before = self.claims.len();
self.claims.retain(|claim| claim.writer.fabric != fabric);
before.saturating_sub(self.claims.len())
}
#[must_use]
pub fn next_deadline(&self) -> Option<Instant> {
self.claims.iter().map(|c| c.deadline).min()
}
}
fn same_set(held: &[AttributeId], asked: &[AttributeId]) -> bool {
held.len() == asked.len() && held.iter().all(|id| asked.contains(id))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::DefaultConfig;
type Table = AtomicWrites<DefaultConfig, 4, 4>;
const EP: EndpointId = 1;
const THERMOSTAT: ClusterId = 0x0201;
const HEAT: AttributeId = 0x0012;
const COOL: AttributeId = 0x0011;
fn alice() -> Writer {
Writer {
node: NodeId(0x0000_0000_0000_1111),
fabric: FabricIndex(1),
}
}
fn bob() -> Writer {
Writer {
node: NodeId(0x0000_0000_0000_2222),
fabric: FabricIndex(1),
}
}
fn at(ms: u64) -> Instant {
Instant::from_micros(ms.saturating_mul(1000))
}
fn timeout() -> Duration {
Duration::from_millis(1_000)
}
#[test]
fn a_claim_covers_its_attributes_and_only_its_own_client() {
let mut table = Table::new();
table
.begin(EP, THERMOSTAT, alice(), &[HEAT, COOL], timeout(), at(0))
.expect("begin");
assert!(
table
.check_write(EP, THERMOSTAT, Some(alice()), HEAT)
.is_ok()
);
assert_eq!(
table.check_write(EP, THERMOSTAT, Some(bob()), HEAT),
Err(Status::InvalidInState)
);
assert_eq!(
table.check_write(EP, THERMOSTAT, Some(alice()), 0x0099),
Err(Status::InvalidInState)
);
}
#[test]
fn writing_an_atomic_attribute_with_no_claim_is_invalid_in_state() {
let table = Table::new();
assert_eq!(
table.check_write(EP, THERMOSTAT, Some(alice()), HEAT),
Err(Status::InvalidInState)
);
assert_eq!(
table.check_write(EP, THERMOSTAT, None, HEAT),
Err(Status::InvalidInState)
);
}
#[test]
fn a_second_claim_on_the_same_cluster_by_the_same_client_is_refused() {
let mut table = Table::new();
table
.begin(EP, THERMOSTAT, alice(), &[HEAT], timeout(), at(0))
.expect("begin");
assert_eq!(
table.begin(EP, THERMOSTAT, alice(), &[COOL], timeout(), at(0)),
Err(Status::InvalidInState)
);
}
#[test]
fn an_attribute_another_client_has_claimed_is_busy() {
let mut table = Table::new();
table
.begin(EP, THERMOSTAT, alice(), &[HEAT], timeout(), at(0))
.expect("begin");
assert_eq!(
table.begin(EP, THERMOSTAT, bob(), &[HEAT], timeout(), at(0)),
Err(Status::Busy)
);
table
.begin(EP, THERMOSTAT, bob(), &[COOL], timeout(), at(0))
.expect("a different attribute is free");
}
#[test]
fn an_empty_or_duplicated_attribute_set_is_invalid() {
let mut table = Table::new();
assert_eq!(
table.begin(EP, THERMOSTAT, alice(), &[], timeout(), at(0)),
Err(Status::InvalidCommand)
);
assert_eq!(
table.begin(EP, THERMOSTAT, alice(), &[HEAT, HEAT], timeout(), at(0)),
Err(Status::InvalidCommand)
);
}
#[test]
fn committing_requires_the_same_set_in_any_order() {
let mut table = Table::new();
table
.begin(EP, THERMOSTAT, alice(), &[HEAT, COOL], timeout(), at(0))
.expect("begin");
assert_eq!(
table.finish(EP, THERMOSTAT, alice(), &[HEAT]),
Err(Status::InvalidInState),
"a subset is not the set"
);
assert_eq!(
table.finish(EP, THERMOSTAT, bob(), &[COOL, HEAT]),
Err(Status::InvalidInState),
"and not another client's"
);
table
.finish(EP, THERMOSTAT, alice(), &[COOL, HEAT])
.expect("the same set, reordered");
assert!(table.is_empty(), "the claim is released either way");
}
#[test]
fn a_claim_that_is_never_committed_lapses() {
let mut table = Table::new();
table
.begin(EP, THERMOSTAT, alice(), &[HEAT], timeout(), at(0))
.expect("begin");
assert_eq!(table.next_deadline(), Some(at(1_000)));
assert_eq!(table.reap(at(999)), 0, "not yet");
assert_eq!(table.reap(at(1_001)), 1, "lapsed");
assert!(table.is_empty());
table
.begin(EP, THERMOSTAT, bob(), &[HEAT], timeout(), at(1_001))
.expect("no longer held");
}
#[test]
fn only_an_operational_node_on_a_fabric_can_hold_a_claim() {
let mut ctx = InteractionContext::new();
assert_eq!(Writer::from_context(&ctx), None, "no peer at all");
ctx.peer_node_id = Some(NodeId(0x0000_0000_0000_1111));
assert_eq!(Writer::from_context(&ctx), None, "no accessing fabric");
ctx.fabric_index = Some(FabricIndex(1));
assert_eq!(
Writer::from_context(&ctx),
Some(alice()),
"a CASE session on a fabric"
);
ctx.peer_node_id = Some(NodeId(0xFFFF_FFFF_FFFF_0001));
assert_eq!(Writer::from_context(&ctx), None);
}
#[test]
fn removing_a_fabric_releases_its_claims() {
let mut table = Table::new();
table
.begin(EP, THERMOSTAT, alice(), &[HEAT], timeout(), at(0))
.expect("begin");
let other_fabric = Writer {
node: NodeId(0x0000_0000_0000_3333),
fabric: FabricIndex(2),
};
table
.begin(EP, THERMOSTAT, other_fabric, &[COOL], timeout(), at(0))
.expect("begin");
assert_eq!(table.remove_fabric(FabricIndex(1)), 1);
assert_eq!(table.len(), 1);
assert!(table.find(EP, THERMOSTAT, other_fabric).is_some());
}
#[test]
fn the_same_node_id_on_two_fabrics_is_two_clients() {
let mut table = Table::new();
let on_one = alice();
let on_two = Writer {
node: on_one.node,
fabric: FabricIndex(2),
};
table
.begin(EP, THERMOSTAT, on_one, &[HEAT], timeout(), at(0))
.expect("begin");
assert_eq!(
table.check_write(EP, THERMOSTAT, Some(on_two), HEAT),
Err(Status::InvalidInState)
);
}
}