1use crate::{
4 __private::RowInfo,
5 Error, IndexValue,
6 codec::Decoder,
7 key,
8 named_schema::{TypeGraph, TypeLink},
9 primary::RowKey,
10};
11use sha2::{Digest, Sha256};
12use std::{collections::BTreeSet, sync::Arc};
13
14#[doc(hidden)]
18#[must_use]
19pub const fn check_schema_member(path: &str, root: &str, members: Option<&str>) -> bool {
20 const fn listed(path: &[u8], list: &[u8]) -> bool {
21 let mut start = 0;
22 while start < list.len() {
23 let mut end = start;
24 let mut same = true;
25 while end < list.len() && list[end] != b'|' {
26 let i = end - start;
27 same = same && i < path.len() && path[i] == list[end];
28 end += 1;
29 }
30 if same && end - start == path.len() {
31 return true;
32 }
33 start = end + 1;
34 }
35
36 false
37 }
38 let path = path.as_bytes();
39 let mut first_separator = 0;
40 while first_separator < path.len() && path[first_separator] != b':' {
41 first_separator += 1;
42 }
43 let (_, relative) = path.split_at(first_separator);
44
45 let root = root.as_bytes();
46 let mut index = 0;
47 while index < root.len() {
48 if index == relative.len() || relative[index] != root[index] {
49 return true;
50 }
51 index += 1;
52 }
53
54 match members {
55 Some(paths) => listed(relative, paths.as_bytes()),
56 None => false,
57 }
58}
59
60pub(crate) const MAX_ENTITIES: u8 = 128;
61pub(crate) const MAX_FIELDS: usize = 32;
62
63#[doc(hidden)]
66#[must_use]
67pub const fn handle(name: &str) -> u32 {
68 let bytes = name.as_bytes();
69 let mut value = 2_166_136_261_u32;
70 let mut position = 0;
71 while position < bytes.len() {
72 value = (value ^ bytes[position] as u32).wrapping_mul(16_777_619);
73 position += 1;
74 }
75
76 value
77}
78
79#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
81pub enum FieldType {
82 List {
84 item: &'static FieldType,
86 max_items: u32,
88 },
89 Named(TypeLink),
92 Nat8,
94 Nat16,
96 Nat32,
98 Int8,
100 Int16,
102 Int32,
104 Nat64,
106 Int64,
108 Nat128,
110 Int128,
112 U256,
114 Ulid,
116 Date,
118 Timestamp,
120 Duration,
122 Decimal {
124 scale: u32,
126 },
127 Float32,
129 Float64,
131 Bool,
133 Principal,
135 Subaccount,
137 Account,
139 Text {
141 max_bytes: u32,
143 },
144 Blob {
146 max_bytes: u32,
148 },
149}
150
151#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
153pub struct FieldSchema {
154 pub managed: Option<crate::ManagedTimestamp>,
156 pub default: Option<&'static crate::LiteralDefault>,
158 pub name: &'static str,
160 pub value: FieldType,
162 pub optional: bool,
164 pub reference: Option<ReferenceSchema>,
166}
167
168#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
171pub struct ReferenceSchema {
172 pub entity_name: &'static str,
174 #[doc(hidden)]
176 pub entity: u32,
177 pub index: u32,
179}
180
181#[derive(Debug, PartialEq, Eq, serde::Serialize)]
183pub struct IndexSchema {
184 #[doc(hidden)]
186 pub id: u32,
187 pub name: &'static str,
189 pub fields: &'static [&'static str],
191 pub unique: bool,
193 pub present_only: bool,
195}
196
197impl IndexSchema {
198 pub(crate) fn is_unique_lookup(&self, fixed_components: usize) -> bool {
200 self.unique && fixed_components == self.fields.len()
201 }
202}
203
204#[derive(serde::Serialize)]
206pub struct EntitySchema {
207 pub max_row_bytes: usize,
209 #[doc(hidden)]
211 pub id: u32,
212 pub name: &'static str,
214 pub fields: &'static [FieldSchema],
216 pub primary_key: &'static str,
218 pub indexes: &'static [IndexSchema],
220}
221
222impl EntitySchema {
223 pub(crate) fn field_position(&self, name: &str) -> Option<usize> {
224 self.fields.iter().position(|field| field.name == name)
225 }
226
227 pub(crate) fn field_by_name(&self, name: &str) -> Option<&FieldSchema> {
228 self.field_position(name)
229 .map(|position| &self.fields[position])
230 }
231
232 pub(crate) fn field_is_required(&self, path: &str) -> bool {
233 self.index_field(path).is_some_and(|field| !field.optional)
234 }
235
236 pub(crate) fn record_member(&self, path: &str) -> Option<(usize, crate::member::RecordMember)> {
237 let (parent, child) = path.split_once('.')?;
238 let position = self.field_position(parent)?;
239 let member =
240 crate::member::RecordMember::resolve(self.fields[position].value, child).ok()?;
241 Some((position, member))
242 }
243
244 pub(crate) fn index_field(&self, name: &str) -> Option<crate::ValueSchema> {
245 let (parent, member) = crate::member::resolve_field(self, name).ok()?;
246 let field = &self.fields[parent];
247 let leaf = member.map_or(field, |m| m.field());
248
249 Some(crate::ValueSchema {
250 value: leaf.value,
251 optional: field.optional || leaf.optional,
252 })
253 }
254
255 pub(crate) fn index_by_name(&self, name: &str) -> Option<&IndexSchema> {
256 self.indexes.iter().find(|index| index.name == name)
257 }
258
259 pub(crate) fn has_managed(&self) -> bool {
260 self.fields.iter().any(|field| field.managed.is_some())
261 }
262
263 pub(crate) fn key_type(&self) -> Result<FieldType, Error> {
264 self.field_by_name(self.primary_key)
265 .filter(|field| !field.optional)
266 .map(|f| f.value)
267 .ok_or(Error::Corrupt)
268 }
269 pub(crate) fn inspect_row(&self, bytes: &[u8]) -> Result<RowInfo, Error> {
272 let mut values = [IndexValue::Absent; MAX_FIELDS];
273 let mut spans = [(0, 0); MAX_FIELDS];
274 self.inspect_fields(bytes, self.key_fields(), &mut values, Some(&mut spans))?;
275
276 self.row_info(&values, bytes, &spans)
277 }
278
279 pub(crate) fn key_fields(&self) -> u32 {
280 self.fields
281 .iter()
282 .enumerate()
283 .fold(0, |mask, (position, field)| {
284 if field.name == self.primary_key
285 || self.indexes.iter().any(|i| i.fields.contains(&field.name))
286 {
287 mask | (1 << position)
288 } else {
289 mask
290 }
291 })
292 }
293 pub(crate) fn inspect_fields<'a>(
299 &self,
300 bytes: &'a [u8],
301 selected: u32,
302 keys: &mut [IndexValue<'a>; MAX_FIELDS],
303 mut spans: Option<&mut [(u16, u16); MAX_FIELDS]>,
304 ) -> Result<(), Error> {
305 let mut reader = Decoder::for_entity(bytes, self)?;
306 let mut times = [None; 2];
307 for (position, field) in self.fields.iter().enumerate() {
308 let start = reader.position();
309 let present = !field.optional || reader.boolean()?;
310 if !present {
311 } else if let Some(managed) = field.managed {
313 let value = reader.timestamp()?;
314 times[managed.slot()] = Some(value);
315 keys[position] = IndexValue::from(value);
316 } else if selected & (1 << position) != 0 {
317 *keys.get_mut(position).ok_or(Error::Corrupt)? =
318 IndexValue::read(&mut reader, field.value)?;
319 } else {
320 reader.skip(field.value)?;
321 }
322 if let Some(spans) = &mut spans {
323 spans[position] = (start as u16, reader.position() as u16);
324 }
325 }
326 reader.finish()?;
327 crate::managed::validate_order(times)?;
328
329 Ok(())
330 }
331
332 pub(crate) fn row_info<'a>(
333 &self,
334 keys: &[IndexValue<'a>; MAX_FIELDS],
335 bytes: &'a [u8],
336 spans: &[(u16, u16); MAX_FIELDS],
337 ) -> Result<RowInfo, Error> {
338 let position = |name: &str| self.field_position(name).ok_or(Error::Corrupt);
339 let indexes = self
340 .indexes
341 .iter()
342 .map(|index| {
343 let mut components = [(IndexValue::Absent, false); 4];
344 for (slot, name) in components.iter_mut().zip(index.fields) {
345 *slot = if let Some(position) = self.field_position(name) {
346 (keys[position], self.fields[position].optional)
347 } else {
348 let (parent, member) = self.record_member(name).ok_or(Error::Corrupt)?;
349 let (start, end) = spans[parent];
350 let optional = self.fields[parent].optional;
351 (
352 member.read(&bytes[usize::from(start)..usize::from(end)], optional)?,
353 optional || member.field().optional,
354 )
355 };
356 if slot.0 == IndexValue::Absent && !slot.1 {
357 return Err(Error::Corrupt);
358 }
359 }
360
361 Ok(key::encode_index(
362 &components[..index.fields.len()],
363 index.present_only,
364 ))
365 })
366 .collect::<Result<_, Error>>()?;
367 let key = RowKey::from_index(keys[position(self.primary_key)?])?;
368
369 let mut list_links = Vec::new();
370 for (field, &(start, end)) in self.fields.iter().zip(spans) {
371 if let (Some(reference), FieldType::List { item, max_items }) =
372 (field.reference, field.value)
373 {
374 let mut reader = Decoder::new(&bytes[usize::from(start)..usize::from(end)])?;
375 if !field.optional || reader.boolean()? {
376 let count = reader.nat32()?;
377 if count > max_items {
378 return Err(Error::Corrupt);
379 }
380 for _ in 0..count {
381 list_links.push((
382 reference.index,
383 RowKey::from_index(IndexValue::read(&mut reader, *item)?)?,
384 ));
385 }
386 }
387 reader.finish()?;
388 }
389 }
390 Ok(RowInfo {
391 key,
392 indexes,
393 list_links,
394 })
395 }
396}
397
398#[derive(Clone)]
403pub struct Schema {
404 metadata: Arc<SchemaMetadata>,
405 pub(crate) fingerprint: [u8; 32],
406}
407
408struct SchemaMetadata {
409 entities: Vec<&'static EntitySchema>,
410 types: TypeGraph,
411}
412
413#[derive(serde::Serialize)]
415pub struct SchemaDescription<'a> {
416 pub fingerprint: [u8; 32],
418 pub entities: &'a [&'static EntitySchema],
420 pub types: Vec<&'static crate::TypeSchema>,
422}
423
424impl Schema {
425 pub fn new(entities: &[&'static EntitySchema]) -> Result<Self, Error> {
429 Self::admit_schema(entities, |_, _, _, _| {})
430 }
431
432 pub(crate) fn admit_schema(
434 entities: &[&'static EntitySchema],
435 report_reference: impl FnOnce(&str, &FieldSchema, &str, Option<(&str, FieldType)>),
436 ) -> Result<Self, Error> {
437 if entities.is_empty() || entities.len() > usize::from(MAX_ENTITIES) {
438 return Err(Error::InvalidSchema);
439 }
440 let mut entities = entities.to_vec();
441 entities.sort_by_key(|entity| entity.name);
442 let mut bytes = Vec::new();
443 for version in [crate::codec::ROW_CODEC_VERSION, 1, 2, 1] {
450 bytes.extend(version.to_le_bytes());
451 }
452 bytes.extend((entities.len() as u32).to_le_bytes());
453 let mut ids = BTreeSet::new();
454 let mut types = TypeGraph::default();
455 for entity in &entities {
456 if entity.id != handle(entity.name)
457 || !ids.insert(entity.id)
458 || entity.fields.is_empty()
459 || !(1..=crate::codec::MAX_ROW_BYTES).contains(&entity.max_row_bytes)
460 || entity.fields.len() > MAX_FIELDS
461 || entity.indexes.len() > 8
462 || !entity.key_type().is_ok_and(RowKey::supports)
463 || entity
464 .fields
465 .windows(2)
466 .any(|pair| pair[0].name >= pair[1].name)
467 {
468 return Err(Error::InvalidSchema);
469 }
470 name(&mut bytes, entity.name)?;
471 if entity.max_row_bytes != crate::codec::DEFAULT_ROW_BYTES {
472 bytes.extend(0_u32.to_le_bytes());
474 bytes.extend((entity.max_row_bytes as u32).to_le_bytes());
475 }
476 bytes.extend((entity.fields.len() as u32).to_le_bytes());
477 let mut list_fanout = 0;
478 let mut list_indexes = BTreeSet::new();
479 for field in entity.fields {
480 name(&mut bytes, field.name)?;
481 encode_type(
482 &mut bytes,
483 field.value,
484 field.optional,
485 field.reference.is_some(),
486 )?;
487 types.include(field.value)?;
488 if let Some(reference) = field.reference {
489 let Some(target) = entities.iter().find(|target| {
490 target.id == reference.entity && target.name == reference.entity_name
491 }) else {
492 report_reference(entity.name, field, reference.entity_name, None);
493
494 return Err(Error::InvalidSchema);
495 };
496 let key_type = target.key_type().map_err(|_| Error::InvalidSchema)?;
497 let referenced_type = match field.value {
498 FieldType::List { item, .. } => *item,
499 scalar => scalar,
500 };
501 if referenced_type != key_type {
502 report_reference(
503 entity.name,
504 field,
505 target.name,
506 Some((target.primary_key, key_type)),
507 );
508
509 return Err(Error::InvalidSchema);
510 }
511 if let FieldType::List { max_items, .. } = field.value {
512 list_fanout += max_items;
513 if list_fanout > 32
514 || reference.index != handle(field.name)
515 || !list_indexes.insert(reference.index)
516 {
517 return Err(Error::InvalidSchema);
518 }
519 name(&mut bytes, target.name)?;
520 name(&mut bytes, field.name)?;
521 continue;
522 }
523 if !RowKey::supports(field.value) {
524 return Err(Error::InvalidSchema);
525 }
526 let index = entity
527 .indexes
528 .iter()
529 .find(|index| {
530 index.id == reference.index
531 && !index.present_only
532 && index.fields.first() == Some(&field.name)
533 })
534 .ok_or(Error::InvalidSchema)?;
535 name(&mut bytes, target.name)?;
536 name(&mut bytes, index.name)?;
537 }
538 }
539 name(&mut bytes, entity.primary_key)?;
540 bytes.extend((entity.indexes.len() as u32).to_le_bytes());
541 let mut index_ids = BTreeSet::new();
542 for index in entity.indexes {
543 if index.id != handle(index.name)
544 || !index_ids.insert(index.id)
545 || index.fields.is_empty()
546 || index.fields.len() > 4
547 {
548 return Err(Error::InvalidSchema);
549 }
550 let mut fields = BTreeSet::new();
551 let has_optional = index.fields.iter().any(|name| {
552 entity
553 .fields
554 .iter()
555 .any(|field| field.name == *name && field.optional)
556 });
557 if (index.unique && has_optional && !index.present_only)
558 || (index.present_only && (!index.unique || !has_optional))
559 {
560 return Err(Error::InvalidSchema);
561 }
562 name(&mut bytes, index.name)?;
563 bytes.push(u8::from(index.unique) | (u8::from(index.present_only) << 1));
564 bytes.extend((index.fields.len() as u32).to_le_bytes());
565 for field in index.fields {
566 if !fields.insert(field) {
567 return Err(Error::InvalidSchema);
568 }
569 if let Some(declared) = entity.field_by_name(field) {
570 if !key::supports(declared.value) {
571 return Err(Error::InvalidSchema);
572 }
573 name(&mut bytes, field)?;
574 } else {
575 let (parent, member) =
576 entity.record_member(field).ok_or(Error::InvalidSchema)?;
577 let parent = &entity.fields[parent];
578 let leaf = member.field();
579 if index.unique || index.fields.len() != 1 {
580 return Err(Error::InvalidSchema);
581 }
582 bytes.extend(u32::MAX.to_le_bytes());
585 name(&mut bytes, parent.name)?;
586 name(&mut bytes, leaf.name)?;
587 }
588 }
589 }
590 if entity
591 .indexes
592 .windows(2)
593 .any(|pair| pair[0].name >= pair[1].name)
594 {
595 return Err(Error::InvalidSchema);
596 }
597 }
598 types.encode(&mut bytes)?;
599 let defaults: Vec<_> = entities
602 .iter()
603 .flat_map(|entity| {
604 entity
605 .fields
606 .iter()
607 .filter_map(move |field| field.default.map(|value| (entity, field, value)))
608 })
609 .collect();
610 if !defaults.is_empty() {
611 bytes.extend(b"ic-db:insert-defaults:v1\0");
612 bytes.extend((defaults.len() as u32).to_le_bytes());
613 for (entity, field, value) in defaults {
614 if field.name == entity.primary_key {
615 return Err(Error::InvalidSchema);
616 }
617 name(&mut bytes, entity.name)?;
618 name(&mut bytes, field.name)?;
619 let encoded = value.encode(field.value)?;
620 bytes.extend((encoded.len() as u32).to_le_bytes());
621 bytes.extend(encoded);
622 }
623 }
624 let mut policies = Vec::new();
625 for entity in &entities {
626 let mut seen = [false; 2];
627 for field in entity.fields {
628 if let Some(managed) = field.managed {
629 if crate::key::operand_type(field.value) != FieldType::Timestamp
630 || field.optional
631 || field.default.is_some()
632 || field.reference.is_some()
633 || field.name == entity.primary_key
634 || seen[managed.slot()]
635 {
636 return Err(Error::InvalidSchema);
637 }
638 seen[managed.slot()] = true;
639 policies.push((entity.name, field.name, managed));
640 }
641 }
642 }
643 if !policies.is_empty() {
644 bytes.extend(b"ic-db:managed-times:v1\0");
645 bytes.extend((policies.len() as u32).to_le_bytes());
646 for (entity, field, managed) in policies {
647 name(&mut bytes, entity)?;
648 name(&mut bytes, field)?;
649 bytes.push(managed.slot() as u8 + 1);
650 }
651 }
652 let mut hash = Sha256::new();
653 hash.update(b"ic-db:compiled-schema:v1\0");
654 hash.update(bytes);
655
656 Ok(Self {
657 metadata: Arc::new(SchemaMetadata { entities, types }),
658 fingerprint: hash.finalize().into(),
659 })
660 }
661
662 #[must_use]
664 pub const fn fingerprint(&self) -> [u8; 32] {
665 self.fingerprint
666 }
667
668 #[must_use]
670 pub fn entities(&self) -> &[&'static EntitySchema] {
671 &self.metadata.entities
672 }
673
674 pub fn describe(&self, selected: Option<&str>) -> Result<SchemaDescription<'_>, Error> {
681 let (entities, types) = if let Some(name) = selected {
682 let position = self
683 .entities()
684 .binary_search_by_key(&name, |entity| entity.name)
685 .map_err(|_| Error::UnknownEntity)?;
686 let entity = self.entities()[position];
687 let mut reachable = TypeGraph::default();
688 for field in entity.fields {
689 reachable.include(field.value)?;
690 }
691 if !self.metadata.types.contains(&reachable) {
692 return Err(Error::InvalidSchema);
693 }
694 (
695 &self.entities()[position..=position],
696 reachable.definitions().collect(),
697 )
698 } else {
699 (self.entities(), self.types().collect())
700 };
701 Ok(SchemaDescription {
702 fingerprint: self.fingerprint(),
703 entities,
704 types,
705 })
706 }
707
708 pub(crate) fn entity_by_id(&self, id: u32) -> Option<&'static EntitySchema> {
709 self.entities()
710 .iter()
711 .copied()
712 .find(|entity| entity.id == id)
713 }
714
715 pub(crate) fn entity_by_name(&self, name: &str) -> Option<&'static EntitySchema> {
716 self.entities()
717 .binary_search_by_key(&name, |entity| entity.name)
718 .ok()
719 .map(|position| self.entities()[position])
720 }
721
722 pub fn types(&self) -> impl Iterator<Item = &'static crate::TypeSchema> + '_ {
724 self.metadata.types.definitions()
725 }
726
727 pub(crate) fn admits(&self, proposed: &EntitySchema) -> Result<&'static EntitySchema, Error> {
731 let current = self.entity_by_id(proposed.id).ok_or(Error::UnknownEntity)?;
732 if std::ptr::eq(current, proposed) {
734 return Ok(current);
735 }
736 if current.max_row_bytes != proposed.max_row_bytes
737 || current.name != proposed.name
738 || current.fields != proposed.fields
739 || current.primary_key != proposed.primary_key
740 || current.indexes != proposed.indexes
741 {
742 return Err(Error::UnknownEntity);
743 }
744 let mut proposed_types = TypeGraph::default();
745 for field in proposed.fields {
746 proposed_types
747 .include(field.value)
748 .map_err(|_| Error::UnknownEntity)?;
749 }
750 if !self.metadata.types.contains(&proposed_types) {
751 return Err(Error::UnknownEntity);
752 }
753
754 Ok(current)
755 }
756}
757
758pub(crate) fn name(bytes: &mut Vec<u8>, value: &str) -> Result<(), Error> {
759 if value.is_empty() || value.len() > 64 {
760 return Err(Error::InvalidSchema);
761 }
762 bytes.extend((value.len() as u32).to_le_bytes());
763 bytes.extend(value.as_bytes());
764
765 Ok(())
766}
767
768pub(crate) fn encode_type(
769 bytes: &mut Vec<u8>,
770 value: FieldType,
771 optional: bool,
772 reference: bool,
773) -> Result<(), Error> {
774 let tag = match value {
775 FieldType::Nat64 => 1,
776 FieldType::Bool => 2,
777 FieldType::Text { .. } => 3,
778 FieldType::Int64 => 4,
779 FieldType::Nat128 => 5,
780 FieldType::Int128 => 6,
781 FieldType::Blob { .. } => 7,
782 FieldType::Nat8 => 8,
783 FieldType::Nat16 => 9,
784 FieldType::Nat32 => 10,
785 FieldType::Int8 => 11,
786 FieldType::Int16 => 12,
787 FieldType::Int32 => 13,
788 FieldType::Principal => 14,
789 FieldType::Named(_) => 15,
790 FieldType::List { .. } => 16,
791 FieldType::U256 => 17,
792 FieldType::Float32 => 18,
793 FieldType::Float64 => 19,
794 FieldType::Subaccount => 20,
795 FieldType::Account => 21,
796 FieldType::Ulid => 22,
797 FieldType::Date => 23,
798 FieldType::Timestamp => 24,
799 FieldType::Duration => 25,
800 FieldType::Decimal { .. } => 26,
801 };
802 bytes.push(tag | if optional { 0x80 } else { 0 } | if reference { 0x40 } else { 0 });
803 match value {
804 FieldType::Decimal { scale } => {
805 if scale > crate::Decimal::MAX_SCALE {
806 return Err(Error::InvalidSchema);
807 }
808 bytes.extend(scale.to_le_bytes());
809 }
810 FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => {
811 if max_bytes > crate::codec::MAX_ROW_BYTES as u32 {
812 return Err(Error::InvalidSchema);
813 }
814 bytes.extend(max_bytes.to_le_bytes());
815 }
816 FieldType::Named(link) => name(bytes, link.name)?,
817 FieldType::List { item, max_items } => {
818 if max_items > crate::named_schema::MAX_COLLECTION_ITEMS as u32
819 || matches!(item, FieldType::List { .. })
820 {
821 return Err(Error::InvalidSchema);
822 }
823 for bound in [
824 max_items,
825 crate::named_schema::MAX_DEPTH as u32,
826 crate::named_schema::MAX_NODES as u32,
827 crate::named_schema::MAX_COLLECTION_ITEMS as u32,
828 ] {
829 bytes.extend(bound.to_le_bytes());
830 }
831 encode_type(bytes, *item, false, false)?;
832 }
833 _ => {}
834 }
835
836 Ok(())
837}