valence_core/model.rs
1//! Model contracts generated from schema DSL.
2//!
3//! Generated model types implement [`Model`] via `valence-codegen`. See the
4//! `valence-codegen` crate README and `examples/codegen-host` for the build pipeline.
5
6use crate::error::Result;
7use crate::runtime::Valence;
8use async_trait::async_trait;
9
10/// Core trait that all generated models implement.
11///
12/// CRUD methods route through the active [`Valence`] backend, applying privacy and ownership
13/// hooks defined in the source schema.
14///
15/// # Examples
16///
17/// Generated models (from `valence-codegen`) implement this trait. After including
18/// `$OUT_DIR/generated_models.rs`:
19///
20/// ```ignore
21/// use valence::Model;
22///
23/// let created = Widget::create(widget, &valence).await?;
24/// let loaded = Widget::get(created.id(), &valence).await?;
25/// Widget::update(created.id(), updated, &valence).await?;
26/// Widget::delete(created.id(), &valence).await?;
27/// ```
28///
29/// See workspace `examples/codegen-host` and `examples/product-model-host`.
30#[async_trait]
31pub trait Model: Sized + Send + Sync {
32 /// Generated schema metadata type for this model.
33 type Schema;
34 /// Field-level change set type used by update/merge paths.
35 type FieldChanges: Send + Sync;
36
37 /// Physical table name from the schema DSL `table:` key.
38 fn table_name() -> &'static str;
39 /// Schema version string from the DSL `version:` key.
40 fn schema_version() -> &'static str;
41
42 /// Fetch one row by primary key; returns `Ok(None)` when absent.
43 async fn get(id: &str, valence: &Valence) -> Result<Option<Self>>;
44 /// Insert a new row.
45 async fn create(data: Self, valence: &Valence) -> Result<Self>;
46 /// Replace an existing row by id.
47 async fn update(id: &str, data: Self, valence: &Valence) -> Result<Self>;
48 /// Delete one row by id.
49 async fn delete(id: &str, valence: &Valence) -> Result<()>;
50 /// Create or replace a row by explicit id.
51 async fn upsert(id: &str, data: Self, valence: &Valence) -> Result<Self>;
52 /// Patch an existing row with a partial JSON object when the backend supports merge.
53 async fn merge(id: &str, patch: serde_json::Value, valence: &Valence) -> Result<Self>;
54}
55
56/// Field access direction for privacy checks.
57#[derive(Debug, Clone, Copy)]
58pub enum FieldOperation {
59 /// Read path (get, list, query projection).
60 Read,
61 /// Write path (create, update, merge).
62 Write,
63}
64
65/// Error returned when a privacy rule blocks field access.
66#[derive(Debug, Clone)]
67pub struct PrivacyError {
68 /// Schema field name that failed the check.
69 pub field: String,
70 /// Whether the operation was a read or write.
71 pub operation: FieldOperation,
72 /// Human-readable denial reason.
73 pub message: String,
74}
75
76impl std::fmt::Display for PrivacyError {
77 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78 write!(
79 f,
80 "Privacy violation on field '{}' for {:?} operation: {}",
81 self.field, self.operation, self.message
82 )
83 }
84}
85
86impl std::error::Error for PrivacyError {}
87
88/// Compile-time schema metadata access for generated models (trait; struct is [`crate::schema::SchemaMetadata`]).
89pub trait SchemaMetadata: Model {
90 /// Static metadata type emitted by codegen.
91 type SchemaMetadata;
92
93 /// Return the process-global metadata instance for this model.
94 fn schema_metadata() -> &'static Self::SchemaMetadata;
95
96 /// Convenience accessor for instance callers.
97 fn get_schema_metadata(&self) -> &'static Self::SchemaMetadata {
98 Self::schema_metadata()
99 }
100}