1mod maintenance;
5mod query;
6
7use crate::{
8 __private::RowInfo, Entity, EntitySchema, Error, FieldType, IndexValue, PrimaryKey, Schema,
9 UniqueKey, key, primary::RowKey, store_key::StoreKey,
10};
11use ic_storage::{
12 Memory, RuntimeMemory,
13 adapter::{MapIter, StableBTreeMap},
14};
15pub use maintenance::{
16 CopyStatus, CopyStep, Maintenance, RetiredSource, SchemaCopy, SchemaTransition,
17};
18pub use query::{
19 Aggregate, AggregateJobs, Column, Comparison, GroupCount, GroupCursor, GroupOrder, GroupPage,
20 GroupSummaries, GroupSummary, GroupSummaryPage, GroupValue, JobHandle, JobOutcome, JobStep,
21 Query, QueryCursor, QueryOperand, QueryPage, SelectColumns, SelectedQuery, Selection,
22 SortDirection, SummaryMeasure,
23};
24use std::collections::{BTreeMap, BTreeSet};
25
26const MANIFEST: &[u8] = b"ICDBMF02";
27const MAX_BATCH: usize = 32;
28const MAX_BATCH_BYTES: usize = 128 * 1024;
29type Map<M> = StableBTreeMap<StoreKey, Vec<u8>, M>;
30
31#[inline(never)]
34fn next_primary<M: Memory>(
35 entries: &mut MapIter<'_, StoreKey, Vec<u8>, M>,
36 prefix: &[u8],
37 key_type: FieldType,
38) -> Result<Option<(RowKey, Vec<u8>)>, Error> {
39 let Some(entry) = entries.next() else {
40 return Ok(None);
41 };
42 if !entry.key().starts_with(prefix) {
43 return Ok(None);
44 }
45 let id = RowKey::decode(&entry.key()[ENTITY_PREFIX_BYTES..], key_type)?;
46
47 Ok(Some((id, entry.value())))
48}
49
50fn decode_primary<E: Entity>(bytes: &[u8], key: E::Key) -> Result<E, Error> {
51 let row = E::decode(bytes)?;
52 if row.key() != key {
53 return Err(Error::Corrupt);
54 }
55
56 Ok(row)
57}
58
59fn read_index_owner<M: Memory>(
62 map: &Map<M>,
63 entity: u32,
64 key_type: FieldType,
65 encoded: &[u8],
66) -> Result<(RowKey, Vec<u8>), Error> {
67 let owner = RowKey::decode(encoded, key_type)?;
68 let key = prefix(2, entity, encoded);
69 let row = map.get(&StoreKey::new(key)?).ok_or(Error::Corrupt)?;
70
71 Ok((owner, row))
72}
73
74#[inline(never)]
76fn next_index<M: Memory>(
77 map: &Map<M>,
78 entries: &mut MapIter<'_, StoreKey, Vec<u8>, M>,
79 prefix: &[u8],
80 entity: u32,
81 key_type: FieldType,
82) -> Result<Option<(StoreKey, RowKey, Vec<u8>)>, Error> {
83 let Some(entry) = entries.next() else {
84 return Ok(None);
85 };
86 if !entry.key().starts_with(prefix) {
87 return Ok(None);
88 }
89 let (id, bytes) = read_index_owner(map, entity, key_type, &entry.value())?;
90
91 Ok(Some((entry.key().clone(), id, bytes)))
92}
93
94#[inline(never)]
95fn index_prefix_key(
96 entity: &EntitySchema,
97 index: &str,
98 values: &[IndexValue<'_>],
99 limit: usize,
100) -> Result<StoreKey, Error> {
101 let index = entity.index_by_name(index).ok_or(Error::InvalidSchema)?;
102 if values.is_empty() || !(1..=32).contains(&limit) {
103 return Err(Error::Limit);
104 }
105
106 StoreKey::new(admit_index_prefix(entity, index, values)?)
107}
108
109fn collect_references(
112 entity: &EntitySchema,
113 info: &RowInfo,
114 required: &mut BTreeSet<(u32, RowKey)>,
115) -> Result<(), Error> {
116 for field in entity.fields {
117 if let Some(reference) = field.reference {
118 if matches!(field.value, FieldType::List { .. }) {
119 required.extend(
120 info.list_links
121 .iter()
122 .filter(|(index, _)| *index == reference.index)
123 .map(|(_, key)| (reference.entity, *key)),
124 );
125 continue;
126 }
127 let position = entity
128 .indexes
129 .iter()
130 .position(|index| index.id == reference.index)
131 .ok_or(Error::Corrupt)?;
132 let mut bytes = info
133 .indexes
134 .get(position)
135 .and_then(Option::as_ref)
136 .map(Vec::as_slice)
137 .ok_or(Error::Corrupt)?;
138 if field.optional {
139 match bytes.split_first() {
141 Some((0, _)) => continue,
142 Some((1, rest)) => bytes = rest,
143 _ => return Err(Error::Corrupt),
144 }
145 }
146 let mut remaining = bytes;
147 key::consume(&mut remaining, field.value)?;
148 let target = RowKey::decode(&bytes[..bytes.len() - remaining.len()], field.value)?;
149 required.insert((reference.entity, target));
150 }
151 }
152
153 Ok(())
154}
155
156fn validate_reference_target<M: Memory>(
157 map: &Map<M>,
158 schema: &Schema,
159 entity: u32,
160 id: RowKey,
161) -> Result<(), Error> {
162 let bytes = map
163 .get(&row_key(entity, id))
164 .ok_or(Error::ReferenceViolation)?;
165 let entity = schema.entity_by_id(entity).ok_or(Error::Corrupt)?;
166 if entity.inspect_row(&bytes)?.key != id {
167 return Err(Error::Corrupt);
168 }
169
170 Ok(())
171}
172
173fn manifest_key() -> StoreKey {
174 StoreKey::new(vec![0]).expect("manifest key fits")
175}
176
177fn live_manifest(schema: [u8; 32], incarnation: [u8; 16]) -> Vec<u8> {
178 let mut bytes = MANIFEST.to_vec();
179 bytes.extend(schema);
180 bytes.extend(incarnation);
181
182 bytes
183}
184
185#[derive(Default)]
187pub struct Batch {
188 operation_time: Option<crate::Timestamp>,
189 mutations: Vec<Mutation>,
190 bytes: usize,
191}
192struct Mutation {
193 entity: &'static EntitySchema,
194 key: RowKey,
195 kind: Kind,
196}
197struct ReturningRow<'a> {
198 entity: u32,
199 key: RowKey,
200 decode: &'a mut dyn FnMut(&[u8]) -> Result<(), Error>,
201}
202
203enum Kind {
204 Insert(Vec<u8>, RowInfo),
205 CopyInsert(Vec<u8>, RowInfo, [Option<crate::Timestamp>; 2]),
207 Replace(Vec<u8>, RowInfo),
208 Delete,
209}
210
211impl Batch {
212 #[must_use]
214 pub fn new() -> Self {
215 Self::default()
216 }
217
218 #[cfg(feature = "test-support")]
220 #[must_use]
221 pub fn at_for_test(time: crate::Timestamp) -> Self {
222 Self {
223 operation_time: Some(time),
224 ..Self::default()
225 }
226 }
227
228 pub fn insert<E: Entity>(&mut self, row: &E) -> Result<(), Error> {
232 if E::SCHEMA.has_managed() {
233 return Err(Error::ManagedField);
234 }
235
236 self.put(row, Kind::Insert)
237 }
238
239 pub fn insert_input<I: crate::InsertInput>(&mut self, input: I) -> Result<I::Entity, Error> {
248 let time = *self
249 .operation_time
250 .get_or_insert_with(crate::Timestamp::now);
251 let row = input.__into_entity(Some(time))?;
252 self.put(&row, Kind::Insert)?;
253
254 Ok(row)
255 }
256
257 pub fn replace<E: Entity>(&mut self, row: &E) -> Result<(), Error> {
263 if E::SCHEMA.has_managed() {
264 self.operation_time
265 .get_or_insert_with(crate::Timestamp::now);
266 }
267 self.put(row, Kind::Replace)
268 }
269
270 pub fn delete<E: Entity>(&mut self, key: impl Into<crate::Id<E>>) -> Result<(), Error> {
274 self.push(
275 Mutation {
276 entity: E::SCHEMA,
277 key: key.into().key().into_row_key(),
278 kind: Kind::Delete,
279 },
280 0,
281 )
282 }
283
284 fn put<E: Entity>(
285 &mut self,
286 row: &E,
287 kind: impl FnOnce(Vec<u8>, RowInfo) -> Kind,
288 ) -> Result<(), Error> {
289 let bytes = row.encode()?;
290 if bytes.len() > E::SCHEMA.max_row_bytes {
291 return Err(Error::Limit);
292 }
293 let info = row.__row_info();
296 let key = info.key;
297 let len = bytes.len();
298 let kind = kind(bytes, info);
299 self.push(
300 Mutation {
301 entity: E::SCHEMA,
302 key,
303 kind,
304 },
305 len,
306 )
307 }
308
309 fn push(&mut self, mutation: Mutation, bytes: usize) -> Result<(), Error> {
310 if self.mutations.len() == MAX_BATCH || bytes > MAX_BATCH_BYTES - self.bytes {
311 return Err(Error::Limit);
312 }
313 self.bytes += bytes;
314 self.mutations.push(mutation);
315
316 Ok(())
317 }
318}
319
320pub struct Page<E: Entity> {
322 pub rows: Vec<E>,
324 pub next_after: Option<E::Key>,
326}
327
328pub struct Database<M: Memory> {
330 map: Map<M>,
331 schema: Schema,
332 incarnation: [u8; 16],
333}
334
335impl<M: Memory> Database<M> {
336 pub fn create(
342 memory: RuntimeMemory<M>,
343 schema: Schema,
344 incarnation: [u8; 16],
345 ) -> Result<Self, Error> {
346 if incarnation == [0; 16] {
347 return Err(Error::InvalidSchema);
348 }
349 if memory.size() != 0 {
350 return Err(Error::Exists);
351 }
352 let mut map = Map::create(memory);
353 map.insert(
354 manifest_key(),
355 live_manifest(schema.fingerprint, incarnation),
356 );
357 for entity in schema.entities() {
358 map.insert(entity_state_key(entity.id), EntityState::default().encode());
359 }
360
361 Ok(Self {
362 map,
363 schema,
364 incarnation,
365 })
366 }
367
368 pub fn open(memory: RuntimeMemory<M>, schema: Schema) -> Result<Self, Error> {
376 if memory.size() == 0 {
377 return Err(Error::Corrupt);
378 }
379 let map = Map::load(memory);
380 let manifest = map.get(&manifest_key()).ok_or(Error::Corrupt)?;
381 if maintenance::admits_gate(&manifest)? {
382 return Err(Error::Maintenance);
383 }
384 if manifest.len() != 56 {
385 return Err(Error::Corrupt);
386 }
387 if &manifest[..8] != MANIFEST || manifest[8..40] != schema.fingerprint {
388 return Err(Error::IncompatibleSchema);
389 }
390 let incarnation = manifest[40..].try_into().map_err(|_| Error::Corrupt)?;
391 if incarnation == [0; 16] {
392 return Err(Error::Corrupt);
393 }
394
395 Ok(Self {
396 map,
397 schema,
398 incarnation,
399 })
400 }
401
402 #[must_use]
404 pub const fn schema(&self) -> &Schema {
405 &self.schema
406 }
407
408 #[must_use]
410 pub const fn incarnation(&self) -> [u8; 16] {
411 self.incarnation
412 }
413
414 pub fn revision<E: Entity>(&self) -> Result<u64, Error> {
418 let entity = self.schema.admits(E::SCHEMA)?;
419
420 read_revision(&self.map, entity.id)
421 }
422
423 pub fn cardinality<E: Entity>(&self) -> Result<u64, Error> {
431 let entity = self.schema.admits(E::SCHEMA)?;
432
433 Ok(read_entity_state(&self.map, entity.id)?.count)
434 }
435
436 pub fn cardinality_by_name(&self, name: &str) -> Result<u64, Error> {
443 let entity = self
444 .schema
445 .entity_by_name(name)
446 .ok_or(Error::UnknownEntity)?;
447
448 Ok(read_entity_state(&self.map, entity.id)?.count)
449 }
450
451 fn revision_by_id(&self, entity: u32) -> Result<u64, Error> {
452 if self.schema.entity_by_id(entity).is_none() {
453 return Err(Error::UnknownEntity);
454 }
455
456 read_revision(&self.map, entity)
457 }
458
459 #[inline]
463 pub fn get<E: Entity>(&self, key: impl Into<crate::Id<E>>) -> Result<Option<E>, Error> {
464 let entity = self.schema.admits(E::SCHEMA)?;
465
466 self.get_typed::<E>(entity, key.into().key())
467 }
468
469 pub fn get_unique<K: UniqueKey>(&self, key: &K) -> Result<Option<K::Entity>, Error> {
473 let components = key.components();
474 let values = components.as_ref();
475 if !K::Entity::SCHEMA
476 .index_by_name(K::INDEX)
477 .is_some_and(|index| index.is_unique_lookup(values.len()))
478 {
479 return Err(Error::InvalidQuery);
480 }
481
482 self.query::<K::Entity>()
483 .using_index(K::INDEX, values)
484 .work_limit(1)
485 .try_one()
486 }
487
488 pub fn get_many<E: Entity>(
500 &self,
501 keys: &[impl Copy + Into<crate::Id<E>>],
502 ) -> Result<Vec<Option<E>>, Error> {
503 if keys.len() > 32 {
504 return Err(Error::Limit);
505 }
506 let entity = self.schema.admits(E::SCHEMA)?;
507
508 let keys: Vec<_> = keys.iter().map(|&key| key.into().key()).collect();
509 self.get_many_typed::<E>(entity, &keys)
510 }
511
512 #[inline(never)]
514 fn get_many_typed<E: Entity>(
515 &self,
516 entity: &EntitySchema,
517 keys: &[E::Key],
518 ) -> Result<Vec<Option<E>>, Error> {
519 let mut rows: Vec<_> = (0..keys.len()).map(|_| None).collect();
520 let mut handled = 0_u32;
521 for (i, &key) in keys.iter().enumerate() {
522 if handled & (1 << i) != 0 {
523 continue;
524 }
525 let bytes = self.map.get(&row_key(entity.id, key.into_row_key()));
526 for (j, &other) in keys.iter().enumerate().skip(i) {
527 if other == key {
528 handled |= 1 << j;
529 if let Some(bytes) = &bytes {
530 rows[j] = Some(decode_primary::<E>(bytes, key)?);
531 }
532 }
533 }
534 }
535
536 Ok(rows)
537 }
538
539 #[inline(never)]
542 fn get_typed<E: Entity>(&self, entity: &EntitySchema, key: E::Key) -> Result<Option<E>, Error> {
543 self.map
544 .get(&row_key(entity.id, key.into_row_key()))
545 .map(|bytes| decode_primary::<E>(&bytes, key))
546 .transpose()
547 }
548
549 #[inline]
555 pub fn page<E: Entity>(&self, after: Option<E::Key>, limit: usize) -> Result<Page<E>, Error> {
556 let entity = self.schema.admits(E::SCHEMA)?;
557
558 self.page_typed::<E>(entity, after, limit)
559 }
560
561 #[inline(never)]
562 fn page_typed<E: Entity>(
563 &self,
564 entity: &EntitySchema,
565 after: Option<E::Key>,
566 limit: usize,
567 ) -> Result<Page<E>, Error> {
568 if !(1..=32).contains(&limit) {
569 return Err(Error::Limit);
570 }
571 let prefix = prefix(2, entity.id, &[]);
572 let start = after.map_or_else(
573 || StoreKey::new(prefix.clone()).expect("row namespace fits"),
574 |key| row_key(entity.id, key.into_row_key()),
575 );
576 let lower = if after.is_some() {
577 std::ops::Bound::Excluded(start)
578 } else {
579 std::ops::Bound::Included(start)
580 };
581 let mut entries = self.map.range((lower, std::ops::Bound::Unbounded));
582 let key_type = entity.key_type()?;
583 let mut rows = Vec::new();
584 let mut last = None;
585 for _ in 0..limit {
586 let Some((id, bytes)) = next_primary(&mut entries, &prefix, key_type)? else {
587 break;
588 };
589 let id = E::Key::from_row_key(id)?;
590 rows.push(decode_primary::<E>(&bytes, id)?);
591 last = Some(id);
592 }
593
594 let more = rows.len() == limit
596 && entries
597 .next()
598 .is_some_and(|entry| entry.key().starts_with(&prefix));
599 Ok(Page {
600 next_after: if more { last } else { None },
601 rows,
602 })
603 }
604
605 #[inline]
613 pub fn index_prefix<E: Entity>(
614 &self,
615 index: &str,
616 values: &[IndexValue<'_>],
617 limit: usize,
618 ) -> Result<Vec<E>, Error> {
619 let entity = self.schema.admits(E::SCHEMA)?;
620
621 self.index_prefix_typed::<E>(entity, index, values, limit)
622 }
623
624 #[inline(never)]
625 fn index_prefix_typed<E: Entity>(
626 &self,
627 entity: &EntitySchema,
628 index: &str,
629 values: &[IndexValue<'_>],
630 limit: usize,
631 ) -> Result<Vec<E>, Error> {
632 let prefix = index_prefix_key(entity, index, values, limit)?;
633 let mut rows = Vec::new();
634 let mut entries = self.map.range(prefix.clone()..);
635 let key_type = entity.key_type()?;
636 for _ in 0..limit {
637 let Some((key, id, bytes)) =
638 next_index(&self.map, &mut entries, &prefix, entity.id, key_type)?
639 else {
640 break;
641 };
642 let row = E::decode(&bytes)?;
643 validate_index_entry(entity, &row.__row_info(), id, &key)?;
644 rows.push(row);
645 }
646
647 Ok(rows)
648 }
649
650 pub fn commit(&mut self, batch: Batch) -> Result<(), Error> {
659 observe!(commit, { self.commit_batch(batch, None, None).map(|_| ()) })
660 }
661
662 pub fn commit_returning<E: Entity>(
670 &mut self,
671 batch: Batch,
672 key: impl Into<crate::Id<E>>,
673 ) -> Result<E, Error> {
674 observe!(commit, {
675 self.schema.admits(E::SCHEMA)?;
676 let mut row = None;
677 let selected = ReturningRow {
678 entity: E::SCHEMA.id,
679 key: key.into().key().into_row_key(),
680 decode: &mut |bytes| {
681 row = Some(E::decode(bytes)?);
682 Ok(())
683 },
684 };
685 self.commit_batch(batch, Some(selected), None)?;
686 Ok(row.expect("commit validated the selected row before publication"))
687 })
688 }
689
690 pub(crate) fn insert_if_absent<K: UniqueKey>(
691 &mut self,
692 input: impl crate::InsertInput<Entity = K::Entity>,
693 ) -> Result<crate::InsertOutcome<K::Entity>, Error> {
694 let entity = K::Entity::SCHEMA;
695 let index = entity
696 .index_by_name(K::INDEX)
697 .filter(|i| i.unique)
698 .ok_or(Error::InvalidQuery)?;
699 let mut batch = Batch::new();
700 let row = batch.insert_input(input)?;
701 let prefix = index_prefix(entity.id, index.id);
702 let applied = observe!(commit, {
703 self.commit_batch(batch, None, Some((entity, &prefix)))
704 })?;
705 Ok(if applied {
706 crate::InsertOutcome::Inserted(row)
707 } else {
708 crate::InsertOutcome::AlreadyPresent
709 })
710 }
711
712 fn commit_batch(
714 &mut self,
715 batch: Batch,
716 mut returning: Option<ReturningRow<'_>>,
717 conflict_target: Option<(&EntitySchema, &[u8])>,
718 ) -> Result<bool, Error> {
719 let mut targets = BTreeSet::new();
720 let mut removes = BTreeSet::new();
721 let mut writes = BTreeMap::new();
722 let mut unique = BTreeSet::new();
723 let mut entities = BTreeMap::new();
726 let mut required = BTreeSet::new();
727 let mut deleted = Vec::new();
728 for mut mutation in batch.mutations {
729 self.schema.admits(mutation.entity)?;
730 let key = row_key(mutation.entity.id, mutation.key);
731 if !targets.insert(key.clone()) {
732 return Err(Error::DuplicateTarget);
733 }
734 let old = self.map.get(&key);
735 match (&mutation.kind, &old) {
736 (Kind::Insert(..) | Kind::CopyInsert(..), Some(_)) => return Err(Error::Exists),
737 (Kind::Replace(..), None) => return Err(Error::Missing),
738 (Kind::Delete, None) => continue,
739 _ => {}
740 }
741 if mutation.entity.has_managed() {
742 match &mut mutation.kind {
743 Kind::Insert(bytes, _) => crate::managed::validate_insert(
744 mutation.entity,
745 bytes,
746 batch.operation_time.ok_or(Error::MissingOperationTime)?,
747 )?,
748 Kind::Replace(bytes, info) => {
749 if crate::managed::replace(
750 mutation.entity,
751 bytes,
752 old.as_deref().ok_or(Error::Missing)?,
753 batch.operation_time.ok_or(Error::MissingOperationTime)?,
754 )? {
755 *info = mutation.entity.inspect_row(bytes)?;
756 }
757 }
758 Kind::CopyInsert(bytes, _, expected) => {
759 if crate::managed::values(mutation.entity, bytes)? != *expected {
760 return Err(Error::ManagedField);
761 }
762 }
763 Kind::Delete => {}
764 }
765 }
766 if let Kind::Insert(bytes, _) | Kind::Replace(bytes, _) = &mutation.kind
767 && let Some(selected) = returning
768 .take_if(|row| row.entity == mutation.entity.id && row.key == mutation.key)
769 {
770 (selected.decode)(bytes)?;
771 }
772 let mut after_indexes = match &mutation.kind {
775 Kind::Insert(_, info) | Kind::CopyInsert(_, info, _) | Kind::Replace(_, info) => {
776 index_entries(mutation.entity, info)?
777 }
778 Kind::Delete => Vec::new(),
779 };
780 let (_, changed, delta) = match entities.entry(mutation.entity.id) {
781 std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
782 std::collections::btree_map::Entry::Vacant(entry) => entry.insert((
783 read_entity_state(&self.map, mutation.entity.id)?,
784 false,
785 0_i64,
786 )),
787 };
788 if let (Kind::Replace(bytes, _), Some(old)) = (&mutation.kind, &old)
789 && bytes == old
790 {
791 continue;
792 }
793 if let Some(old) = old {
794 let info = mutation.entity.inspect_row(&old)?;
795 if info.key != mutation.key {
796 return Err(Error::Corrupt);
797 }
798 let owner = info.key.encode();
799 for (key, _) in index_entries(mutation.entity, &info)? {
800 if self.map.get(&key).as_deref() != Some(owner.as_slice()) {
801 return Err(Error::Corrupt);
802 }
803
804 if let Some(position) =
807 after_indexes.iter().position(|(after, _)| *after == key)
808 {
809 after_indexes.remove(position);
810 } else {
811 removes.insert(key);
812 }
813 }
814 }
815 *changed = true;
816 *delta += match &mutation.kind {
817 Kind::Insert(..) | Kind::CopyInsert(..) => 1,
818 Kind::Delete => -1,
819 Kind::Replace(..) => 0,
820 };
821 let copy_insert = matches!(&mutation.kind, Kind::CopyInsert(..));
824
825 match mutation.kind {
826 Kind::Delete => {
827 deleted.push((mutation.entity.id, mutation.key));
828 removes.insert(key);
829 }
830 Kind::Insert(bytes, info)
831 | Kind::CopyInsert(bytes, info, _)
832 | Kind::Replace(bytes, info) => {
833 writes.insert(key, bytes);
834 for (key, is_unique) in after_indexes {
835 if is_unique && !unique.insert(key.clone()) {
836 return Err(Error::UniqueViolation);
837 }
838 writes.insert(key, info.key.encode());
839 }
840 if !copy_insert {
841 collect_references(mutation.entity, &info, &mut required)?;
842 }
843 }
844 }
845 }
846 if returning.is_some() {
847 return Err(Error::Missing);
848 }
849 let mut skip_insert = false;
851 for key in unique {
852 if let Some((entity, _)) = conflict_target.filter(|(_, prefix)| key.starts_with(prefix))
853 {
854 if let Some(encoded) = self.map.get(&key) {
855 let (owner, bytes) =
856 read_index_owner(&self.map, entity.id, entity.key_type()?, &encoded)?;
857 validate_index_entry(entity, &entity.inspect_row(&bytes)?, owner, &key)?;
858 skip_insert = true;
859 }
860 continue;
861 }
862 if self.map.contains_key(&key) && !removes.contains(&key) {
863 return Err(Error::UniqueViolation);
864 }
865 }
866 if skip_insert {
867 self.validate_references(&required, &deleted, &removes, &BTreeMap::new())?;
869 return Ok(false);
870 }
871 self.validate_references(&required, &deleted, &removes, &writes)?;
872 for (entity, (mut state, changed, delta)) in entities {
873 if changed {
874 state.revision = state.revision.checked_add(1).ok_or(Error::Limit)?;
875 state.count = if delta >= 0 {
876 state.count.checked_add(delta as u64).ok_or(Error::Limit)?
877 } else {
878 state
879 .count
880 .checked_sub((-delta) as u64)
881 .ok_or(Error::Corrupt)?
882 };
883 writes.insert(entity_state_key(entity), state.encode());
884 }
885 }
886 for key in removes {
888 self.map.remove(&key);
889 }
890 for (key, value) in writes {
891 self.map.insert(key, value);
892 }
893
894 Ok(true)
895 }
896
897 fn validate_references(
900 &self,
901 required: &BTreeSet<(u32, RowKey)>,
902 deleted: &[(u32, RowKey)],
903 removes: &BTreeSet<StoreKey>,
904 writes: &BTreeMap<StoreKey, Vec<u8>>,
905 ) -> Result<(), Error> {
906 for &(entity, id) in required {
907 let key = row_key(entity, id);
908 if writes.contains_key(&key) {
909 continue;
910 } if removes.contains(&key) {
912 return Err(Error::ReferenceViolation);
913 }
914 validate_reference_target(&self.map, &self.schema, entity, id)?;
915 }
916 for &(target, id) in deleted {
917 for entity in self.schema.entities() {
918 for field in entity.fields {
919 let Some(reference) = field.reference.filter(|value| value.entity == target)
920 else {
921 continue;
922 };
923 let prefix = if matches!(field.value, FieldType::List { .. }) {
924 list_target_prefix(entity.id, reference.index, id)
925 } else {
926 let mut prefix = index_prefix(entity.id, reference.index);
927 id.index_value()
928 .append_component(field.optional, &mut prefix);
929 prefix
930 };
931 let prefix = StoreKey::new(prefix)?;
932 for (position, entry) in self
935 .map
936 .range(prefix.clone()..)
937 .take_while(|entry| entry.key().starts_with(&prefix))
938 .take(MAX_BATCH + 1)
939 .enumerate()
940 {
941 if removes.contains(entry.key()) {
942 if position == MAX_BATCH {
943 return Err(Error::Corrupt);
944 }
945 continue;
946 }
947 let (owner, bytes) = read_index_owner(
948 &self.map,
949 entity.id,
950 entity.key_type()?,
951 &entry.value(),
952 )?;
953 let info = entity.inspect_row(&bytes)?;
954 validate_index_entry(entity, &info, owner, entry.key())?;
955
956 return Err(Error::ReferenceViolation);
957 }
958 }
959 }
960 }
961
962 Ok(())
963 }
964}
965
966const ENTITY_PREFIX_BYTES: usize = 1 + size_of::<u32>();
968const INDEX_PREFIX_BYTES: usize = ENTITY_PREFIX_BYTES + size_of::<u32>();
969
970fn prefix(tag: u8, entity: u32, suffix: &[u8]) -> Vec<u8> {
971 let mut key = Vec::with_capacity(ENTITY_PREFIX_BYTES + suffix.len());
972 key.push(tag);
973 key.extend_from_slice(&entity.to_be_bytes());
974 key.extend_from_slice(suffix);
975
976 key
977}
978
979fn entity_state_key(entity: u32) -> StoreKey {
980 StoreKey::new(prefix(1, entity, &[])).expect("entity state key fits")
981}
982
983fn read_revision<M: Memory>(map: &Map<M>, entity: u32) -> Result<u64, Error> {
984 Ok(read_entity_state(map, entity)?.revision)
985}
986
987#[derive(Default)]
989struct EntityState {
990 revision: u64,
991 count: u64,
992}
993impl EntityState {
994 fn encode(&self) -> Vec<u8> {
995 let mut bytes = self.revision.to_le_bytes().to_vec();
996 bytes.extend(self.count.to_le_bytes());
997
998 bytes
999 }
1000}
1001fn read_entity_state<M: Memory>(map: &Map<M>, entity: u32) -> Result<EntityState, Error> {
1002 let bytes = map.get(&entity_state_key(entity)).ok_or(Error::Corrupt)?;
1003 let (revision, count) = bytes.split_first_chunk::<8>().ok_or(Error::Corrupt)?;
1004 let revision = u64::from_le_bytes(*revision);
1005 let count = u64::from_le_bytes(count.try_into().map_err(|_| Error::Corrupt)?);
1006 if revision == 0 && count != 0 {
1008 return Err(Error::Corrupt);
1009 }
1010
1011 Ok(EntityState { revision, count })
1012}
1013
1014fn row_key(entity: u32, id: RowKey) -> StoreKey {
1015 let mut key = prefix(2, entity, &[]);
1016 id.append_to(&mut key);
1017
1018 StoreKey::new(key).expect("bounded primary key fits")
1019}
1020
1021fn index_prefix(entity: u32, index: u32) -> Vec<u8> {
1022 prefix(3, entity, &index.to_be_bytes())
1023}
1024fn list_target_prefix(entity: u32, field: u32, target: RowKey) -> Vec<u8> {
1026 let mut key = prefix(4, entity, &field.to_be_bytes());
1027 target.append_to(&mut key);
1028 key
1029}
1030
1031fn admit_index_prefix(
1033 entity: &EntitySchema,
1034 index: &crate::IndexSchema,
1035 values: &[IndexValue<'_>],
1036) -> Result<Vec<u8>, Error> {
1037 if values.len() > index.fields.len() {
1038 return Err(Error::Limit);
1039 }
1040 let mut prefix = index_prefix(entity.id, index.id);
1041 for (value, name) in values.iter().zip(index.fields) {
1042 let field = entity.index_field(name).ok_or(Error::InvalidSchema)?;
1043 value.admit(field.value, field.optional)?;
1044 if index.present_only && *value == IndexValue::Absent {
1045 return Err(Error::InvalidOperand);
1046 }
1047 value.append_component(field.optional, &mut prefix);
1048 if prefix.len() > crate::MAX_INDEX_KEY_BYTES {
1049 return Err(Error::Limit);
1050 }
1051 }
1052 let mut completion = if index.unique {
1053 0
1054 } else {
1055 key::minimum_bytes(entity.key_type()?)?
1056 };
1057 for name in &index.fields[values.len()..] {
1058 let field = entity.index_field(name).ok_or(Error::InvalidSchema)?;
1059 completion += if field.optional && !index.present_only {
1060 1
1061 } else {
1062 key::minimum_bytes(field.value)? + usize::from(field.optional)
1063 };
1064 }
1065 if prefix.len() + completion > crate::MAX_INDEX_KEY_BYTES {
1066 return Err(Error::Limit);
1067 }
1068
1069 Ok(prefix)
1070}
1071fn visit_index_components(
1073 entity: &EntitySchema,
1074 info: &RowInfo,
1075 mut visit: impl FnMut(&crate::IndexSchema, &[u8]) -> Result<(), Error>,
1076) -> Result<(), Error> {
1077 if info.indexes.len() != entity.indexes.len() {
1078 return Err(Error::Corrupt);
1079 }
1080 for (index, values) in entity.indexes.iter().zip(&info.indexes) {
1081 let Some(values) = values else {
1082 if index.present_only {
1083 continue;
1084 }
1085
1086 return Err(Error::Corrupt);
1087 };
1088 let mut remaining = values.as_slice();
1089 for name in index.fields {
1090 let field = entity.index_field(name).ok_or(Error::Corrupt)?;
1091 key::consume_component(&mut remaining, field, index.present_only, Error::Corrupt)?;
1092 }
1093 if !remaining.is_empty() {
1094 return Err(Error::Corrupt);
1095 }
1096 visit(index, values)?;
1097 }
1098
1099 Ok(())
1100}
1101
1102fn index_entries(entity: &EntitySchema, info: &RowInfo) -> Result<Vec<(StoreKey, bool)>, Error> {
1103 let mut entries = Vec::new();
1104 visit_index_components(entity, info, |index, values| {
1105 let mut key = index_prefix(entity.id, index.id);
1106 key.extend_from_slice(values);
1107 if !index.unique {
1108 info.key.append_to(&mut key);
1109 }
1110 entries.push((StoreKey::new(key)?, index.unique));
1111
1112 Ok(())
1113 })?;
1114
1115 let mut links = BTreeSet::new();
1116 for &(field, target) in &info.list_links {
1117 if links.insert((field, target)) {
1118 let mut key = list_target_prefix(entity.id, field, target);
1119 info.key.append_to(&mut key);
1120 entries.push((StoreKey::new(key)?, false));
1121 }
1122 }
1123 Ok(entries)
1124}
1125
1126fn validate_index_entry(
1129 entity: &EntitySchema,
1130 info: &RowInfo,
1131 owner: RowKey,
1132 key: &[u8],
1133) -> Result<(), Error> {
1134 if info.key != owner {
1135 return Err(Error::Corrupt);
1136 }
1137 if key.first() == Some(&4) {
1138 return index_entries(entity, info)?
1139 .iter()
1140 .any(|(entry, _)| entry.as_ref() == key)
1141 .then_some(())
1142 .ok_or(Error::Corrupt);
1143 }
1144 let (header, payload) = key
1145 .split_at_checked(INDEX_PREFIX_BYTES)
1146 .ok_or(Error::Corrupt)?;
1147 if header[0] != 3 || header[1..ENTITY_PREFIX_BYTES] != entity.id.to_be_bytes() {
1148 return Err(Error::Corrupt);
1149 }
1150 let mut matches = false;
1151 let owner = owner.encode();
1152 visit_index_components(entity, info, |index, values| {
1153 let suffix = if index.unique {
1154 &[][..]
1155 } else {
1156 owner.as_slice()
1157 };
1158 if INDEX_PREFIX_BYTES + values.len() + suffix.len() > crate::MAX_INDEX_KEY_BYTES {
1159 return Err(Error::Limit);
1160 }
1161 if header[ENTITY_PREFIX_BYTES..] == index.id.to_be_bytes() {
1162 matches = payload.strip_prefix(values) == Some(suffix);
1163 }
1164
1165 Ok(())
1166 })?;
1167 if !matches {
1168 return Err(Error::Corrupt);
1169 }
1170
1171 Ok(())
1172}