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 ///
52 /// Privacy: when the row is absent, **create** policies apply; when it exists, **update**
53 /// policies apply to both the existing row and the proposed payload (after an authorized read).
54 async fn upsert(id: &str, data: Self, valence: &Valence) -> Result<Self>;
55 /// Patch an existing row with a partial JSON object when the backend supports merge.
56 async fn merge(id: &str, patch: serde_json::Value, valence: &Valence) -> Result<Self>;
57}
58
59/// Field access direction for privacy checks.
60#[derive(Debug, Clone, Copy)]
61pub enum FieldOperation {
62 /// Read path (get, list, query projection).
63 Read,
64 /// Write path (create, update, merge).
65 Write,
66}
67
68/// Error returned when a privacy rule blocks field access.
69#[derive(Debug, Clone)]
70pub struct PrivacyError {
71 /// Schema field name that failed the check.
72 pub field: String,
73 /// Whether the operation was a read or write.
74 pub operation: FieldOperation,
75 /// Human-readable denial reason.
76 pub message: String,
77}
78
79impl std::fmt::Display for PrivacyError {
80 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81 write!(
82 f,
83 "Privacy violation on field '{}' for {:?} operation: {}",
84 self.field, self.operation, self.message
85 )
86 }
87}
88
89impl std::error::Error for PrivacyError {}
90
91/// Compile-time schema metadata access for generated models (trait; struct is [`crate::schema::SchemaMetadata`]).
92pub trait SchemaMetadata: Model {
93 /// Static metadata type emitted by codegen.
94 type SchemaMetadata;
95
96 /// Return the process-global metadata instance for this model.
97 fn schema_metadata() -> &'static Self::SchemaMetadata;
98
99 /// Convenience accessor for instance callers.
100 fn get_schema_metadata(&self) -> &'static Self::SchemaMetadata {
101 Self::schema_metadata()
102 }
103}