mockforge-collab 0.3.128

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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! Workspace management and collaboration

// Workspace and related types will be extracted to mockforge-workspace;
// allow here until then.
#![allow(deprecated)]

use crate::core_bridge::CoreBridge;
use crate::error::{CollabError, Result};
use crate::models::{TeamWorkspace, UserRole, WorkspaceFork, WorkspaceMember};
use crate::permissions::{Permission, PermissionChecker};
use chrono::Utc;
use parking_lot::RwLock;
use sqlx::{Pool, Sqlite};
use std::collections::HashMap;
use std::sync::Arc;
use uuid::Uuid;

/// Workspace service for managing collaborative workspaces
pub struct WorkspaceService {
    db: Pool<Sqlite>,
    cache: Arc<RwLock<HashMap<Uuid, TeamWorkspace>>>,
    core_bridge: Option<Arc<CoreBridge>>,
}

impl WorkspaceService {
    /// Create a new workspace service
    #[must_use]
    pub fn new(db: Pool<Sqlite>) -> Self {
        Self {
            db,
            cache: Arc::new(RwLock::new(HashMap::new())),
            core_bridge: None,
        }
    }

    /// Create a new workspace service with `CoreBridge` integration
    #[must_use]
    pub fn with_core_bridge(db: Pool<Sqlite>, core_bridge: Arc<CoreBridge>) -> Self {
        Self {
            db,
            cache: Arc::new(RwLock::new(HashMap::new())),
            core_bridge: Some(core_bridge),
        }
    }

    /// Check database health by running a simple query
    pub async fn check_database_health(&self) -> bool {
        match sqlx::query("SELECT 1").execute(&self.db).await {
            Ok(_) => true,
            Err(e) => {
                tracing::error!("Database health check failed: {}", e);
                false
            }
        }
    }

    /// Create a new workspace
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub async fn create_workspace(
        &self,
        name: String,
        description: Option<String>,
        owner_id: Uuid,
    ) -> Result<TeamWorkspace> {
        let mut workspace = TeamWorkspace::new(name.clone(), owner_id);
        workspace.description.clone_from(&description);

        // If we have CoreBridge, create a proper core workspace and embed it
        if let Some(core_bridge) = &self.core_bridge {
            let core_workspace = core_bridge.create_empty_workspace(name, owner_id)?;
            workspace.config = core_workspace.config;
        } else {
            // Fallback: create minimal config
            workspace.config = serde_json::json!({
                "name": workspace.name,
                "description": workspace.description,
                "folders": [],
                "requests": []
            });
        }

        // Insert into database
        sqlx::query!(
            r#"
            INSERT INTO workspaces (id, name, description, owner_id, config, version, created_at, updated_at, is_archived)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            "#,
            workspace.id,
            workspace.name,
            workspace.description,
            workspace.owner_id,
            workspace.config,
            workspace.version,
            workspace.created_at,
            workspace.updated_at,
            workspace.is_archived
        )
        .execute(&self.db)
        .await?;

        // Add owner as admin member
        let member = WorkspaceMember::new(workspace.id, owner_id, UserRole::Admin);
        sqlx::query!(
            r#"
            INSERT INTO workspace_members (id, workspace_id, user_id, role, joined_at, last_activity)
            VALUES (?, ?, ?, ?, ?, ?)
            "#,
            member.id,
            member.workspace_id,
            member.user_id,
            member.role,
            member.joined_at,
            member.last_activity
        )
        .execute(&self.db)
        .await?;

        // Update cache
        self.cache.write().insert(workspace.id, workspace.clone());

        Ok(workspace)
    }

    /// Get a workspace by ID
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub async fn get_workspace(&self, workspace_id: Uuid) -> Result<TeamWorkspace> {
        // Check cache first
        if let Some(workspace) = self.cache.read().get(&workspace_id) {
            return Ok(workspace.clone());
        }

        // Query database
        let workspace = sqlx::query_as!(
            TeamWorkspace,
            r#"
            SELECT
                id as "id: Uuid",
                name,
                description,
                owner_id as "owner_id: Uuid",
                config,
                version,
                created_at as "created_at: chrono::DateTime<chrono::Utc>",
                updated_at as "updated_at: chrono::DateTime<chrono::Utc>",
                is_archived as "is_archived: bool"
            FROM workspaces
            WHERE id = ?
            "#,
            workspace_id
        )
        .fetch_optional(&self.db)
        .await?
        .ok_or_else(|| CollabError::WorkspaceNotFound(workspace_id.to_string()))?;

        // Update cache
        self.cache.write().insert(workspace_id, workspace.clone());

        Ok(workspace)
    }

    /// Update a workspace
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub async fn update_workspace(
        &self,
        workspace_id: Uuid,
        user_id: Uuid,
        name: Option<String>,
        description: Option<String>,
        config: Option<serde_json::Value>,
    ) -> Result<TeamWorkspace> {
        // Check permissions
        let member = self.get_member(workspace_id, user_id).await?;
        PermissionChecker::check(member.role, Permission::WorkspaceUpdate)?;

        let mut workspace = self.get_workspace(workspace_id).await?;

        // Update fields
        if let Some(name) = name {
            workspace.name = name;
        }
        if let Some(description) = description {
            workspace.description = Some(description);
        }
        if let Some(config) = config {
            workspace.config = config;
        }
        workspace.updated_at = Utc::now();
        workspace.version += 1;

        // Save to database
        sqlx::query!(
            r#"
            UPDATE workspaces
            SET name = ?, description = ?, config = ?, version = ?, updated_at = ?
            WHERE id = ?
            "#,
            workspace.name,
            workspace.description,
            workspace.config,
            workspace.version,
            workspace.updated_at,
            workspace.id
        )
        .execute(&self.db)
        .await?;

        // Update cache
        self.cache.write().insert(workspace_id, workspace.clone());

        Ok(workspace)
    }

    /// Delete (archive) a workspace
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub async fn delete_workspace(&self, workspace_id: Uuid, user_id: Uuid) -> Result<()> {
        // Check permissions
        let member = self.get_member(workspace_id, user_id).await?;
        PermissionChecker::check(member.role, Permission::WorkspaceDelete)?;

        let now = Utc::now();
        sqlx::query!(
            r#"
            UPDATE workspaces
            SET is_archived = TRUE, updated_at = ?
            WHERE id = ?
            "#,
            now,
            workspace_id
        )
        .execute(&self.db)
        .await?;

        // Remove from cache
        self.cache.write().remove(&workspace_id);

        Ok(())
    }

    /// Add a member to a workspace
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub async fn add_member(
        &self,
        workspace_id: Uuid,
        user_id: Uuid,
        new_member_id: Uuid,
        role: UserRole,
    ) -> Result<WorkspaceMember> {
        // Check permissions
        let member = self.get_member(workspace_id, user_id).await?;
        PermissionChecker::check(member.role, Permission::InviteMembers)?;

        // Create new member
        let new_member = WorkspaceMember::new(workspace_id, new_member_id, role);

        sqlx::query!(
            r#"
            INSERT INTO workspace_members (id, workspace_id, user_id, role, joined_at, last_activity)
            VALUES (?, ?, ?, ?, ?, ?)
            "#,
            new_member.id,
            new_member.workspace_id,
            new_member.user_id,
            new_member.role,
            new_member.joined_at,
            new_member.last_activity
        )
        .execute(&self.db)
        .await?;

        Ok(new_member)
    }

    /// Remove a member from a workspace
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub async fn remove_member(
        &self,
        workspace_id: Uuid,
        user_id: Uuid,
        member_to_remove: Uuid,
    ) -> Result<()> {
        // Check permissions
        let member = self.get_member(workspace_id, user_id).await?;
        PermissionChecker::check(member.role, Permission::RemoveMembers)?;

        // Don't allow removing the owner
        let workspace = self.get_workspace(workspace_id).await?;
        if member_to_remove == workspace.owner_id {
            return Err(CollabError::InvalidInput("Cannot remove workspace owner".to_string()));
        }

        sqlx::query!(
            r#"
            DELETE FROM workspace_members
            WHERE workspace_id = ? AND user_id = ?
            "#,
            workspace_id,
            member_to_remove
        )
        .execute(&self.db)
        .await?;

        Ok(())
    }

    /// Change a member's role
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub async fn change_role(
        &self,
        workspace_id: Uuid,
        user_id: Uuid,
        member_id: Uuid,
        new_role: UserRole,
    ) -> Result<WorkspaceMember> {
        // Check permissions
        let member = self.get_member(workspace_id, user_id).await?;
        PermissionChecker::check(member.role, Permission::ChangeRoles)?;

        // Don't allow changing the owner's role
        let workspace = self.get_workspace(workspace_id).await?;
        if member_id == workspace.owner_id {
            return Err(CollabError::InvalidInput(
                "Cannot change workspace owner's role".to_string(),
            ));
        }

        sqlx::query!(
            r#"
            UPDATE workspace_members
            SET role = ?
            WHERE workspace_id = ? AND user_id = ?
            "#,
            new_role,
            workspace_id,
            member_id
        )
        .execute(&self.db)
        .await?;

        self.get_member(workspace_id, member_id).await
    }

    /// Get a workspace member
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub async fn get_member(&self, workspace_id: Uuid, user_id: Uuid) -> Result<WorkspaceMember> {
        sqlx::query_as!(
            WorkspaceMember,
            r#"
            SELECT
                id as "id: Uuid",
                workspace_id as "workspace_id: Uuid",
                user_id as "user_id: Uuid",
                role as "role: UserRole",
                joined_at as "joined_at: chrono::DateTime<chrono::Utc>",
                last_activity as "last_activity: chrono::DateTime<chrono::Utc>"
            FROM workspace_members
            WHERE workspace_id = ? AND user_id = ?
            "#,
            workspace_id,
            user_id
        )
        .fetch_optional(&self.db)
        .await?
        .ok_or_else(|| CollabError::AuthorizationFailed("User is not a member".to_string()))
    }

    /// List all members of a workspace
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub async fn list_members(&self, workspace_id: Uuid) -> Result<Vec<WorkspaceMember>> {
        let members = sqlx::query_as!(
            WorkspaceMember,
            r#"
            SELECT
                id as "id: Uuid",
                workspace_id as "workspace_id: Uuid",
                user_id as "user_id: Uuid",
                role as "role: UserRole",
                joined_at as "joined_at: chrono::DateTime<chrono::Utc>",
                last_activity as "last_activity: chrono::DateTime<chrono::Utc>"
            FROM workspace_members
            WHERE workspace_id = ?
            ORDER BY joined_at
            "#,
            workspace_id
        )
        .fetch_all(&self.db)
        .await?;

        Ok(members)
    }

    /// List all workspaces for a user
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub async fn list_user_workspaces(&self, user_id: Uuid) -> Result<Vec<TeamWorkspace>> {
        let workspaces = sqlx::query_as!(
            TeamWorkspace,
            r#"
            SELECT
                w.id as "id: Uuid",
                w.name,
                w.description,
                w.owner_id as "owner_id: Uuid",
                w.config,
                w.version,
                w.created_at as "created_at: chrono::DateTime<chrono::Utc>",
                w.updated_at as "updated_at: chrono::DateTime<chrono::Utc>",
                w.is_archived as "is_archived: bool"
            FROM workspaces w
            INNER JOIN workspace_members m ON w.id = m.workspace_id
            WHERE m.user_id = ? AND w.is_archived = FALSE
            ORDER BY w.updated_at DESC
            "#,
            user_id
        )
        .fetch_all(&self.db)
        .await?;

        Ok(workspaces)
    }

    /// Fork a workspace (create an independent copy)
    ///
    /// Creates a new workspace that is a copy of the source workspace.
    /// The forked workspace has its own ID and can be modified independently.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub async fn fork_workspace(
        &self,
        source_workspace_id: Uuid,
        new_name: Option<String>,
        new_owner_id: Uuid,
        fork_point_commit_id: Option<Uuid>,
    ) -> Result<TeamWorkspace> {
        // Verify user has access to source workspace
        self.get_member(source_workspace_id, new_owner_id).await?;

        // Get source workspace
        let source_workspace = self.get_workspace(source_workspace_id).await?;

        // Create new workspace with copied data
        let mut forked_workspace = TeamWorkspace::new(
            new_name.unwrap_or_else(|| format!("{} (Fork)", source_workspace.name)),
            new_owner_id,
        );
        forked_workspace.description.clone_from(&source_workspace.description);

        // Deep copy the config (workspace data) to ensure independence
        // If we have CoreBridge, we can properly clone the core workspace
        if let Some(core_bridge) = &self.core_bridge {
            // Get the core workspace from source
            if let Ok(mut core_workspace) = core_bridge.team_to_core(&source_workspace) {
                // Generate new IDs for all entities in the forked workspace
                core_workspace.id = forked_workspace.id.to_string();
                core_workspace.name.clone_from(&forked_workspace.name);
                core_workspace.description.clone_from(&forked_workspace.description);
                core_workspace.created_at = forked_workspace.created_at;
                core_workspace.updated_at = forked_workspace.updated_at;

                // Regenerate IDs for folders and requests to ensure independence
                Self::regenerate_entity_ids(&mut core_workspace);

                // Convert back to TeamWorkspace
                if let Ok(team_ws) = core_bridge.core_to_team(&core_workspace, new_owner_id) {
                    forked_workspace.config = team_ws.config;
                } else {
                    // Fallback to shallow copy
                    forked_workspace.config.clone_from(&source_workspace.config);
                }
            } else {
                // Fallback to shallow copy
                forked_workspace.config.clone_from(&source_workspace.config);
            }
        } else {
            // Fallback to shallow copy
            forked_workspace.config = source_workspace.config.clone();
        }

        // Insert forked workspace into database
        sqlx::query!(
            r#"
            INSERT INTO workspaces (id, name, description, owner_id, config, version, created_at, updated_at, is_archived)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            "#,
            forked_workspace.id,
            forked_workspace.name,
            forked_workspace.description,
            forked_workspace.owner_id,
            forked_workspace.config,
            forked_workspace.version,
            forked_workspace.created_at,
            forked_workspace.updated_at,
            forked_workspace.is_archived
        )
        .execute(&self.db)
        .await?;

        // Add owner as admin member
        let member = WorkspaceMember::new(forked_workspace.id, new_owner_id, UserRole::Admin);
        sqlx::query!(
            r#"
            INSERT INTO workspace_members (id, workspace_id, user_id, role, joined_at, last_activity)
            VALUES (?, ?, ?, ?, ?, ?)
            "#,
            member.id,
            member.workspace_id,
            member.user_id,
            member.role,
            member.joined_at,
            member.last_activity
        )
        .execute(&self.db)
        .await?;

        // Create fork relationship record
        let fork = WorkspaceFork::new(
            source_workspace_id,
            forked_workspace.id,
            new_owner_id,
            fork_point_commit_id,
        );
        sqlx::query!(
            r#"
            INSERT INTO workspace_forks (id, source_workspace_id, forked_workspace_id, forked_at, forked_by, fork_point_commit_id)
            VALUES (?, ?, ?, ?, ?, ?)
            "#,
            fork.id,
            fork.source_workspace_id,
            fork.forked_workspace_id,
            fork.forked_at,
            fork.forked_by,
            fork.fork_point_commit_id
        )
        .execute(&self.db)
        .await?;

        // Update cache
        self.cache.write().insert(forked_workspace.id, forked_workspace.clone());

        Ok(forked_workspace)
    }

    /// List all forks of a workspace
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub async fn list_forks(&self, workspace_id: Uuid) -> Result<Vec<WorkspaceFork>> {
        let forks = sqlx::query_as!(
            WorkspaceFork,
            r#"
            SELECT
                id as "id: Uuid",
                source_workspace_id as "source_workspace_id: Uuid",
                forked_workspace_id as "forked_workspace_id: Uuid",
                forked_at as "forked_at: chrono::DateTime<chrono::Utc>",
                forked_by as "forked_by: Uuid",
                fork_point_commit_id as "fork_point_commit_id: Uuid"
            FROM workspace_forks
            WHERE source_workspace_id = ?
            ORDER BY forked_at DESC
            "#,
            workspace_id
        )
        .fetch_all(&self.db)
        .await?;

        Ok(forks)
    }

    /// Get the source workspace for a fork
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub async fn get_fork_source(
        &self,
        forked_workspace_id: Uuid,
    ) -> Result<Option<WorkspaceFork>> {
        let fork = sqlx::query_as!(
            WorkspaceFork,
            r#"
            SELECT
                id as "id: Uuid",
                source_workspace_id as "source_workspace_id: Uuid",
                forked_workspace_id as "forked_workspace_id: Uuid",
                forked_at as "forked_at: chrono::DateTime<chrono::Utc>",
                forked_by as "forked_by: Uuid",
                fork_point_commit_id as "fork_point_commit_id: Uuid"
            FROM workspace_forks
            WHERE forked_workspace_id = ?
            "#,
            forked_workspace_id
        )
        .fetch_optional(&self.db)
        .await?;

        Ok(fork)
    }

    /// Regenerate entity IDs in a core workspace to ensure fork independence
    #[allow(clippy::items_after_statements)]
    fn regenerate_entity_ids(core_workspace: &mut mockforge_core::workspace::Workspace) {
        use mockforge_core::workspace::Folder;
        use uuid::Uuid;

        // Regenerate workspace ID
        core_workspace.id = Uuid::new_v4().to_string();

        // Helper to regenerate folder IDs recursively
        fn regenerate_folder_ids(folder: &mut Folder) {
            folder.id = Uuid::new_v4().to_string();
            for subfolder in &mut folder.folders {
                regenerate_folder_ids(subfolder);
            }
            for request in &mut folder.requests {
                request.id = Uuid::new_v4().to_string();
            }
        }

        // Regenerate IDs for root folders
        for folder in &mut core_workspace.folders {
            regenerate_folder_ids(folder);
        }

        // Regenerate IDs for root requests
        for request in &mut core_workspace.requests {
            request.id = Uuid::new_v4().to_string();
        }
    }
}

/// Workspace manager (higher-level API)
pub struct WorkspaceManager {
    service: Arc<WorkspaceService>,
}

impl WorkspaceManager {
    /// Create a new workspace manager
    #[must_use]
    pub const fn new(service: Arc<WorkspaceService>) -> Self {
        Self { service }
    }

    /// Create and setup a new workspace
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub async fn create_workspace(
        &self,
        name: String,
        description: Option<String>,
        owner_id: Uuid,
    ) -> Result<TeamWorkspace> {
        self.service.create_workspace(name, description, owner_id).await
    }

    /// Get workspace with member check
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub async fn get_workspace(&self, workspace_id: Uuid, user_id: Uuid) -> Result<TeamWorkspace> {
        // Verify user is a member
        self.service.get_member(workspace_id, user_id).await?;
        self.service.get_workspace(workspace_id).await
    }
}

#[cfg(test)]
mod tests {
    // Note: These tests would require a database setup
    // For now, they serve as documentation of the API
}