Skip to main content

hyprstream_core/services/
editing.rs

1//! CRDT-based collaborative file editing.
2//!
3//! Provides a shared document model using automerge for collaborative editing
4//! of files within worktrees. Multiple clients can edit the same file via
5//! separate fids, sharing a single `AutoCommit` document.
6//!
7//! ## Session lifecycle
8//!
9//! 1. `editOpen` — Read file, hash it, initialize automerge doc, create session
10//! 2. `editState` — Serialize current automerge doc state to text (TOML/JSON/etc.)
11//! 3. `editApply` — Apply automerge changes from a client
12//! 4. `flush` — Write automerge state back to disk (atomic, checks file_hash)
13//! 5. `editClose` — Close this client's session (decrements client_count)
14
15use automerge::transaction::Transactable;
16use automerge::AutoCommit;
17use dashmap::DashMap;
18use parking_lot::Mutex;
19use sha2::{Digest, Sha256};
20use std::sync::Arc;
21use tracing::{debug, warn};
22
23/// Document format for parsing/serialization.
24///
25use hyprstream_rpc_std::registry_client::DocFormat;
26
27/// Shared CRDT document for a file, accessed by multiple clients.
28///
29/// Always accessed through `Arc<Mutex<SharedDoc>>` — no inner locks needed.
30pub struct SharedDoc {
31    pub doc: AutoCommit,
32    pub path: String,
33    pub format: DocFormat,
34    pub dirty: bool,
35    pub file_hash: [u8; 32],
36    pub client_count: usize,
37}
38
39/// Canonical key for a shared document: (repo_id, worktree_name, normalized_path).
40pub type DocKey = (String, String, String);
41
42/// Table of active CRDT editing sessions.
43pub struct EditingTable {
44    /// Shared docs keyed by canonical file identity.
45    docs: DashMap<DocKey, Arc<Mutex<SharedDoc>>>,
46    /// Maps (client_identity, fid) → DocKey for session lookup and cleanup.
47    sessions: DashMap<(String, u32), DocKey>,
48}
49
50impl Default for EditingTable {
51    fn default() -> Self {
52        Self::new()
53    }
54}
55
56impl EditingTable {
57    pub fn new() -> Self {
58        Self {
59            docs: DashMap::new(),
60            sessions: DashMap::new(),
61        }
62    }
63
64    /// Open (or join) a CRDT editing session for a file.
65    ///
66    /// If no shared doc exists for this file, creates one from `content`.
67    /// If one already exists, increments client_count and returns it.
68    ///
69    /// Returns error if `(client_id, fid)` already has an active session.
70    #[allow(clippy::too_many_arguments)]
71    pub fn open(
72        &self,
73        client_id: &str,
74        fid: u32,
75        repo_id: &str,
76        worktree: &str,
77        rel_path: &str,
78        format: DocFormat,
79        content: &str,
80    ) -> Result<Arc<Mutex<SharedDoc>>, String> {
81        let session_key = (client_id.to_owned(), fid);
82        if self.sessions.contains_key(&session_key) {
83            return Err(format!("fid {} already has an active editing session", fid));
84        }
85
86        let doc_key: DocKey = (
87            repo_id.to_owned(),
88            worktree.to_owned(),
89            normalize_path(rel_path),
90        );
91
92        let shared = self.docs.entry(doc_key.clone()).or_insert_with(|| {
93            let mut doc = AutoCommit::new();
94            // Store the file content as a text value in the automerge doc
95            doc.put(automerge::ROOT, "content", content).ok();
96            let hash = sha256_hash(content.as_bytes());
97            debug!("Created new shared doc for {}:{}", worktree, rel_path);
98            Arc::new(Mutex::new(SharedDoc {
99                doc,
100                path: normalize_path(rel_path),
101                format,
102                dirty: false,
103                file_hash: hash,
104                client_count: 0,
105            }))
106        });
107
108        // Increment client count
109        {
110            let mut sd = shared.lock();
111            sd.client_count += 1;
112        }
113
114        self.sessions.insert(session_key, doc_key);
115        Ok(Arc::clone(&shared))
116    }
117
118    /// Get the shared doc for a client's active session.
119    pub fn get_session(&self, client_id: &str, fid: u32) -> Option<Arc<Mutex<SharedDoc>>> {
120        let session_key = (client_id.to_owned(), fid);
121        let doc_key = self.sessions.get(&session_key)?;
122        let shared = self.docs.get(&*doc_key)?;
123        Some(Arc::clone(&shared))
124    }
125
126    /// Check if a file has an active editing session (by any client).
127    pub fn has_active_session(&self, repo_id: &str, worktree: &str, rel_path: &str) -> bool {
128        let doc_key: DocKey = (
129            repo_id.to_owned(),
130            worktree.to_owned(),
131            normalize_path(rel_path),
132        );
133        self.docs.contains_key(&doc_key)
134    }
135
136    /// Close a client's editing session. Decrements client_count.
137    /// Removes the shared doc if count reaches 0.
138    ///
139    /// Returns true if the session existed and was closed.
140    pub fn close(&self, client_id: &str, fid: u32) -> bool {
141        let session_key = (client_id.to_owned(), fid);
142        let Some((_, doc_key)) = self.sessions.remove(&session_key) else {
143            return false;
144        };
145
146        let should_remove = {
147            if let Some(shared) = self.docs.get(&doc_key) {
148                let mut sd = shared.lock();
149                sd.client_count = sd.client_count.saturating_sub(1);
150                sd.client_count == 0
151            } else {
152                false
153            }
154        };
155
156        if should_remove {
157            self.docs.remove(&doc_key);
158            debug!("Removed shared doc (last client closed): {:?}", doc_key);
159        }
160
161        true
162    }
163
164    /// Called when a fid is reaped by the idle reaper.
165    /// Logs a warning if the session was dirty.
166    pub fn on_reap(&self, client_id: &str, fid: u32) {
167        let session_key = (client_id.to_owned(), fid);
168        if let Some((_, doc_key)) = self.sessions.remove(&session_key) {
169            let should_remove = {
170                if let Some(shared) = self.docs.get(&doc_key) {
171                    let mut sd = shared.lock();
172                    if sd.dirty {
173                        warn!(
174                            "Reaping fid {} with dirty editing session for {:?}",
175                            fid, doc_key
176                        );
177                    }
178                    sd.client_count = sd.client_count.saturating_sub(1);
179                    sd.client_count == 0
180                } else {
181                    false
182                }
183            };
184
185            if should_remove {
186                self.docs.remove(&doc_key);
187            }
188        }
189    }
190
191    /// Called when a fid is clunked. Same as close but explicit name.
192    pub fn on_clunk(&self, client_id: &str, fid: u32) {
193        self.close(client_id, fid);
194    }
195
196    /// Check if a specific fid has an active editing session for the given file path.
197    /// Used by handle_write to guard against direct writes to CRDT-edited files.
198    pub fn fid_has_session(&self, client_id: &str, fid: u32) -> bool {
199        let session_key = (client_id.to_owned(), fid);
200        self.sessions.contains_key(&session_key)
201    }
202
203    /// Check if a file at the given path has any active editing session.
204    /// Used by handle_write to guard against direct writes to CRDT-edited files.
205    pub fn file_has_session(&self, repo_id: &str, worktree: &str, rel_path: &str) -> bool {
206        self.has_active_session(repo_id, worktree, rel_path)
207    }
208}
209
210/// Normalize a path: no leading `./`, no trailing `/`, POSIX separators.
211pub fn normalize_path(path: &str) -> String {
212    let p = path
213        .replace('\\', "/")
214        .trim_start_matches("./")
215        .trim_end_matches('/')
216        .to_owned();
217    if p.is_empty() {
218        ".".to_owned()
219    } else {
220        p
221    }
222}
223
224/// SHA-256 hash of bytes.
225pub fn sha256_hash(data: &[u8]) -> [u8; 32] {
226    let mut hasher = Sha256::new();
227    hasher.update(data);
228    let result = hasher.finalize();
229    let mut hash = [0u8; 32];
230    hash.copy_from_slice(&result);
231    hash
232}