Skip to main content

che_orm/
sync.rs

1//! Backend-independent model registration for local-first applications.
2use crate::{ColumnSchema, ColumnType, Model, TableSchema, Uuid};
3
4/// Role of a synchronized model in a particular database.
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum ModelRole {
7    Client,
8    Server,
9}
10
11/// Stable protocol name mapped to a model-controlled SQL column.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct SyncField {
14    pub name: &'static str,
15    pub column: &'static str,
16    pub writable: bool,
17}
18
19impl SyncField {
20    pub const fn writable(name: &'static str, column: &'static str) -> Self {
21        Self {
22            name,
23            column,
24            writable: true,
25        }
26    }
27    pub const fn server_owned(name: &'static str, column: &'static str) -> Self {
28        Self {
29            name,
30            column,
31            writable: false,
32        }
33    }
34}
35
36/// Shared model definition. Its client/server role belongs to registration.
37pub trait SyncModel: Model<PrimaryKey = Uuid> + Send + Sync + 'static {
38    const SYNC_NAME: &'static str;
39    const SYNC_VERSION: u32 = 1;
40    /// Derived sync models keep service columns out of the Rust struct.
41    const AUTOMATIC_METADATA: bool = false;
42    const REVISION_COLUMN: &'static str = "revision";
43    const UPDATED_AT_COLUMN: &'static str = "updated_at";
44    const DELETED_AT_COLUMN: &'static str = "deleted_at";
45    const SCOPE_COLUMN: &'static str = "sync_scope";
46    fn sync_fields() -> Vec<SyncField>;
47
48    fn registered_fields() -> Vec<SyncField> {
49        let mut fields = Self::sync_fields();
50        for (name, column) in [
51            ("revision", Self::REVISION_COLUMN),
52            ("updated_at", Self::UPDATED_AT_COLUMN),
53            ("deleted_at", Self::DELETED_AT_COLUMN),
54            ("sync_scope", Self::SCOPE_COLUMN),
55        ] {
56            if !fields.iter().any(|field| field.column == column) {
57                fields.push(SyncField::server_owned(name, column));
58            }
59        }
60        fields
61    }
62
63    /// Physical schema, including infrastructure-owned service columns.
64    fn sync_schema() -> TableSchema {
65        let mut schema = Self::schema();
66        if Self::AUTOMATIC_METADATA {
67            for (name, ty, nullable, default) in [
68                (Self::REVISION_COLUMN, ColumnType::Integer, false, Some("0")),
69                (Self::UPDATED_AT_COLUMN, ColumnType::DateTime, false, None),
70                (Self::DELETED_AT_COLUMN, ColumnType::DateTime, true, None),
71                (Self::SCOPE_COLUMN, ColumnType::Text, false, Some("''")),
72            ] {
73                let mut column = ColumnSchema::new(name, ty, nullable);
74                column.default = default;
75                column.auto_now = name == Self::UPDATED_AT_COLUMN;
76                schema.columns.push(column);
77            }
78        }
79        schema
80    }
81}
82
83/// Runtime-independent registration consumed by che-sync.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct SyncRegistration {
86    pub role: ModelRole,
87    pub name: &'static str,
88    pub version: u32,
89    pub schema: TableSchema,
90    pub fields: Vec<SyncField>,
91    pub protected_columns: Vec<&'static str>,
92    pub json_columns: Vec<&'static str>,
93    pub revision: &'static str,
94    pub updated_at: &'static str,
95    pub deleted_at: &'static str,
96    pub scope: &'static str,
97}
98
99impl SyncRegistration {
100    pub fn new<M: SyncModel>(role: ModelRole) -> Self {
101        Self {
102            role,
103            name: M::SYNC_NAME,
104            version: M::SYNC_VERSION,
105            schema: M::sync_schema(),
106            fields: M::registered_fields(),
107            protected_columns: M::write_protected_columns().to_vec(),
108            json_columns: M::json_columns().to_vec(),
109            revision: M::REVISION_COLUMN,
110            updated_at: M::UPDATED_AT_COLUMN,
111            deleted_at: M::DELETED_AT_COLUMN,
112            scope: M::SCOPE_COLUMN,
113        }
114    }
115}
116
117/// Infrastructure tables shared by all registrations of a database role.
118pub fn sync_migration_operations(
119    registrations: &[SyncRegistration],
120) -> Result<Vec<crate::MigrationOperation>, crate::MigrationError> {
121    let Some(first) = registrations.first() else {
122        return Ok(vec![]);
123    };
124    sync_migration_operations_for_role(first.role, registrations)
125}
126
127/// Explicit role variant, also useful for an empty legacy registry.
128pub fn sync_migration_operations_for_role(
129    role: ModelRole,
130    registrations: &[SyncRegistration],
131) -> Result<Vec<crate::MigrationOperation>, crate::MigrationError> {
132    use crate::{
133        ColumnState, MigrationError, MigrationOperation, ModelKey, ModelState, TableState,
134    };
135    use ColumnType::{Integer as I, Text as T};
136    if registrations
137        .iter()
138        .any(|registration| registration.role != role)
139    {
140        return Err(MigrationError::InvalidState(
141            "a database cannot mix client and server sync roles".into(),
142        ));
143    }
144    fn table(name: &str, columns: &[(&str, ColumnType)], unique: &[&str]) -> crate::TableState {
145        crate::TableState {
146            name: name.into(),
147            columns: columns
148                .iter()
149                .map(|(name, ty)| crate::ColumnState {
150                    field_name: (*name).into(),
151                    name: (*name).into(),
152                    column_type: *ty,
153                    nullable: false,
154                    primary_key: false,
155                    unique: false,
156                    default: None,
157                    check: None,
158                    choices: None,
159                    references: None,
160                    auto_now: false,
161                    auto_now_add: false,
162                })
163                .collect(),
164            unique_constraints: vec![unique.iter().map(|name| (*name).into()).collect()],
165            indexes: vec![],
166        }
167    }
168    let mut tables = match role {
169        ModelRole::Client => vec![
170            table("_sync_meta", &[("key", T), ("value", T)], &["key"]),
171            table(
172                "_sync_dirty",
173                &[("model", T), ("entity_id", T)],
174                &["model", "entity_id"],
175            ),
176            table(
177                "_sync_outbox",
178                &[("operation_id", T), ("payload", T)],
179                &["operation_id"],
180            ),
181            table(
182                "_sync_conflicts",
183                &[("model", T), ("entity_id", T), ("payload", T)],
184                &["model", "entity_id"],
185            ),
186        ],
187        ModelRole::Server => vec![
188            table(
189                "_sync_effects",
190                &[("id", T), ("scope", T), ("principal", T), ("payload", T)],
191                &["id"],
192            ),
193            table(
194                "_sync_scopes",
195                &[("scope", T), ("epoch", T), ("sequence", I)],
196                &["scope"],
197            ),
198            table(
199                "_sync_changes",
200                &[("scope", T), ("sequence", I), ("payload", T)],
201                &["scope", "sequence"],
202            ),
203            table(
204                "_sync_receipts",
205                &[
206                    ("scope", T),
207                    ("replica_id", T),
208                    ("operation_id", T),
209                    ("request", T),
210                    ("result", T),
211                ],
212                &["scope", "replica_id", "operation_id"],
213            ),
214        ],
215    };
216    if role == ModelRole::Client {
217        for registration in registrations {
218            let mut shadow = TableState::from(&registration.schema);
219            shadow.name = format!("_sync_server_{}", registration.schema.name);
220            shadow.indexes.clear();
221            shadow.unique_constraints.clear();
222            for column in &mut shadow.columns {
223                if !column.primary_key
224                    && ![
225                        registration.revision,
226                        registration.updated_at,
227                        registration.scope,
228                    ]
229                    .contains(&column.name.as_str())
230                {
231                    column.nullable = true;
232                }
233                column.unique = false;
234                column.default = None;
235                column.check = None;
236                column.references = None;
237                column.auto_now = false;
238                column.auto_now_add = false;
239            }
240            shadow.columns.push(ColumnState {
241                field_name: "_sync_epoch".into(),
242                name: "_sync_epoch".into(),
243                column_type: T,
244                nullable: true,
245                primary_key: false,
246                unique: false,
247                default: None,
248                check: None,
249                choices: None,
250                references: None,
251                auto_now: false,
252                auto_now_add: false,
253            });
254            tables.push(shadow);
255        }
256    } else {
257        // Each model owns its cursor/lock row and immutable operation journal.
258        // Legacy shared tables remain available for explicitly migrated clients.
259        for registration in registrations {
260            let mut log = table(
261                &format!("{}_sync_log", registration.schema.name),
262                &[
263                    ("id", I),
264                    ("record_id", ColumnType::Uuid),
265                    ("revision", I),
266                    ("kind", T),
267                    ("diff", T),
268                    ("created_at", ColumnType::DateTime),
269                    ("schema_version", I),
270                ],
271                &["id"],
272            );
273            log.columns[0].primary_key = true;
274            log.indexes.push(vec!["record_id".into(), "id".into()]);
275            tables.push(log);
276            tables.push(table(
277                &format!("{}_sync_log_state", registration.schema.name),
278                &[("key", I), ("sequence", I), ("history", T)],
279                &["key"],
280            ));
281        }
282    }
283    Ok(tables
284        .into_iter()
285        .map(|table| {
286            let identity = registrations
287                .iter()
288                .find(|registration| {
289                    table.name == format!("_sync_server_{}", registration.schema.name)
290                })
291                .map(|registration| format!("shadow:{}", registration.name))
292                .unwrap_or_else(|| {
293                    registrations
294                        .iter()
295                        .find_map(|registration| {
296                            if table.name == format!("{}_sync_log", registration.schema.name) {
297                                Some(format!("log:{}", registration.name))
298                            } else if table.name
299                                == format!("{}_sync_log_state", registration.schema.name)
300                            {
301                                Some(format!("log-state:{}", registration.name))
302                            } else {
303                                None
304                            }
305                        })
306                        .unwrap_or_else(|| table.name.clone())
307                });
308            MigrationOperation::CreateModel {
309                model: ModelState {
310                    key: ModelKey {
311                        app: "che_sync".into(),
312                        name: identity,
313                    },
314                    table,
315                },
316            }
317        })
318        .collect())
319}