Skip to main content

ic_memory/slot/
range_authority.rs

1use super::descriptor::AllocationSlotDescriptor;
2use super::memory_manager::{
3    MEMORY_MANAGER_INVALID_ID, MEMORY_MANAGER_MAX_ID, MEMORY_MANAGER_MIN_ID,
4    MemoryManagerSlotError, validate_memory_manager_id,
5};
6use crate::text::validate_diagnostic_text;
7use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
8
9///
10/// MemoryManagerIdRange
11///
12/// Inclusive range of usable `MemoryManager` virtual memory IDs.
13#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
14#[serde(deny_unknown_fields)]
15pub struct MemoryManagerIdRange {
16    pub(crate) start: u8,
17    pub(crate) end: u8,
18}
19
20impl MemoryManagerIdRange {
21    /// Construct and validate an inclusive `MemoryManager` ID range.
22    pub const fn new(start: u8, end: u8) -> Result<Self, MemoryManagerRangeError> {
23        if start > end {
24            return Err(MemoryManagerRangeError::InvalidRange { start, end });
25        }
26        if start == MEMORY_MANAGER_INVALID_ID {
27            return Err(MemoryManagerRangeError::InvalidMemoryManagerId { id: start });
28        }
29        if end == MEMORY_MANAGER_INVALID_ID {
30            return Err(MemoryManagerRangeError::InvalidMemoryManagerId { id: end });
31        }
32        Ok(Self { start, end })
33    }
34
35    /// Return the full usable `MemoryManager` ID range.
36    #[must_use]
37    pub const fn all_usable() -> Self {
38        Self {
39            start: MEMORY_MANAGER_MIN_ID,
40            end: MEMORY_MANAGER_MAX_ID,
41        }
42    }
43
44    /// Return true when `id` is inside this inclusive range.
45    #[must_use]
46    pub const fn contains(&self, id: u8) -> bool {
47        id >= self.start && id <= self.end
48    }
49
50    /// Validate this range's decoded bounds.
51    pub const fn validate(&self) -> Result<(), MemoryManagerRangeError> {
52        match Self::new(self.start, self.end) {
53            Ok(_) => Ok(()),
54            Err(err) => Err(err),
55        }
56    }
57
58    /// First usable ID in the range.
59    #[must_use]
60    pub const fn start(&self) -> u8 {
61        self.start
62    }
63
64    /// Last usable ID in the range.
65    #[must_use]
66    pub const fn end(&self) -> u8 {
67        self.end
68    }
69}
70
71///
72/// MemoryManagerRangeError
73///
74/// Invalid `MemoryManager` virtual memory ID range.
75#[non_exhaustive]
76#[derive(Clone, Copy, Debug, Eq, thiserror::Error, PartialEq)]
77pub enum MemoryManagerRangeError {
78    /// Range bounds are reversed.
79    #[error("MemoryManager ID range is invalid: start={start} end={end}")]
80    InvalidRange {
81        /// Requested first ID.
82        start: u8,
83        /// Requested last ID.
84        end: u8,
85    },
86    /// ID 255 is the unallocated-bucket sentinel.
87    #[error("MemoryManager ID {id} is not a usable allocation slot")]
88    InvalidMemoryManagerId {
89        /// Invalid MemoryManager ID.
90        id: u8,
91    },
92}
93
94///
95/// MemoryManagerRangeMode
96///
97/// Allocation policy mode for a `MemoryManager` authority range.
98///
99/// These modes describe policy authority, not durable allocation state.
100/// Only `Allowed` ranges supply fresh logical placements; neither mode allocates
101/// memory by itself. [`crate::ic_memory_range!`] defaults to `Reserved` when its
102/// `mode` argument is omitted.
103///
104
105#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
106pub enum MemoryManagerRangeMode {
107    /// Range is reserved for authority-owned framework or infrastructure use.
108    ///
109    /// Reserved does not mean every ID in the range has been allocated.
110    Reserved,
111    /// Range is allowed for authority-governed application allocation use.
112    ///
113    /// Allowed does not allocate any ID in the range.
114    Allowed,
115}
116
117///
118/// MemoryManagerAuthorityRecord
119///
120/// Ordered diagnostic authority record for a `MemoryManager` ID range.
121///
122
123#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
124#[serde(deny_unknown_fields)]
125pub struct MemoryManagerAuthorityRecord {
126    /// Inclusive range governed by this authority.
127    pub(crate) range: MemoryManagerIdRange,
128    /// Stable printable ASCII authority identifier.
129    pub(crate) authority: String,
130    /// Policy mode for this authority range.
131    pub(crate) mode: MemoryManagerRangeMode,
132    /// Optional stable printable ASCII diagnostic purpose.
133    #[serde(deserialize_with = "crate::cbor::deserialize_present_option")]
134    pub(crate) purpose: Option<String>,
135}
136
137impl MemoryManagerAuthorityRecord {
138    /// Build a diagnostic authority record after validating printable metadata.
139    pub fn new(
140        range: MemoryManagerIdRange,
141        authority: impl Into<String>,
142        mode: MemoryManagerRangeMode,
143        purpose: Option<String>,
144    ) -> Result<Self, MemoryManagerRangeAuthorityError> {
145        let record = Self {
146            range,
147            authority: authority.into(),
148            mode,
149            purpose,
150        };
151        validate_authority_record(&record)?;
152        Ok(record)
153    }
154
155    /// Return the inclusive range governed by this authority.
156    #[must_use]
157    pub const fn range(&self) -> MemoryManagerIdRange {
158        self.range
159    }
160
161    /// Return the stable printable ASCII authority identifier.
162    #[must_use]
163    pub fn authority(&self) -> &str {
164        &self.authority
165    }
166
167    /// Return the policy mode for this authority range.
168    #[must_use]
169    pub const fn mode(&self) -> MemoryManagerRangeMode {
170        self.mode
171    }
172
173    /// Return the optional stable printable ASCII diagnostic purpose.
174    #[must_use]
175    pub fn purpose(&self) -> Option<&str> {
176        self.purpose.as_deref()
177    }
178
179    /// Validate constructor invariants after decode or manual assembly.
180    pub fn validate(&self) -> Result<(), MemoryManagerRangeAuthorityError> {
181        validate_authority_record(self)
182    }
183}
184
185///
186/// MemoryManagerRangeAuthority
187///
188/// Substrate-specific range authority policy helper for `MemoryManager` IDs.
189///
190/// This helper records policy and diagnostic authority ranges only. It never
191/// mutates the allocation ledger, and it does not allocate or reserve durable
192/// stable-memory slots. Durable allocation remains the generic ledger mapping
193/// from stable key to allocation slot.
194///
195/// When used through the default runtime registry, registered ranges are
196/// authoritative generic policy and are checked before caller-supplied
197/// [`crate::AllocationPolicy`]. When no user ranges are registered, frameworks
198/// can enforce fixed application claims through their own policy. Logical
199/// placement and historical selection always require explicit grants; fresh
200/// placements use only `Allowed` ranges.
201///
202
203#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
204pub struct MemoryManagerRangeAuthority {
205    authorities: Vec<MemoryManagerAuthorityRecord>,
206}
207
208#[derive(Deserialize)]
209#[serde(deny_unknown_fields)]
210struct MemoryManagerRangeAuthorityDto {
211    authorities: Vec<MemoryManagerAuthorityRecord>,
212}
213
214impl<'de> Deserialize<'de> for MemoryManagerRangeAuthority {
215    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
216        let dto = MemoryManagerRangeAuthorityDto::deserialize(deserializer)?;
217        Self::from_records(dto.authorities).map_err(D::Error::custom)
218    }
219}
220
221impl MemoryManagerRangeAuthority {
222    /// Create an empty `MemoryManager` range authority policy.
223    #[must_use]
224    pub const fn new() -> Self {
225        Self {
226            authorities: Vec::new(),
227        }
228    }
229
230    /// Build a range authority from diagnostic records.
231    ///
232    /// Each record is validated before insertion, overlaps are rejected, and
233    /// accepted records are stored in ascending range order. Decoded records
234    /// pass the same checks as records built with their checked constructor.
235    pub fn from_records(
236        records: Vec<MemoryManagerAuthorityRecord>,
237    ) -> Result<Self, MemoryManagerRangeAuthorityError> {
238        let mut authorities: Vec<MemoryManagerAuthorityRecord> = Vec::new();
239        for record in records {
240            validate_authority_record(&record)?;
241            for existing in &authorities {
242                if ranges_overlap(existing.range, record.range) {
243                    return Err(MemoryManagerRangeAuthorityError::OverlappingRanges {
244                        existing_start: existing.range.start(),
245                        existing_end: existing.range.end(),
246                        candidate_start: record.range.start(),
247                        candidate_end: record.range.end(),
248                    });
249                }
250            }
251            authorities.push(record);
252            authorities.sort_by_key(|record| record.range.start());
253        }
254        Ok(Self { authorities })
255    }
256
257    /// Validate that `slot` belongs to `expected_authority`.
258    pub fn validate_slot_authority(
259        &self,
260        slot: &AllocationSlotDescriptor,
261        expected_authority: &str,
262    ) -> Result<&MemoryManagerAuthorityRecord, MemoryManagerRangeAuthorityError> {
263        let id = slot
264            .memory_manager_id()
265            .map_err(MemoryManagerRangeAuthorityError::Slot)?;
266        self.validate_id_authority(id, expected_authority)
267    }
268
269    /// Validate that `slot` belongs to `expected_authority` with `expected_mode`.
270    pub fn validate_slot_authority_mode(
271        &self,
272        slot: &AllocationSlotDescriptor,
273        expected_authority: &str,
274        expected_mode: MemoryManagerRangeMode,
275    ) -> Result<&MemoryManagerAuthorityRecord, MemoryManagerRangeAuthorityError> {
276        let id = slot
277            .memory_manager_id()
278            .map_err(MemoryManagerRangeAuthorityError::Slot)?;
279        self.validate_id_authority_mode(id, expected_authority, expected_mode)
280    }
281
282    /// Validate that `id` belongs to `expected_authority`.
283    pub fn validate_id_authority(
284        &self,
285        id: u8,
286        expected_authority: &str,
287    ) -> Result<&MemoryManagerAuthorityRecord, MemoryManagerRangeAuthorityError> {
288        validate_diagnostic_string("expected_authority", expected_authority)?;
289        let record = self.covering_record(id)?;
290
291        if record.authority != expected_authority {
292            return Err(MemoryManagerRangeAuthorityError::AuthorityMismatch {
293                id,
294                expected_authority: expected_authority.to_string(),
295                actual_authority: record.authority.clone(),
296            });
297        }
298
299        Ok(record)
300    }
301
302    /// Validate that `id` belongs to `expected_authority` with `expected_mode`.
303    pub fn validate_id_authority_mode(
304        &self,
305        id: u8,
306        expected_authority: &str,
307        expected_mode: MemoryManagerRangeMode,
308    ) -> Result<&MemoryManagerAuthorityRecord, MemoryManagerRangeAuthorityError> {
309        let record = self.validate_id_authority(id, expected_authority)?;
310        if record.mode != expected_mode {
311            return Err(MemoryManagerRangeAuthorityError::ModeMismatch {
312                id,
313                authority: record.authority.clone(),
314                expected_mode,
315                actual_mode: record.mode,
316            });
317        }
318        Ok(record)
319    }
320
321    /// Return the authority record that governs `id`, if any.
322    pub fn authority_for_id(
323        &self,
324        id: u8,
325    ) -> Result<Option<&MemoryManagerAuthorityRecord>, MemoryManagerRangeAuthorityError> {
326        validate_memory_manager_id(id).map_err(MemoryManagerRangeAuthorityError::Slot)?;
327        Ok(self
328            .authorities
329            .iter()
330            .find(|record| record.range.contains(id)))
331    }
332
333    /// Ordered non-overlapping authority records.
334    ///
335    /// This is the stable diagnostic/export surface for the authority table.
336    /// Records are returned in ascending range order and do not imply ledger
337    /// allocation state.
338    #[must_use]
339    pub fn authorities(&self) -> &[MemoryManagerAuthorityRecord] {
340        &self.authorities
341    }
342
343    /// Validate that authority records exactly and contiguously cover `target`.
344    ///
345    /// All records must be inside `target`, and together they must form a
346    /// gap-free partition. This checks policy table coverage only and never
347    /// changes allocation ledger state.
348    pub fn validate_complete_coverage(
349        &self,
350        target: MemoryManagerIdRange,
351    ) -> Result<(), MemoryManagerRangeAuthorityError> {
352        if self.authorities.is_empty() {
353            return Err(MemoryManagerRangeAuthorityError::MissingCoverage {
354                start: target.start(),
355                end: target.end(),
356            });
357        }
358
359        for record in &self.authorities {
360            if record.range.start() < target.start() || record.range.end() > target.end() {
361                return Err(
362                    MemoryManagerRangeAuthorityError::RangeOutsideCoverageTarget {
363                        start: record.range.start(),
364                        end: record.range.end(),
365                        target_start: target.start(),
366                        target_end: target.end(),
367                    },
368                );
369            }
370        }
371
372        let mut next_uncovered = u16::from(target.start());
373        let target_end = u16::from(target.end());
374        for record in &self.authorities {
375            let record_start = u16::from(record.range.start());
376            let record_end = u16::from(record.range.end());
377
378            if record_start > next_uncovered {
379                let start = u8::try_from(next_uncovered).map_err(|_| {
380                    MemoryManagerRangeAuthorityError::MissingCoverage {
381                        start: target.start(),
382                        end: target.end(),
383                    }
384                })?;
385                return Err(MemoryManagerRangeAuthorityError::MissingCoverage {
386                    start,
387                    end: record.range.start() - 1,
388                });
389            }
390
391            if record_end >= next_uncovered {
392                next_uncovered = record_end + 1;
393            }
394        }
395
396        if next_uncovered <= target_end {
397            let start = u8::try_from(next_uncovered).map_err(|_| {
398                MemoryManagerRangeAuthorityError::MissingCoverage {
399                    start: target.start(),
400                    end: target.end(),
401                }
402            })?;
403            return Err(MemoryManagerRangeAuthorityError::MissingCoverage {
404                start,
405                end: target.end(),
406            });
407        }
408
409        Ok(())
410    }
411
412    fn covering_record(
413        &self,
414        id: u8,
415    ) -> Result<&MemoryManagerAuthorityRecord, MemoryManagerRangeAuthorityError> {
416        let Some(record) = self.authority_for_id(id)? else {
417            return Err(MemoryManagerRangeAuthorityError::UnclaimedId { id });
418        };
419        Ok(record)
420    }
421}
422
423fn validate_authority_record(
424    record: &MemoryManagerAuthorityRecord,
425) -> Result<(), MemoryManagerRangeAuthorityError> {
426    record.range.validate()?;
427    validate_diagnostic_string("authority", &record.authority)?;
428    if let Some(purpose) = &record.purpose {
429        validate_diagnostic_string("purpose", purpose)?;
430    }
431    Ok(())
432}
433
434///
435/// MemoryManagerRangeAuthorityError
436///
437/// Invalid `MemoryManager` range authority policy.
438#[non_exhaustive]
439#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)]
440pub enum MemoryManagerRangeAuthorityError {
441    /// Authority range bounds are invalid.
442    #[error(transparent)]
443    Range(#[from] MemoryManagerRangeError),
444    /// Slot descriptor is not a usable `MemoryManager` ID slot.
445    #[error("{0}")]
446    Slot(#[from] MemoryManagerSlotError),
447    /// Authority range overlaps an existing range.
448    #[error(
449        "MemoryManager authority range {candidate_start}-{candidate_end} overlaps existing range {existing_start}-{existing_end}"
450    )]
451    OverlappingRanges {
452        /// Existing range start.
453        existing_start: u8,
454        /// Existing range end.
455        existing_end: u8,
456        /// Candidate range start.
457        candidate_start: u8,
458        /// Candidate range end.
459        candidate_end: u8,
460    },
461    /// Authority or purpose text failed diagnostic string validation.
462    #[error("{field} {reason}")]
463    InvalidDiagnosticString {
464        /// Diagnostic field name.
465        field: &'static str,
466        /// Validation failure.
467        reason: &'static str,
468    },
469    /// No authority range covers the requested ID.
470    #[error("MemoryManager ID {id} is not covered by an authority range")]
471    UnclaimedId {
472        /// Unclaimed MemoryManager ID.
473        id: u8,
474    },
475    /// Slot is governed by a different authority.
476    #[error(
477        "MemoryManager ID {id} belongs to authority '{actual_authority}', not '{expected_authority}'"
478    )]
479    AuthorityMismatch {
480        /// MemoryManager ID.
481        id: u8,
482        /// Expected authority identifier.
483        expected_authority: String,
484        /// Actual authority identifier.
485        actual_authority: String,
486    },
487    /// Slot is governed by the expected authority with a different mode.
488    #[error(
489        "MemoryManager ID {id} belongs to authority '{authority}' with mode {actual_mode:?}, not {expected_mode:?}"
490    )]
491    ModeMismatch {
492        /// MemoryManager ID.
493        id: u8,
494        /// Authority identifier.
495        authority: String,
496        /// Expected authority mode.
497        expected_mode: MemoryManagerRangeMode,
498        /// Actual authority mode.
499        actual_mode: MemoryManagerRangeMode,
500    },
501    /// A complete coverage target has no authority records for part of it.
502    #[error("MemoryManager authority coverage is missing range {start}-{end}")]
503    MissingCoverage {
504        /// First missing ID.
505        start: u8,
506        /// Last missing ID.
507        end: u8,
508    },
509    /// An authority record lies outside the complete coverage target.
510    #[error(
511        "MemoryManager authority range {start}-{end} is outside coverage target {target_start}-{target_end}"
512    )]
513    RangeOutsideCoverageTarget {
514        /// Authority range start.
515        start: u8,
516        /// Authority range end.
517        end: u8,
518        /// Coverage target start.
519        target_start: u8,
520        /// Coverage target end.
521        target_end: u8,
522    },
523}
524
525const fn ranges_overlap(left: MemoryManagerIdRange, right: MemoryManagerIdRange) -> bool {
526    left.start() <= right.end() && right.start() <= left.end()
527}
528
529fn validate_diagnostic_string(
530    field: &'static str,
531    value: &str,
532) -> Result<(), MemoryManagerRangeAuthorityError> {
533    validate_diagnostic_text(value).map_err(|error| {
534        MemoryManagerRangeAuthorityError::InvalidDiagnosticString {
535            field,
536            reason: error.reason(),
537        }
538    })
539}