qualia_core_db/q42/field_semantics/
mod.rs1use super::field_envelope::{Block, Entry, Field, StructuralView};
5mod entries;
6mod graph;
7mod rules;
8mod shared;
9pub use rules::{validate_fields, FieldRule};
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum Error {
13 Scratch,
14 Limit,
15 Overflow,
16 MissingField,
17 FieldType,
18 RequiredCritical,
19 UnknownCriticalSchema,
20 UnknownCriticalField,
21 UnknownCriticalType,
22 UnsupportedDomain,
23 Reference,
24 ReferenceSchema,
25 Cycle,
26 Depth,
27 Value,
28 Frame,
29 Time,
30 Descriptor,
31 Provenance,
32 Validity,
33 PayloadIntegrity,
34}
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub struct Limits {
37 pub blocks: usize,
38 pub entries: usize,
39 pub edges: usize,
40 pub depth: u32,
41 pub work: u64,
43}
44impl Default for Limits {
45 fn default() -> Self {
46 Self {
47 blocks: 4096,
48 entries: 4096,
49 edges: 16384,
50 depth: 32,
51 work: 8_000_000,
52 }
53 }
54}
55#[derive(Clone, Copy, Debug, Default)]
57pub struct NodeState {
58 id: u32,
59 indegree: u32,
60 depth: u32,
61 done: bool,
62}
63pub struct Scratch<'a> {
64 pub metadata: &'a mut [NodeState],
65 pub entries: &'a mut [NodeState],
66}
67pub trait DomainRegistry {
71 fn rules(&self, _schema: u16, _revision: u16) -> Option<&'static [FieldRule]> {
72 None
73 }
74 fn validate_block(&self, _block: Block<'_>, _context: &Context<'_, '_>) -> Result<(), Error> {
75 Err(Error::UnsupportedDomain)
76 }
77 fn descriptor_target_schema(&self, _key: u16) -> Option<u16> {
79 None
80 }
81 fn validate_units(&self, _units: &str, _context: &Context<'_, '_>) -> Result<(), Error> {
82 Err(Error::UnsupportedDomain)
83 }
84 fn validate_grid_frame(
87 &self,
88 _frame: Block<'_>,
89 _context: &Context<'_, '_>,
90 ) -> Result<(), Error> {
91 Err(Error::UnsupportedDomain)
92 }
93 fn validate_spatial_entry(
96 &self,
97 _entry: Entry<'_>,
98 frame: Block<'_>,
99 _context: &Context<'_, '_>,
100 ) -> Result<(), Error> {
101 if field(frame, 7).is_some() {
102 Ok(())
103 } else {
104 Err(Error::UnsupportedDomain)
105 }
106 }
107 fn validate_frame_profile(
109 &self,
110 _frame: Block<'_>,
111 _context: &Context<'_, '_>,
112 ) -> Result<(), Error> {
113 Err(Error::UnsupportedDomain)
114 }
115}
116#[derive(Clone, Copy, Debug, Default)]
117pub struct SharedOnly;
118impl DomainRegistry for SharedOnly {}
119#[derive(Debug)]
120pub struct Context<'v, 'a> {
121 view: &'v StructuralView<'a>,
122 work: std::cell::Cell<u64>,
123}
124impl<'v, 'a> Context<'v, 'a> {
125 pub fn charge_work(&self, amount: u64) -> Result<(), Error> {
127 let left = self.work.get().checked_sub(amount).ok_or(Error::Limit)?;
128 self.work.set(left);
129 Ok(())
130 }
131 pub fn remaining_work(&self) -> u64 {
132 self.work.get()
133 }
134 pub fn blocks(&self) -> impl Iterator<Item = Result<Block<'a>, Error>> + '_ {
136 self.view.blocks().map(move |block| {
137 self.charge_work(1)?;
138 Ok(block)
139 })
140 }
141 pub fn block(&self, id: u32) -> Result<Block<'a>, Error> {
142 for block in self.view.blocks() {
143 self.charge_work(1)?;
144 if block.id() == id {
145 return Ok(block);
146 }
147 }
148 Err(Error::Reference)
149 }
150 pub fn entry(&self, id: u32) -> Result<Entry<'a>, Error> {
151 self.charge_work(1)?;
152 self.view.entry(id).map_err(|_| Error::Reference)
153 }
154 pub fn require_schema(&self, id: u32, schema: u16) -> Result<Block<'a>, Error> {
155 let block = self.block(id)?;
156 if block.schema_type() != schema || block.revision() != 1 {
157 return Err(Error::ReferenceSchema);
158 }
159 Ok(block)
160 }
161 fn require_admitted(
162 &self,
163 id: u32,
164 registry: &impl DomainRegistry,
165 ) -> Result<Block<'a>, Error> {
166 let block = self.block(id)?;
167 if rules::shared_rules(block.schema_type(), block.revision()).is_none()
168 && registry
169 .rules(block.schema_type(), block.revision())
170 .is_none()
171 {
172 return Err(Error::UnsupportedDomain);
173 }
174 Ok(block)
175 }
176}
177pub struct SharedAdmission<'v, 'a> {
180 pub context: Context<'v, 'a>,
181 pub preserved_unknown_blocks: u32,
182}
183pub fn admit_shared<'v, 'a>(
184 view: &'v StructuralView<'a>,
185 registry: &impl DomainRegistry,
186 scratch: &mut Scratch<'_>,
187 limits: Limits,
188) -> Result<SharedAdmission<'v, 'a>, Error> {
189 let context = Context {
190 view,
191 work: std::cell::Cell::new(limits.work),
192 };
193 let mut count = 0usize;
194 for _ in view.blocks() {
195 context.charge_work(1)?;
196 count += 1;
197 if count > limits.blocks {
198 return Err(Error::Limit);
199 }
200 }
201 if count > limits.blocks || view.entry_count() as usize > limits.entries {
202 return Err(Error::Limit);
203 }
204 if scratch.metadata.len() < count || scratch.entries.len() < view.entry_count() as usize {
205 return Err(Error::Scratch);
206 }
207 let mut unknown = 0u32;
208 for block in view.blocks() {
209 context.charge_work(block.raw_bytes().len() as u64)?;
210 let fields = block.fields().count() as u64;
211 context.charge_work(fields.checked_mul(64).ok_or(Error::Overflow)?)?;
212 for field in block.fields() {
213 if !(1..=11).contains(&field.type_tag()) && field.flags() & 1 != 0 {
214 return Err(Error::UnknownCriticalType);
215 }
216 }
217 if let Some(rules) = rules::shared_rules(block.schema_type(), block.revision()) {
218 context.charge_work(
219 fields
220 .checked_mul(rules.len() as u64 + 1)
221 .ok_or(Error::Overflow)?,
222 )?;
223 validate_fields(block, rules)?;
224 shared::validate(block, &context, registry)?;
225 } else if let Some(rules) = registry.rules(block.schema_type(), block.revision()) {
226 validate_fields(block, rules)?;
227 registry.validate_block(block, &context)?;
228 } else {
229 if block.flags() & 1 != 0 {
230 return Err(Error::UnknownCriticalSchema);
231 }
232 if block.fields().any(|f| f.flags() & 1 != 0) {
233 return Err(Error::UnknownCriticalField);
234 }
235 unknown = unknown.checked_add(1).ok_or(Error::Overflow)?;
236 }
237 }
238 entries::validate(&context, registry)?;
239 graph::metadata(&context, &mut scratch.metadata[..count], limits)?;
240 graph::ancestry(
241 &context,
242 &mut scratch.entries[..view.entry_count() as usize],
243 limits,
244 )?;
245 Ok(SharedAdmission {
246 context,
247 preserved_unknown_blocks: unknown,
248 })
249}
250pub fn field<'a>(block: Block<'a>, key: u16) -> Option<Field<'a>> {
251 block.fields().find(|f| f.key() == key)
252}
253fn required<'a>(block: Block<'a>, key: u16) -> Result<Field<'a>, Error> {
254 field(block, key).ok_or(Error::MissingField)
255}
256fn u32_at(b: &[u8], at: usize) -> u32 {
257 u32::from_le_bytes(b[at..at + 4].try_into().unwrap())
258}
259fn u64_at(b: &[u8], at: usize) -> u64 {
260 u64::from_le_bytes(b[at..at + 8].try_into().unwrap())
261}
262fn scalar32(block: Block<'_>, key: u16) -> Result<u32, Error> {
263 Ok(u32_at(required(block, key)?.value(), 0))
264}
265fn scalar64(block: Block<'_>, key: u16) -> Result<u64, Error> {
266 Ok(u64_at(required(block, key)?.value(), 0))
267}
268fn text(field: Field<'_>) -> Result<&str, Error> {
269 std::str::from_utf8(field.value()).map_err(|_| Error::Value)
270}
271fn identifier(field: Field<'_>) -> Result<(), Error> {
272 let s = text(field)?;
273 if s.is_empty() || s.chars().any(|c| c.is_control()) {
274 return Err(Error::Value);
275 }
276 Ok(())
277}
278#[cfg(test)]
279mod tests;