Skip to main content

qualia_core_db/net/peer/replication/
resume.rs

1//! Resume only verified blocks of a pinned content manifest (SVC-01.14).
2//!
3//! A pin holds one [`ContentManifest`]. Verified bits are a `u8` bitmap aligned
4//! to [`MAX_RANGES`] (8). An unverified block is not transferred
5//! ([`QdnfError::Incomplete`]). A different digest cannot resume into an
6//! existing pin ([`QdnfError::Conflict`]). Container generation is not a QSync
7//! root. Packages remain open.
8
9use super::manifest::{
10    container_generation_is_qsync_root as manifest_is_qsync_root, ContentManifest, MAX_RANGES,
11};
12use crate::net::qdnf::errors::QdnfError;
13use crate::net::qdnf::types::StrongDigest;
14
15/// Maximum concurrently pinned manifests.
16pub const MAX_PINNED: usize = 4;
17
18const _: () = assert!(MAX_RANGES == 8);
19const _: () = assert!(MAX_RANGES <= u8::BITS as usize);
20
21#[derive(Clone, Copy)]
22struct PinSlot {
23    manifest: Option<ContentManifest>,
24    /// Bit `i` set ⇒ range index `i` is verified. Width matches [`MAX_RANGES`].
25    verified: u8,
26}
27
28/// Four pinned manifests, each with an 8-bit verified bitmap.
29pub struct ResumeTable {
30    slots: [PinSlot; MAX_PINNED],
31}
32
33impl ResumeTable {
34    /// Creates a default `ResumeTable`.
35    pub const fn new() -> Self {
36        Self {
37            slots: [PinSlot {
38                manifest: None,
39                verified: 0,
40            }; MAX_PINNED],
41        }
42    }
43}
44
45impl Default for ResumeTable {
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51/// Pin `manifest`. Same digest is idempotent (same pin id). Fifth distinct digest
52/// is [`QdnfError::Capacity`].
53pub fn pin(table: &mut ResumeTable, manifest: ContentManifest) -> Result<u8, QdnfError> {
54    let mut i = 0usize;
55    while i < MAX_PINNED {
56        if let Some(held) = table.slots[i].manifest {
57            if held.digest == manifest.digest {
58                return Ok(i as u8);
59            }
60        }
61        i += 1;
62    }
63    i = 0;
64    while i < MAX_PINNED {
65        if table.slots[i].manifest.is_none() {
66            table.slots[i].manifest = Some(manifest);
67            table.slots[i].verified = 0;
68            return Ok(i as u8);
69        }
70        i += 1;
71    }
72    Err(QdnfError::Capacity)
73}
74
75/// Mark range `block_index` verified on `pin`. Only indices in `0..range_count`
76/// of the pinned manifest may be marked.
77pub fn mark_verified(table: &mut ResumeTable, pin: u8, block_index: u8) -> Result<(), QdnfError> {
78    let range_count = pin_range_count(table, pin)?;
79    if (block_index as usize) >= range_count {
80        return Err(QdnfError::Range);
81    }
82    table.slots[pin as usize].verified |= 1u8 << block_index;
83    Ok(())
84}
85
86/// Resume range `block_index` of `pin`. Ok only when that range is verified.
87/// Unverified is [`QdnfError::Incomplete`], not transferred.
88pub fn resume_block(table: &ResumeTable, pin: u8, block_index: u8) -> Result<(), QdnfError> {
89    let (range_count, verified) = pin_verified(table, pin)?;
90    if (block_index as usize) >= range_count {
91        return Err(QdnfError::Range);
92    }
93    if (verified & (1u8 << block_index)) == 0 {
94        return Err(QdnfError::Incomplete);
95    }
96    Ok(())
97}
98
99/// A different digest cannot resume into this pin.
100pub fn resume_digest(table: &ResumeTable, pin: u8, digest: StrongDigest) -> Result<(), QdnfError> {
101    let held = pin_manifest(table, pin)?;
102    if held.digest != digest {
103        return Err(QdnfError::Conflict);
104    }
105    Ok(())
106}
107
108/// Unverified blocks are never treated as transferred.
109#[inline]
110pub fn resume_unverified_is_allowed() -> bool {
111    false
112}
113
114/// Container generation is not an authorized QSync root (SVC-01.14).
115#[inline]
116pub fn container_generation_is_qsync_root() -> bool {
117    manifest_is_qsync_root()
118}
119
120fn pin_slot(table: &ResumeTable, pin: u8) -> Result<&PinSlot, QdnfError> {
121    let i = pin as usize;
122    if i >= MAX_PINNED {
123        return Err(QdnfError::Unauthorized);
124    }
125    let slot = &table.slots[i];
126    if slot.manifest.is_none() {
127        return Err(QdnfError::Unauthorized);
128    }
129    Ok(slot)
130}
131
132fn pin_manifest(table: &ResumeTable, pin: u8) -> Result<ContentManifest, QdnfError> {
133    pin_slot(table, pin)?
134        .manifest
135        .ok_or(QdnfError::Unauthorized)
136}
137
138fn pin_range_count(table: &ResumeTable, pin: u8) -> Result<usize, QdnfError> {
139    Ok(pin_manifest(table, pin)?.range_count())
140}
141
142fn pin_verified(table: &ResumeTable, pin: u8) -> Result<(usize, u8), QdnfError> {
143    let slot = pin_slot(table, pin)?;
144    let range_count = slot.manifest.ok_or(QdnfError::Unauthorized)?.range_count();
145    Ok((range_count, slot.verified))
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151    use crate::net::peer::replication::manifest::ByteRange;
152
153    fn digest(tag: u8) -> StrongDigest {
154        let mut d = StrongDigest::ZERO;
155        d.0[0] = tag;
156        d
157    }
158
159    fn bind(tag: u8, n_ranges: usize) -> ContentManifest {
160        let mut ranges = [ByteRange { offset: 0, len: 1 }; MAX_RANGES];
161        let mut i = 0usize;
162        while i < n_ranges {
163            ranges[i] = ByteRange {
164                offset: (i as u64) * 8,
165                len: 4,
166            };
167            i += 1;
168        }
169        ContentManifest::bind(digest(tag), 0, 64, &ranges[..n_ranges]).unwrap()
170    }
171
172    #[test]
173    fn pin_mark_verified_resume_ok() {
174        let mut table = ResumeTable::new();
175        let pin_id = pin(&mut table, bind(1, 2)).unwrap();
176        mark_verified(&mut table, pin_id, 0).unwrap();
177        resume_block(&table, pin_id, 0).unwrap();
178    }
179
180    #[test]
181    fn resume_before_mark_verified_is_incomplete() {
182        let mut table = ResumeTable::new();
183        let pin_id = pin(&mut table, bind(1, 2)).unwrap();
184        assert_eq!(resume_block(&table, pin_id, 0), Err(QdnfError::Incomplete));
185    }
186
187    #[test]
188    fn block_index_past_range_count_is_range() {
189        let mut table = ResumeTable::new();
190        let pin_id = pin(&mut table, bind(1, 2)).unwrap();
191        assert_eq!(mark_verified(&mut table, pin_id, 2), Err(QdnfError::Range));
192        assert_eq!(resume_block(&table, pin_id, 2), Err(QdnfError::Range));
193    }
194
195    #[test]
196    fn fifth_pin_is_capacity() {
197        let mut table = ResumeTable::new();
198        pin(&mut table, bind(1, 1)).unwrap();
199        pin(&mut table, bind(2, 1)).unwrap();
200        pin(&mut table, bind(3, 1)).unwrap();
201        pin(&mut table, bind(4, 1)).unwrap();
202        assert_eq!(pin(&mut table, bind(5, 1)), Err(QdnfError::Capacity));
203    }
204
205    #[test]
206    fn pin_same_digest_is_idempotent() {
207        let mut table = ResumeTable::new();
208        let a = pin(&mut table, bind(7, 2)).unwrap();
209        let b = pin(&mut table, bind(7, 2)).unwrap();
210        assert_eq!(a, b);
211        pin(&mut table, bind(8, 1)).unwrap();
212        let c = pin(&mut table, bind(7, 1)).unwrap();
213        assert_eq!(a, c);
214    }
215
216    #[test]
217    fn mark_verified_unknown_pin_is_unauthorized() {
218        let mut table = ResumeTable::new();
219        assert_eq!(
220            mark_verified(&mut table, 0, 0),
221            Err(QdnfError::Unauthorized)
222        );
223        assert_eq!(
224            mark_verified(&mut table, MAX_PINNED as u8, 0),
225            Err(QdnfError::Unauthorized)
226        );
227    }
228
229    #[test]
230    fn resume_unverified_is_not_allowed() {
231        assert!(!resume_unverified_is_allowed());
232    }
233
234    #[test]
235    fn container_generation_is_not_qsync_root() {
236        assert!(!container_generation_is_qsync_root());
237        assert!(!manifest_is_qsync_root());
238    }
239
240    #[test]
241    fn different_digest_cannot_resume_into_pin() {
242        let mut table = ResumeTable::new();
243        let pin_id = pin(&mut table, bind(1, 1)).unwrap();
244        resume_digest(&table, pin_id, digest(1)).unwrap();
245        assert_eq!(
246            resume_digest(&table, pin_id, digest(2)),
247            Err(QdnfError::Conflict)
248        );
249    }
250}