hyprstream_core/services/
editing.rs1use 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
23use hyprstream_rpc_std::registry_client::DocFormat;
26
27pub 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
39pub type DocKey = (String, String, String);
41
42pub struct EditingTable {
44 docs: DashMap<DocKey, Arc<Mutex<SharedDoc>>>,
46 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 #[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 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 {
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 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 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 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 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 pub fn on_clunk(&self, client_id: &str, fid: u32) {
193 self.close(client_id, fid);
194 }
195
196 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 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
210pub 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
224pub 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}