Skip to main content

qualia_core_db/sensing/container/
view.rs

1use super::super::{
2    record::{
3        decode_measurement_index_record, MeasurementRecord, ResolvedFieldPayloadBinding,
4        MAX_MEASUREMENT_INDEX_RECORDS, MEASUREMENT_INDEX_RECORD_SIZE,
5    },
6    PhysicalFieldSemantics,
7};
8use super::{validate_container, validate_kind, SensingContainerError};
9use crate::container_10d::{typed_payloads::TypedPayloadResolver, SectionType};
10
11/// Borrowed index and raw payload resolver for the same checked envelope.
12/// The host still authenticates the container and field semantic pairing.
13pub struct SensingIndexView<'r, 'data, 'fields> {
14    resolver: &'r TypedPayloadResolver<'data, 'fields>,
15    index: &'data [u8],
16    index_offset: u64,
17    container_id: [u8; 16],
18}
19
20/// Canonical record and exact raw bytes borrowed from one checked resolver.
21/// This establishes structural binding, not container authenticity or policy.
22pub struct ResolvedSensingMeasurement<'data> {
23    record: MeasurementRecord,
24    binding: ResolvedFieldPayloadBinding,
25    payload: &'data [u8],
26}
27
28impl<'data> ResolvedSensingMeasurement<'data> {
29    pub const fn record(&self) -> MeasurementRecord {
30        self.record
31    }
32    pub const fn binding(&self) -> ResolvedFieldPayloadBinding {
33        self.binding
34    }
35    pub const fn payload(&self) -> &'data [u8] {
36        self.payload
37    }
38}
39
40impl<'r, 'data, 'fields> SensingIndexView<'r, 'data, 'fields> {
41    pub fn open(
42        resolver: &'r TypedPayloadResolver<'data, 'fields>,
43        index_field_id: u64,
44        extension_kind: u16,
45        container_id: [u8; 16],
46    ) -> Result<Self, SensingContainerError> {
47        validate_kind(extension_kind)?;
48        validate_container(&container_id)?;
49        if index_field_id == 0 {
50            return Err(SensingContainerError::InvalidFieldId);
51        }
52        let index = resolver
53            .field(index_field_id)
54            .map_err(|_| SensingContainerError::Resolver)?
55            .ok_or(SensingContainerError::MissingIndex)?;
56        if index.record.kind != extension_kind
57            || index.record.flags != 0
58            || index.record.unit_id != 0
59            || index.record.payload_section_id != SectionType::FieldSidecar as u32
60            || index.bytes.is_empty()
61            || index.bytes.len() % MEASUREMENT_INDEX_RECORD_SIZE != 0
62            || index.bytes.len() / MEASUREMENT_INDEX_RECORD_SIZE > MAX_MEASUREMENT_INDEX_RECORDS
63        {
64            return Err(SensingContainerError::InvalidIndex);
65        }
66        for (i, row) in index
67            .bytes
68            .chunks_exact(MEASUREMENT_INDEX_RECORD_SIZE)
69            .enumerate()
70        {
71            if &row[..4] != b"SMR1"
72                || u16::from_le_bytes([row[4], row[5]]) != 1
73                || u16::from_le_bytes([row[6], row[7]]) as usize != MEASUREMENT_INDEX_RECORD_SIZE
74                || u64_at(row, 8) == 0
75                || u64_at(row, 24) == index_field_id
76            {
77                return Err(SensingContainerError::InvalidIndex);
78            }
79            if index.bytes[..i * MEASUREMENT_INDEX_RECORD_SIZE]
80                .chunks_exact(MEASUREMENT_INDEX_RECORD_SIZE)
81                .any(|prior| u64_at(prior, 8) == u64_at(row, 8))
82            {
83                return Err(SensingContainerError::DuplicateRecordId);
84            }
85        }
86        Ok(Self {
87            resolver,
88            index: index.bytes,
89            index_offset: index.record.payload_offset,
90            container_id,
91        })
92    }
93
94    pub fn count(&self) -> usize {
95        self.index.len() / MEASUREMENT_INDEX_RECORD_SIZE
96    }
97
98    /// Untrusted row selector for locating the caller's semantic declaration.
99    /// Canonical payload binding is checked only by `record`.
100    pub fn field_id(&self, index: usize) -> Result<u64, SensingContainerError> {
101        if index >= self.count() {
102            return Err(SensingContainerError::Range);
103        }
104        Ok(u64_at(
105            &self.index[index * MEASUREMENT_INDEX_RECORD_SIZE..],
106            24,
107        ))
108    }
109
110    /// Decode a row with raw bytes resolved from this same envelope. A row is
111    /// not published until its entire canonical encoding matches that binding.
112    pub fn record(
113        &self,
114        index: usize,
115        physical: PhysicalFieldSemantics,
116    ) -> Result<MeasurementRecord, SensingContainerError> {
117        self.resolve_record(index, physical)
118            .map(|resolved| resolved.record)
119    }
120
121    /// Resolve a canonical index row and borrow its raw payload from this same
122    /// envelope. No second resolver or caller-supplied byte slice is accepted.
123    pub fn resolve_record(
124        &self,
125        index: usize,
126        physical: PhysicalFieldSemantics,
127    ) -> Result<ResolvedSensingMeasurement<'data>, SensingContainerError> {
128        if index >= self.count() {
129            return Err(SensingContainerError::Range);
130        }
131        let binding = ResolvedFieldPayloadBinding::new(physical, self.resolver, self.container_id)
132            .map_err(SensingContainerError::Record)?;
133        let raw = binding.raw_payload();
134        if raw.section_id() == SectionType::FieldSidecar as u32 {
135            let raw_end = raw
136                .offset()
137                .checked_add(raw.length())
138                .ok_or(SensingContainerError::Range)?;
139            let index_end = self
140                .index_offset
141                .checked_add(self.index.len() as u64)
142                .ok_or(SensingContainerError::Range)?;
143            if raw.offset() < index_end && self.index_offset < raw_end {
144                return Err(SensingContainerError::IndexPayloadOverlap);
145            }
146        }
147        let start = index * MEASUREMENT_INDEX_RECORD_SIZE;
148        let record = decode_measurement_index_record(
149            &self.index[start..start + MEASUREMENT_INDEX_RECORD_SIZE],
150            binding,
151        )
152        .map_err(SensingContainerError::Record)?;
153        let payload = self
154            .resolver
155            .field(physical.field_id())
156            .map_err(|_| SensingContainerError::Resolver)?
157            .ok_or(SensingContainerError::Resolver)?;
158        Ok(ResolvedSensingMeasurement {
159            record,
160            binding,
161            payload: payload.bytes,
162        })
163    }
164}
165
166fn u64_at(bytes: &[u8], at: usize) -> u64 {
167    u64::from_le_bytes(bytes[at..at + 8].try_into().expect("fixed index row"))
168}