icydb_core/traits/mod.rs
1#[macro_use]
2mod macros;
3mod atomic;
4mod view;
5mod visitor;
6
7pub use atomic::*;
8pub use view::*;
9pub use visitor::*;
10
11// -----------------------------------------------------------------------------
12// Standard re-exports for `traits::X` ergonomics
13// -----------------------------------------------------------------------------
14
15pub use canic_cdk::structures::storable::Storable;
16pub use num_traits::{FromPrimitive as NumFromPrimitive, NumCast, ToPrimitive as NumToPrimitive};
17pub use serde::{Deserialize, Serialize, de::DeserializeOwned};
18pub use std::{
19 cmp::{Eq, Ordering, PartialEq},
20 convert::From,
21 default::Default,
22 fmt::Debug,
23 hash::Hash,
24 ops::{Add, AddAssign, Deref, DerefMut, Div, DivAssign, Mul, MulAssign, Rem, Sub, SubAssign},
25};
26
27use crate::{prelude::*, types::Id, value::ValueEnum, visitor::VisitorContext};
28
29// ============================================================================
30// FOUNDATIONAL KINDS
31// ============================================================================
32//
33// These traits define *where* something lives in the system,
34// not what data it contains.
35//
36
37///
38/// Path
39/// Fully-qualified schema path.
40///
41
42pub trait Path {
43 const PATH: &'static str;
44}
45
46/// Marker for all schema/runtime nodes.
47pub trait Kind: Path + 'static {}
48impl<T> Kind for T where T: Path + 'static {}
49
50/// Marker for canister namespaces.
51pub trait CanisterKind: Kind {}
52
53/// Marker for data stores bound to a canister.
54pub trait StoreKind: Kind {
55 type Canister: CanisterKind;
56}
57
58// ============================================================================
59// ENTITY IDENTITY & SCHEMA
60// ============================================================================
61//
62// These traits describe *what an entity is*, not how it is stored
63// or manipulated at runtime.
64//
65
66///
67/// EntityKey
68///
69/// Associates an entity with the primitive type used as its primary key.
70///
71/// ## Semantics
72/// - Implemented for entity types
73/// - `Self::Key` is the *storage representation* of the primary key
74/// - Keys are plain values (Ulid, u64, Principal, …)
75/// - Typed identity is provided by `Id<Self>`, not by the key itself
76/// - Keys are public identifiers and are never authority-bearing capabilities
77///
78
79pub trait EntityKey {
80 type Key: Copy + Debug + Eq + Ord + FieldValue + EntityKeyBytes + 'static;
81}
82
83///
84/// EntityKeyBytes
85///
86
87pub trait EntityKeyBytes {
88 /// Exact number of bytes produced.
89 const BYTE_LEN: usize;
90
91 /// Write bytes into the provided buffer.
92 fn write_bytes(&self, out: &mut [u8]);
93}
94
95macro_rules! impl_entity_key_bytes_numeric {
96 ($($ty:ty),* $(,)?) => {
97 $(
98 impl EntityKeyBytes for $ty {
99 const BYTE_LEN: usize = ::core::mem::size_of::<Self>();
100
101 fn write_bytes(&self, out: &mut [u8]) {
102 assert_eq!(out.len(), Self::BYTE_LEN);
103 out.copy_from_slice(&self.to_be_bytes());
104 }
105 }
106 )*
107 };
108}
109
110impl_entity_key_bytes_numeric!(i8, i16, i32, i64, u8, u16, u32, u64);
111
112impl EntityKeyBytes for () {
113 const BYTE_LEN: usize = 0;
114
115 fn write_bytes(&self, out: &mut [u8]) {
116 assert_eq!(out.len(), Self::BYTE_LEN);
117 }
118}
119
120///
121/// EntityIdentity
122///
123/// Semantic primary-key metadata about an entity.
124///
125/// These constants name identity metadata only. They do not imply trust, ownership,
126/// authorization, or existence.
127///
128
129pub trait EntityIdentity: EntityKey {
130 const ENTITY_NAME: &'static str;
131 const PRIMARY_KEY: &'static str;
132}
133
134///
135/// EntitySchema
136///
137/// Declared schema facts for an entity.
138///
139
140pub trait EntitySchema: EntityIdentity {
141 const MODEL: &'static EntityModel;
142 const FIELDS: &'static [&'static str];
143 const INDEXES: &'static [&'static IndexModel];
144}
145
146// ============================================================================
147// ENTITY RUNTIME COMPOSITION
148// ============================================================================
149//
150// These traits bind schema-defined entities into runtime placement.
151//
152
153///
154/// EntityPlacement
155///
156/// Runtime placement of an entity
157///
158
159pub trait EntityPlacement {
160 type Store: StoreKind;
161 type Canister: CanisterKind;
162}
163
164///
165/// EntityKind
166///
167/// Fully runtime-bound entity.
168///
169/// This is the *maximum* entity contract and should only be
170/// required by code that actually touches storage or execution.
171///
172
173pub trait EntityKind: EntitySchema + EntityPlacement + Kind + TypeKind {}
174
175// ============================================================================
176// ENTITY VALUES
177// ============================================================================
178//
179// These traits describe *instances* of entities.
180//
181
182///
183/// EntityValue
184///
185/// A concrete entity value that can present a typed identity at boundaries.
186///
187/// Implementors store primitive key material internally.
188/// `id()` constructs a typed `Id<Self>` view on demand.
189/// The returned `Id<Self>` is a public identifier, not proof of authority.
190///
191
192pub trait EntityValue: EntityIdentity + FieldValues + Sized {
193 fn id(&self) -> Id<Self>;
194}
195
196/// Marker for entities with exactly one logical row.
197pub trait SingletonEntity: EntityValue {}
198
199///
200// ============================================================================
201// TYPE SYSTEM CONTRACTS
202// ============================================================================
203//
204// These traits define behavioral expectations for schema-defined types.
205//
206
207///
208/// TypeKind
209///
210/// Any schema-defined data type.
211///
212/// This is a *strong* contract and should only be required
213/// where full lifecycle semantics are needed.
214///
215
216pub trait TypeKind:
217 Kind
218 + AsView
219 + Clone
220 + Default
221 + Serialize
222 + DeserializeOwned
223 + Sanitize
224 + Validate
225 + Visitable
226 + PartialEq
227{
228}
229
230impl<T> TypeKind for T where
231 T: Kind
232 + AsView
233 + Clone
234 + Default
235 + DeserializeOwned
236 + PartialEq
237 + Serialize
238 + Sanitize
239 + Validate
240 + Visitable
241{
242}
243
244/// ============================================================================
245/// QUERY VALUE BOUNDARIES
246/// ============================================================================
247
248///
249/// Collection
250///
251/// Explicit iteration contract for list/set wrapper types.
252/// Avoids implicit deref-based access to inner collections.
253///
254
255pub trait Collection {
256 type Item;
257
258 /// Iterator over the collection's items, tied to the borrow of `self`.
259 type Iter<'a>: Iterator<Item = &'a Self::Item> + 'a
260 where
261 Self: 'a;
262
263 /// Returns an iterator over the collection's items.
264 fn iter(&self) -> Self::Iter<'_>;
265
266 /// Returns the number of items in the collection.
267 fn len(&self) -> usize;
268
269 /// Returns true if the collection contains no items.
270 fn is_empty(&self) -> bool {
271 self.len() == 0
272 }
273}
274
275///
276/// MapCollection
277///
278/// Explicit iteration contract for map wrapper types.
279/// Avoids implicit deref-based access to inner collections.
280///
281
282pub trait MapCollection {
283 type Key;
284 type Value;
285
286 /// Iterator over the map's key/value pairs, tied to the borrow of `self`.
287 type Iter<'a>: Iterator<Item = (&'a Self::Key, &'a Self::Value)> + 'a
288 where
289 Self: 'a;
290
291 /// Returns an iterator over the map's key/value pairs.
292 fn iter(&self) -> Self::Iter<'_>;
293
294 /// Returns the number of entries in the map.
295 fn len(&self) -> usize;
296
297 /// Returns true if the map contains no entries.
298 fn is_empty(&self) -> bool {
299 self.len() == 0
300 }
301}
302
303pub trait EnumValue {
304 fn to_value_enum(&self) -> ValueEnum;
305}
306
307pub trait FieldValues {
308 fn get_value(&self, field: &str) -> Option<Value>;
309}
310
311///
312/// FieldValueKind
313///
314/// Schema affordance classification for query planning and validation.
315/// Describes whether a field is planner-addressable and predicate-queryable.
316///
317#[derive(Clone, Copy, Debug, Eq, PartialEq)]
318pub enum FieldValueKind {
319 /// Planner-addressable atomic value.
320 Atomic,
321
322 /// Structured value with known internal fields that the planner
323 /// does not reason about as an addressable query target.
324 Structured {
325 /// Whether predicates may be expressed against this field.
326 queryable: bool,
327 },
328}
329
330impl FieldValueKind {
331 #[must_use]
332 pub const fn is_queryable(self) -> bool {
333 match self {
334 Self::Atomic => true,
335 Self::Structured { queryable } => queryable,
336 }
337 }
338}
339
340///
341/// FieldValue
342///
343/// Conversion boundary for values used in query predicates.
344///
345/// Represents values that can appear on the *right-hand side* of predicates.
346///
347
348pub trait FieldValue {
349 fn kind() -> FieldValueKind
350 where
351 Self: Sized;
352
353 fn to_value(&self) -> Value;
354
355 #[must_use]
356 fn from_value(value: &Value) -> Option<Self>
357 where
358 Self: Sized;
359}
360
361impl FieldValue for &str {
362 fn kind() -> FieldValueKind {
363 FieldValueKind::Atomic
364 }
365
366 fn to_value(&self) -> Value {
367 Value::Text((*self).to_string())
368 }
369
370 fn from_value(_value: &Value) -> Option<Self> {
371 None
372 }
373}
374
375impl FieldValue for String {
376 fn kind() -> FieldValueKind {
377 FieldValueKind::Atomic
378 }
379
380 fn to_value(&self) -> Value {
381 Value::Text(self.clone())
382 }
383
384 fn from_value(value: &Value) -> Option<Self> {
385 match value {
386 Value::Text(v) => Some(v.clone()),
387 _ => None,
388 }
389 }
390}
391
392impl<T: FieldValue> FieldValue for Option<T> {
393 fn kind() -> FieldValueKind {
394 T::kind()
395 }
396
397 fn to_value(&self) -> Value {
398 match self {
399 Some(v) => v.to_value(),
400 None => Value::Null,
401 }
402 }
403
404 fn from_value(value: &Value) -> Option<Self> {
405 if matches!(value, Value::Null) {
406 return Some(None);
407 }
408
409 T::from_value(value).map(Some)
410 }
411}
412
413impl<T: FieldValue> FieldValue for Box<T> {
414 fn kind() -> FieldValueKind {
415 T::kind()
416 }
417
418 fn to_value(&self) -> Value {
419 (**self).to_value()
420 }
421
422 fn from_value(value: &Value) -> Option<Self> {
423 T::from_value(value).map(Self::new)
424 }
425}
426
427impl<T: FieldValue> FieldValue for Vec<Box<T>> {
428 fn kind() -> FieldValueKind {
429 FieldValueKind::Structured { queryable: true }
430 }
431
432 fn to_value(&self) -> Value {
433 Value::List(self.iter().map(FieldValue::to_value).collect())
434 }
435
436 fn from_value(value: &Value) -> Option<Self> {
437 let Value::List(items) = value else {
438 return None;
439 };
440
441 let mut out = Self::with_capacity(items.len());
442 for item in items {
443 out.push(Box::new(T::from_value(item)?));
444 }
445
446 Some(out)
447 }
448}
449
450// impl_field_value
451#[macro_export]
452macro_rules! impl_field_value {
453 ( $( $type:ty => $variant:ident ),* $(,)? ) => {
454 $(
455 impl FieldValue for $type {
456 fn kind() -> FieldValueKind {
457 FieldValueKind::Atomic
458 }
459
460 fn to_value(&self) -> Value {
461 Value::$variant((*self).into())
462 }
463
464 fn from_value(value: &Value) -> Option<Self> {
465 match value {
466 Value::$variant(v) => (*v).try_into().ok(),
467 _ => None,
468 }
469 }
470 }
471 )*
472 };
473}
474
475impl_field_value!(
476 i8 => Int,
477 i16 => Int,
478 i32 => Int,
479 i64 => Int,
480 u8 => Uint,
481 u16 => Uint,
482 u32 => Uint,
483 u64 => Uint,
484 bool => Bool,
485);
486
487/// ============================================================================
488/// MISC HELPERS
489/// ============================================================================
490
491///
492/// Inner
493///
494/// For newtypes to expose their innermost value.
495///
496pub trait Inner<T> {
497 fn inner(&self) -> &T;
498 fn into_inner(self) -> T;
499}
500
501impl<T> Inner<T> for T
502where
503 T: Atomic,
504{
505 fn inner(&self) -> &T {
506 self
507 }
508
509 fn into_inner(self) -> T {
510 self
511 }
512}
513
514/// ============================================================================
515/// SANITIZATION / VALIDATION
516/// ============================================================================
517
518///
519/// Sanitizer
520///
521/// Transforms a value into a sanitized version.
522///
523pub trait Sanitizer<T> {
524 fn sanitize(&self, value: &mut T) -> Result<(), String>;
525}
526
527///
528/// Validator
529///
530/// Allows a node to validate values.
531///
532pub trait Validator<T: ?Sized> {
533 fn validate(&self, value: &T, ctx: &mut dyn VisitorContext);
534}