Skip to main content

qualia_core_db/query/
cbor_compiler.rs

1use crate::NQuin;
2
3#[derive(Debug, PartialEq, Eq)]
4pub enum ParseError {
5    UnsupportedMediaType, // HTTP 415 equivalent
6    MalformedPayload,
7    BufferOverflow,
8}
9
10/// The Strict Binary Gatekeeper for Qualia-DB network payloads.
11/// Explicitly rejects text-based semantic payloads and enforces binary
12/// CBOR-framed ingestion, with the intended semantic payload profile being
13/// CBOR-LD.
14pub fn ingest_network_payload(payload: &[u8]) -> Result<&[u8], ParseError> {
15    if payload.is_empty() {
16        return Err(ParseError::MalformedPayload);
17    }
18
19    // Read payload[0] to determine the encoding format.
20    let first_byte = payload[0];
21
22    // Reject common text-based semantic web formats:
23    // b'{' (0x7B) -> JSON-LD / JSON
24    // b'<' (0x3C) -> XML / RDF/XML
25    // b'@' (0x40) -> Turtle / N3 prefixes
26    if first_byte == b'{' || first_byte == b'<' || first_byte == b'@' {
27        return Err(ParseError::UnsupportedMediaType);
28    }
29
30    // CBOR Map (0xA0 to 0xB7) or CBOR Array (0x80 to 0x97) headers
31    // If it falls outside standard CBOR composite boundaries (for a root object), we reject it.
32    let is_cbor_map = (0xA0..=0xB7).contains(&first_byte);
33    let is_cbor_array = (0x80..=0x97).contains(&first_byte);
34    let is_cbor_indefinite = first_byte == 0xBF || first_byte == 0x9F;
35
36    if is_cbor_map || is_cbor_array || is_cbor_indefinite {
37        Ok(payload)
38    } else {
39        Err(ParseError::UnsupportedMediaType)
40    }
41}
42
43#[inline]
44fn read_cbor_int(valid_payload: &[u8], cursor: &mut usize) -> Result<u64, ParseError> {
45    if *cursor >= valid_payload.len() {
46        return Err(ParseError::BufferOverflow);
47    }
48    let byte = valid_payload[*cursor];
49    *cursor += 1;
50
51    let major_type = byte >> 5;
52    // Only accept unsigned integers (major type 0) for Lexicon tags
53    if major_type != 0 {
54        // In a full implementation, we'd handle tags and strings.
55        // For the Strict Binary Dictionary, all URIs are pre-compressed to integers.
56        return Ok(0);
57    }
58
59    let additional_info = byte & 0x1F;
60    match additional_info {
61        0..=23 => Ok(additional_info as u64),
62        24 => {
63            if *cursor + 1 > valid_payload.len() {
64                return Err(ParseError::BufferOverflow);
65            }
66            let val = valid_payload[*cursor] as u64;
67            *cursor += 1;
68            Ok(val)
69        }
70        25 => {
71            if *cursor + 2 > valid_payload.len() {
72                return Err(ParseError::BufferOverflow);
73            }
74            let mut bytes = [0u8; 2];
75            bytes.copy_from_slice(&valid_payload[*cursor..*cursor + 2]);
76            *cursor += 2;
77            Ok(u16::from_be_bytes(bytes) as u64)
78        }
79        26 => {
80            if *cursor + 4 > valid_payload.len() {
81                return Err(ParseError::BufferOverflow);
82            }
83            let mut bytes = [0u8; 4];
84            bytes.copy_from_slice(&valid_payload[*cursor..*cursor + 4]);
85            *cursor += 4;
86            Ok(u32::from_be_bytes(bytes) as u64)
87        }
88        27 => {
89            if *cursor + 8 > valid_payload.len() {
90                return Err(ParseError::BufferOverflow);
91            }
92            let mut bytes = [0u8; 8];
93            bytes.copy_from_slice(&valid_payload[*cursor..*cursor + 8]);
94            *cursor += 8;
95            Ok(u64::from_be_bytes(bytes))
96        }
97        _ => Err(ParseError::MalformedPayload),
98    }
99}
100
101/// A lightweight, `no_std`-compatible loop to read variable-length integers from CBOR-LD,
102/// returning both the decoded [`NQuin`] (with canonical 5-field XOR parity) and the exact
103/// byte cursor consumed from `payload`.
104///
105/// Supports both 4-integer frames `[Subject, Predicate, Object, Context]` (defaulting
106/// `metadata` to `0`) and 5-integer frames `[Subject, Predicate, Object, Context, Metadata]`
107/// (preserving Core-1 N3Logic routing bits `0b10 << 61` and `FrameLayout` tags).
108pub fn parse_cbor_ld_to_quin_sized(payload: &[u8]) -> Result<(NQuin, usize), ParseError> {
109    // 1. Enforce the Strict Binary Gatekeeper
110    let valid_payload = ingest_network_payload(payload)?;
111    let first_byte = valid_payload[0];
112
113    let mut cursor = 1; // Skip the root map/array byte
114
115    let subject = read_cbor_int(valid_payload, &mut cursor)?;
116    let predicate = read_cbor_int(valid_payload, &mut cursor)?;
117    let object = read_cbor_int(valid_payload, &mut cursor)?;
118    let context = read_cbor_int(valid_payload, &mut cursor)?;
119
120    // Read optional 5th CBOR integer for `metadata` when present.
121    let metadata = if (0x80..=0x97).contains(&first_byte) {
122        let count = (first_byte & 0x1F) as usize;
123        if count < 4 {
124            return Err(ParseError::MalformedPayload);
125        }
126        if count >= 5 {
127            let m = read_cbor_int(valid_payload, &mut cursor)?;
128            for _ in 5..count {
129                let _ = read_cbor_int(valid_payload, &mut cursor)?;
130            }
131            m
132        } else {
133            0b00 << 61
134        }
135    } else if (0xA0..=0xB7).contains(&first_byte) {
136        let count = (first_byte & 0x1F) as usize;
137        if count >= 5 {
138            read_cbor_int(valid_payload, &mut cursor)?
139        } else {
140            0b00 << 61
141        }
142    } else {
143        // Indefinite-length array (0x9F) or map (0xBF)
144        let m = if cursor < valid_payload.len() && valid_payload[cursor] != 0xFF {
145            read_cbor_int(valid_payload, &mut cursor)?
146        } else {
147            0b00 << 61
148        };
149        if cursor < valid_payload.len() && valid_payload[cursor] == 0xFF {
150            cursor += 1;
151        }
152        m
153    };
154
155    let parity = NQuin::calculate_parity(subject, predicate, object, context, metadata);
156
157    Ok((
158        NQuin {
159            subject,
160            predicate,
161            object,
162            context,
163            metadata,
164            parity,
165        },
166        cursor,
167    ))
168}
169
170/// A lightweight, `no_std`-compatible loop to read variable-length integers from CBOR-LD.
171/// Maps the extracted dictionary tags directly into the 64-bit Lexicon registers
172/// without allocating a single `String` or `Vec`, and computes canonical 5-field XOR parity.
173pub fn parse_cbor_ld_to_quin(payload: &[u8]) -> Result<NQuin, ParseError> {
174    parse_cbor_ld_to_quin_sized(payload).map(|(quin, _)| quin)
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    #[test]
182    fn test_gatekeeper_rejects_json() {
183        let json_payload = b"{\"@context\": \"http://schema.org\"}";
184        assert_eq!(
185            ingest_network_payload(json_payload),
186            Err(ParseError::UnsupportedMediaType)
187        );
188    }
189
190    #[test]
191    fn test_gatekeeper_rejects_turtle() {
192        let turtle_payload = b"@prefix qualia: <urn:qualia:> .";
193        assert_eq!(
194            ingest_network_payload(turtle_payload),
195            Err(ParseError::UnsupportedMediaType)
196        );
197    }
198
199    #[test]
200    fn test_parse_cbor_ld_dictionary() {
201        // CBOR Array of 4 integers: [1000, 2000, 3000, 4000]
202        // Array header: 0x84
203        // 1000 = 0x19 0x03 0xE8
204        // 2000 = 0x19 0x07 0xD0
205        // 3000 = 0x19 0x0B 0xB8
206        // 4000 = 0x19 0x0F 0xA0
207        let cbor_payload: [u8; 13] = [
208            0x84, 0x19, 0x03, 0xE8, 0x19, 0x07, 0xD0, 0x19, 0x0B, 0xB8, 0x19, 0x0F, 0xA0,
209        ];
210
211        let (quin, consumed) = parse_cbor_ld_to_quin_sized(&cbor_payload).unwrap();
212
213        assert_eq!(consumed, 13);
214        assert_eq!(quin.subject, 1000);
215        assert_eq!(quin.predicate, 2000);
216        assert_eq!(quin.object, 3000);
217        assert_eq!(quin.context, 4000);
218        assert_eq!(quin.metadata, 0);
219        assert_eq!(
220            quin.parity,
221            1000u64 ^ 2000u64 ^ 3000u64 ^ 4000u64 ^ 0u64,
222            "must compute canonical 5-field XOR parity"
223        );
224        assert!(quin.verify_ecc_parity());
225    }
226
227    #[test]
228    fn test_parse_cbor_ld_with_fifth_metadata_integer_and_parity() {
229        // CBOR Array of 5 integers: [1000, 2000, 3000, 4000, metadata]
230        // metadata = (0b10 << 61) | 42 = 0x4000_0000_0000_002A
231        let meta: u64 = (0b10u64 << 61) | 42;
232        let mut cbor_payload = [0u8; 22];
233        cbor_payload[0] = 0x85; // 5-element array
234        cbor_payload[1..13].copy_from_slice(&[
235            0x19, 0x03, 0xE8, 0x19, 0x07, 0xD0, 0x19, 0x0B, 0xB8, 0x19, 0x0F, 0xA0,
236        ]);
237        cbor_payload[13] = 27; // 8-byte uint follows
238        cbor_payload[14..22].copy_from_slice(&meta.to_be_bytes());
239
240        let (quin, consumed) = parse_cbor_ld_to_quin_sized(&cbor_payload).unwrap();
241        assert_eq!(consumed, 22);
242        assert_eq!(quin.metadata, meta);
243        assert_eq!(
244            quin.parity,
245            NQuin::calculate_parity(1000, 2000, 3000, 4000, meta)
246        );
247        assert!(quin.verify_ecc_parity());
248    }
249
250    #[test]
251    fn test_parse_cbor_buffer_overflow() {
252        // Truncated array header
253        let cbor_payload: [u8; 4] = [0x84, 0x19, 0x03, 0xE8];
254        assert_eq!(
255            parse_cbor_ld_to_quin(&cbor_payload),
256            Err(ParseError::BufferOverflow)
257        );
258    }
259}