mockforge-collab 0.3.124

Cloud collaboration features for MockForge - team workspaces, real-time sync, and version control
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
//! Version control and history tracking

use crate::error::{CollabError, Result};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use sqlx::{Pool, Sqlite};
use uuid::Uuid;

/// A commit in the history
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct Commit {
    /// Unique commit ID
    pub id: Uuid,
    /// Workspace ID
    pub workspace_id: Uuid,
    /// User who made the commit
    pub author_id: Uuid,
    /// Commit message
    pub message: String,
    /// Parent commit ID (None for initial commit)
    pub parent_id: Option<Uuid>,
    /// Workspace version at this commit
    pub version: i64,
    /// Full workspace state snapshot (JSON)
    pub snapshot: serde_json::Value,
    /// Changes made in this commit (diff)
    pub changes: serde_json::Value,
    /// Timestamp
    pub created_at: chrono::DateTime<Utc>,
}

impl Commit {
    /// Create a new commit
    #[must_use]
    pub fn new(
        workspace_id: Uuid,
        author_id: Uuid,
        message: String,
        parent_id: Option<Uuid>,
        version: i64,
        snapshot: serde_json::Value,
        changes: serde_json::Value,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            workspace_id,
            author_id,
            message,
            parent_id,
            version,
            snapshot,
            changes,
            created_at: Utc::now(),
        }
    }
}

/// A named snapshot (like a git tag)
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct Snapshot {
    /// Unique snapshot ID
    pub id: Uuid,
    /// Workspace ID
    pub workspace_id: Uuid,
    /// Snapshot name
    pub name: String,
    /// Description
    pub description: Option<String>,
    /// Commit ID this snapshot points to
    pub commit_id: Uuid,
    /// Created by
    pub created_by: Uuid,
    /// Created timestamp
    pub created_at: chrono::DateTime<Utc>,
}

impl Snapshot {
    /// Create a new snapshot
    #[must_use]
    pub fn new(
        workspace_id: Uuid,
        name: String,
        description: Option<String>,
        commit_id: Uuid,
        created_by: Uuid,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            workspace_id,
            name,
            description,
            commit_id,
            created_by,
            created_at: Utc::now(),
        }
    }
}

/// Version control system for workspaces
pub struct VersionControl {
    db: Pool<Sqlite>,
}

impl VersionControl {
    /// Create a new version control system
    #[must_use]
    pub const fn new(db: Pool<Sqlite>) -> Self {
        Self { db }
    }

    /// Create a commit
    ///
    /// # Errors
    ///
    /// Returns an error if the database insert fails.
    #[allow(clippy::too_many_arguments)]
    pub async fn create_commit(
        &self,
        workspace_id: Uuid,
        author_id: Uuid,
        message: String,
        parent_id: Option<Uuid>,
        version: i64,
        snapshot: serde_json::Value,
        changes: serde_json::Value,
    ) -> Result<Commit> {
        let commit =
            Commit::new(workspace_id, author_id, message, parent_id, version, snapshot, changes);

        sqlx::query!(
            r#"
            INSERT INTO commits (id, workspace_id, author_id, message, parent_id, version, snapshot, changes, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            "#,
            commit.id,
            commit.workspace_id,
            commit.author_id,
            commit.message,
            commit.parent_id,
            commit.version,
            commit.snapshot,
            commit.changes,
            commit.created_at
        )
        .execute(&self.db)
        .await?;

        Ok(commit)
    }

    /// Get a commit by ID
    ///
    /// # Errors
    ///
    /// Returns an error if the commit is not found or the database query fails.
    pub async fn get_commit(&self, commit_id: Uuid) -> Result<Commit> {
        sqlx::query_as!(
            Commit,
            r#"
            SELECT
                id as "id: Uuid",
                workspace_id as "workspace_id: Uuid",
                author_id as "author_id: Uuid",
                message,
                parent_id as "parent_id: Uuid",
                version,
                snapshot as "snapshot: serde_json::Value",
                changes as "changes: serde_json::Value",
                created_at as "created_at: chrono::DateTime<chrono::Utc>"
            FROM commits
            WHERE id = ?
            "#,
            commit_id
        )
        .fetch_optional(&self.db)
        .await?
        .ok_or_else(|| CollabError::Internal(format!("Commit not found: {commit_id}")))
    }

    /// Get commit history for a workspace
    ///
    /// # Errors
    ///
    /// Returns an error if the database query fails.
    pub async fn get_history(&self, workspace_id: Uuid, limit: Option<i32>) -> Result<Vec<Commit>> {
        let limit = limit.unwrap_or(100);

        let commits = sqlx::query_as!(
            Commit,
            r#"
            SELECT
                id as "id: Uuid",
                workspace_id as "workspace_id: Uuid",
                author_id as "author_id: Uuid",
                message,
                parent_id as "parent_id: Uuid",
                version,
                snapshot as "snapshot: serde_json::Value",
                changes as "changes: serde_json::Value",
                created_at as "created_at: chrono::DateTime<chrono::Utc>"
            FROM commits
            WHERE workspace_id = ?
            ORDER BY created_at DESC
            LIMIT ?
            "#,
            workspace_id,
            limit
        )
        .fetch_all(&self.db)
        .await?;

        Ok(commits)
    }

    /// Get the latest commit for a workspace
    ///
    /// # Errors
    ///
    /// Returns an error if the database query fails.
    pub async fn get_latest_commit(&self, workspace_id: Uuid) -> Result<Option<Commit>> {
        let commit = sqlx::query_as!(
            Commit,
            r#"
            SELECT
                id as "id: Uuid",
                workspace_id as "workspace_id: Uuid",
                author_id as "author_id: Uuid",
                message,
                parent_id as "parent_id: Uuid",
                version,
                snapshot as "snapshot: serde_json::Value",
                changes as "changes: serde_json::Value",
                created_at as "created_at: chrono::DateTime<chrono::Utc>"
            FROM commits
            WHERE workspace_id = ?
            ORDER BY created_at DESC
            LIMIT 1
            "#,
            workspace_id
        )
        .fetch_optional(&self.db)
        .await?;

        Ok(commit)
    }

    /// Create a named snapshot
    ///
    /// # Errors
    ///
    /// Returns an error if the commit does not exist or the database insert fails.
    pub async fn create_snapshot(
        &self,
        workspace_id: Uuid,
        name: String,
        description: Option<String>,
        commit_id: Uuid,
        created_by: Uuid,
    ) -> Result<Snapshot> {
        // Verify commit exists
        self.get_commit(commit_id).await?;

        let snapshot = Snapshot::new(workspace_id, name, description, commit_id, created_by);

        sqlx::query!(
            r#"
            INSERT INTO snapshots (id, workspace_id, name, description, commit_id, created_by, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
            "#,
            snapshot.id,
            snapshot.workspace_id,
            snapshot.name,
            snapshot.description,
            snapshot.commit_id,
            snapshot.created_by,
            snapshot.created_at
        )
        .execute(&self.db)
        .await?;

        Ok(snapshot)
    }

    /// Get a snapshot by name
    ///
    /// # Errors
    ///
    /// Returns an error if the snapshot is not found or the database query fails.
    pub async fn get_snapshot(&self, workspace_id: Uuid, name: &str) -> Result<Snapshot> {
        sqlx::query_as!(
            Snapshot,
            r#"
            SELECT
                id as "id: Uuid",
                workspace_id as "workspace_id: Uuid",
                name,
                description,
                commit_id as "commit_id: Uuid",
                created_by as "created_by: Uuid",
                created_at as "created_at: chrono::DateTime<chrono::Utc>"
            FROM snapshots
            WHERE workspace_id = ? AND name = ?
            "#,
            workspace_id,
            name
        )
        .fetch_optional(&self.db)
        .await?
        .ok_or_else(|| CollabError::Internal(format!("Snapshot not found: {name}")))
    }

    /// List all snapshots for a workspace
    ///
    /// # Errors
    ///
    /// Returns an error if the database query fails.
    pub async fn list_snapshots(&self, workspace_id: Uuid) -> Result<Vec<Snapshot>> {
        let snapshots = sqlx::query_as!(
            Snapshot,
            r#"
            SELECT
                id as "id: Uuid",
                workspace_id as "workspace_id: Uuid",
                name,
                description,
                commit_id as "commit_id: Uuid",
                created_by as "created_by: Uuid",
                created_at as "created_at: chrono::DateTime<chrono::Utc>"
            FROM snapshots
            WHERE workspace_id = ?
            ORDER BY created_at DESC
            "#,
            workspace_id
        )
        .fetch_all(&self.db)
        .await?;

        Ok(snapshots)
    }

    /// Restore workspace to a specific commit
    ///
    /// # Errors
    ///
    /// Returns an error if the commit is not found or does not belong to the workspace.
    pub async fn restore_to_commit(
        &self,
        workspace_id: Uuid,
        commit_id: Uuid,
    ) -> Result<serde_json::Value> {
        let commit = self.get_commit(commit_id).await?;

        if commit.workspace_id != workspace_id {
            return Err(CollabError::InvalidInput(
                "Commit does not belong to this workspace".to_string(),
            ));
        }

        Ok(commit.snapshot)
    }

    /// Compare two commits
    ///
    /// # Errors
    ///
    /// Returns an error if either commit is not found.
    pub async fn diff(&self, from_commit: Uuid, to_commit: Uuid) -> Result<serde_json::Value> {
        let from = self.get_commit(from_commit).await?;
        let to = self.get_commit(to_commit).await?;

        // Simple diff - in production, use a proper diffing library
        let diff = serde_json::json!({
            "from": from.snapshot,
            "to": to.snapshot,
            "changes": to.changes
        });

        Ok(diff)
    }
}

/// History tracking with auto-commit
pub struct History {
    version_control: VersionControl,
    auto_commit: bool,
}

impl History {
    /// Create a new history tracker
    #[must_use]
    pub const fn new(db: Pool<Sqlite>) -> Self {
        Self {
            version_control: VersionControl::new(db),
            auto_commit: true,
        }
    }

    /// Enable/disable auto-commit
    pub const fn set_auto_commit(&mut self, enabled: bool) {
        self.auto_commit = enabled;
    }

    /// Track a change (auto-commit if enabled)
    ///
    /// # Errors
    ///
    /// Returns an error if the commit cannot be created.
    pub async fn track_change(
        &self,
        workspace_id: Uuid,
        user_id: Uuid,
        message: String,
        new_state: serde_json::Value,
        changes: serde_json::Value,
    ) -> Result<Option<Commit>> {
        if !self.auto_commit {
            return Ok(None);
        }

        let latest = self.version_control.get_latest_commit(workspace_id).await?;
        let parent_id = latest.as_ref().map(|c| c.id);
        let version = latest.map_or(1, |c| c.version + 1);

        let commit = self
            .version_control
            .create_commit(workspace_id, user_id, message, parent_id, version, new_state, changes)
            .await?;

        Ok(Some(commit))
    }

    /// Get history
    ///
    /// # Errors
    ///
    /// Returns an error if the database query fails.
    pub async fn get_history(&self, workspace_id: Uuid, limit: Option<i32>) -> Result<Vec<Commit>> {
        self.version_control.get_history(workspace_id, limit).await
    }

    /// Create a snapshot
    ///
    /// # Errors
    ///
    /// Returns an error if there are no commits or the snapshot cannot be created.
    pub async fn create_snapshot(
        &self,
        workspace_id: Uuid,
        name: String,
        description: Option<String>,
        user_id: Uuid,
    ) -> Result<Snapshot> {
        // Get the latest commit
        let latest = self
            .version_control
            .get_latest_commit(workspace_id)
            .await?
            .ok_or_else(|| CollabError::Internal("No commits found".to_string()))?;

        self.version_control
            .create_snapshot(workspace_id, name, description, latest.id, user_id)
            .await
    }

    /// Restore from snapshot
    ///
    /// # Errors
    ///
    /// Returns an error if the snapshot is not found or restoration fails.
    pub async fn restore_snapshot(
        &self,
        workspace_id: Uuid,
        snapshot_name: &str,
    ) -> Result<serde_json::Value> {
        let snapshot = self.version_control.get_snapshot(workspace_id, snapshot_name).await?;
        self.version_control.restore_to_commit(workspace_id, snapshot.commit_id).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_commit_creation() {
        let workspace_id = Uuid::new_v4();
        let author_id = Uuid::new_v4();
        let commit = Commit::new(
            workspace_id,
            author_id,
            "Initial commit".to_string(),
            None,
            1,
            serde_json::json!({}),
            serde_json::json!({}),
        );

        assert_eq!(commit.workspace_id, workspace_id);
        assert_eq!(commit.author_id, author_id);
        assert_eq!(commit.version, 1);
        assert!(commit.parent_id.is_none());
    }

    #[test]
    fn test_snapshot_creation() {
        let workspace_id = Uuid::new_v4();
        let commit_id = Uuid::new_v4();
        let created_by = Uuid::new_v4();
        let snapshot = Snapshot::new(
            workspace_id,
            "v1.0.0".to_string(),
            Some("First release".to_string()),
            commit_id,
            created_by,
        );

        assert_eq!(snapshot.name, "v1.0.0");
        assert_eq!(snapshot.workspace_id, workspace_id);
        assert_eq!(snapshot.commit_id, commit_id);
    }
}