Skip to main content

qualia_core_db/net/qdnf/session/
iri.rs

1//! Service-channel IRI binding and delivery-stage receipts (NET-05.06 partial).
2//!
3//! IRI bytes are already hashed by the caller into [`StrongDigest`]. Two
4//! different services claiming the same digest is [`QdnfError::Conflict`];
5//! the same digest on the same service is idempotent. Transport ACK and
6//! consumption are not durable application or economic receipts. Datagram
7//! expiry is independent of this table. Packages remain open.
8
9use crate::net::qdnf::errors::QdnfError;
10use crate::net::qdnf::session::datagrams::DeliveryStage;
11use crate::net::qdnf::types::{OperationId, StrongDigest};
12
13/// Occupied service-channel slots. A 17th distinct bind is Capacity.
14pub const MAX_CHANNELS: usize = 16;
15
16/// Bind a caller-hashed service IRI to a service channel and operation.
17#[repr(C)]
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub struct ChannelBind {
20    pub iri: StrongDigest,
21    pub service: StrongDigest,
22    pub operation: OperationId,
23}
24
25/// Sixteen-slot service-channel table. Empty slots are `None`.
26pub struct ChannelTable {
27    slots: [Option<ChannelBind>; MAX_CHANNELS],
28}
29
30impl ChannelTable {
31    /// Creates a default `ChannelTable`.
32    pub const fn new() -> Self {
33        Self {
34            slots: [None; MAX_CHANNELS],
35        }
36    }
37
38    /// Bind `bind` into a free slot.
39    ///
40    /// Zero IRI or zero service → [`QdnfError::Malformed`]. Same IRI and
41    /// service → `Ok` (idempotent). Same IRI, different service →
42    /// [`QdnfError::Conflict`]. No free slot for a distinct bind →
43    /// [`QdnfError::Capacity`].
44    pub fn bind(&mut self, bind: ChannelBind) -> Result<(), QdnfError> {
45        if bind.iri == StrongDigest::ZERO || bind.service == StrongDigest::ZERO {
46            return Err(QdnfError::Malformed);
47        }
48        let mut free = None;
49        let mut i = 0usize;
50        while i < MAX_CHANNELS {
51            match self.slots[i] {
52                Some(existing) if existing.iri == bind.iri => {
53                    if existing.service == bind.service {
54                        return Ok(());
55                    }
56                    return Err(QdnfError::Conflict);
57                }
58                Some(_) => {}
59                None => {
60                    if free.is_none() {
61                        free = Some(i);
62                    }
63                }
64            }
65            i += 1;
66        }
67        let idx = free.ok_or(QdnfError::Capacity)?;
68        self.slots[idx] = Some(bind);
69        Ok(())
70    }
71}
72
73impl Default for ChannelTable {
74    fn default() -> Self {
75        Self::new()
76    }
77}
78
79/// Durable application and economic receipts only. Transport ACK and
80/// consumption do not imply durable applied state.
81pub fn stage_implies_durable(stage: DeliveryStage) -> bool {
82    matches!(
83        stage,
84        DeliveryStage::DurableApplied | DeliveryStage::EconomicReceipt
85    )
86}
87
88/// Transport ACK is never an economic receipt.
89pub fn transport_ack_is_economic_receipt() -> bool {
90    false
91}
92
93/// Consumption is never durable application.
94pub fn consumed_is_durable_applied() -> bool {
95    false
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::net::qdnf::session::datagrams::Datagram;
102
103    fn digest(tag: u8) -> StrongDigest {
104        let mut d = StrongDigest::ZERO;
105        d.0[0] = tag;
106        d
107    }
108
109    fn operation(tag: u8) -> OperationId {
110        let mut id = OperationId::ZERO;
111        id.0[0] = tag;
112        id
113    }
114
115    fn bind_pair(iri: u8, service: u8) -> ChannelBind {
116        ChannelBind {
117            iri: digest(iri),
118            service: digest(service),
119            operation: operation(1),
120        }
121    }
122
123    #[test]
124    fn transport_ack_is_not_economic_and_consumed_is_not_durable() {
125        assert!(!transport_ack_is_economic_receipt());
126        assert!(!consumed_is_durable_applied());
127    }
128
129    #[test]
130    fn stage_implies_durable_separates_ack_from_applied() {
131        assert!(!stage_implies_durable(DeliveryStage::TransportAck));
132        assert!(stage_implies_durable(DeliveryStage::DurableApplied));
133        assert!(!stage_implies_durable(DeliveryStage::Consumed));
134        assert!(stage_implies_durable(DeliveryStage::EconomicReceipt));
135    }
136
137    #[test]
138    fn same_iri_different_service_is_conflict() {
139        let mut table = ChannelTable::new();
140        assert!(table.bind(bind_pair(1, 2)).is_ok());
141        assert_eq!(table.bind(bind_pair(1, 3)), Err(QdnfError::Conflict));
142    }
143
144    #[test]
145    fn identical_bind_is_idempotent() {
146        let mut table = ChannelTable::new();
147        let b = bind_pair(4, 5);
148        assert!(table.bind(b).is_ok());
149        assert!(table.bind(b).is_ok());
150    }
151
152    #[test]
153    fn sixteen_distinct_ok_seventeenth_capacity() {
154        let mut table = ChannelTable::new();
155        let mut n = 0u8;
156        while n < MAX_CHANNELS as u8 {
157            let tag = n + 1;
158            assert!(table.bind(bind_pair(tag, tag)).is_ok());
159            n += 1;
160        }
161        assert_eq!(table.bind(bind_pair(0x20, 0x21)), Err(QdnfError::Capacity));
162    }
163
164    #[test]
165    fn expired_datagram_is_independent_of_channel_table() {
166        let mut table = ChannelTable::new();
167        let b = bind_pair(7, 8);
168        assert!(table.bind(b).is_ok());
169        let dg = Datagram {
170            operation: operation(1),
171            expires_unix: 10,
172            len: 4,
173        };
174        assert_eq!(dg.live_at(10), Err(QdnfError::Expired));
175        assert!(dg.live_at(9).is_ok());
176        assert!(table.bind(b).is_ok());
177        assert!(table.bind(bind_pair(9, 10)).is_ok());
178    }
179
180    #[test]
181    fn zero_iri_is_malformed() {
182        let mut table = ChannelTable::new();
183        assert_eq!(
184            table.bind(ChannelBind {
185                iri: StrongDigest::ZERO,
186                service: digest(1),
187                operation: operation(1),
188            }),
189            Err(QdnfError::Malformed)
190        );
191        assert_eq!(
192            table.bind(ChannelBind {
193                iri: digest(1),
194                service: StrongDigest::ZERO,
195                operation: operation(1),
196            }),
197            Err(QdnfError::Malformed)
198        );
199    }
200}