ryo-storage 0.1.0

Persistent storage and transaction log for RYO
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
//! Project index for tracking imported projects.
//!
//! Maintains a registry of projects imported into Ryo's management.
//!
//! # Server Management
//!
//! Each project has an associated socket path for its ryo server.
//! Socket path is derived from project_id: `/tmp/ryo-{project_id[..8]}.sock`
//!
//! # Per-Project Server Options
//!
//! Projects can override global server settings via `server_options`:
//! - `watch`: Enable file watching for auto-reload
//! - `watch_debounce_ms`: Debounce duration for file watcher

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Per-project server options (overrides global config)
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct ProjectServerOptions {
    /// Watch for file changes and auto-reload (None = use global default)
    pub watch: Option<bool>,

    /// Debounce duration for file watcher in milliseconds (None = use global default)
    pub watch_debounce_ms: Option<u64>,
}

/// Check if a process is alive by PID.
#[cfg(unix)]
pub fn is_process_alive(pid: u32) -> bool {
    use std::process::Command;
    Command::new("kill")
        .args(["-0", &pid.to_string()])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

#[cfg(not(unix))]
pub fn is_process_alive(_pid: u32) -> bool {
    // On non-unix, assume alive (conservative)
    true
}

/// Metadata for an imported project.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectMeta {
    /// Unique project identifier (UUID).
    pub project_id: String,
    /// Display name of the project.
    pub name: String,
    /// Project path on disk.
    pub path: PathBuf,
    /// When the project was imported (ISO 8601).
    pub imported_at: String,
    /// Last time the project was accessed.
    pub last_accessed: String,
    /// Number of files in the project.
    pub file_count: usize,
    /// Total lines of code.
    pub total_lines: usize,
    /// Description (from ryo.toml or auto-generated).
    pub description: Option<String>,
    /// Tags for categorization.
    #[serde(default)]
    pub tags: Vec<String>,
    /// Whether ryo.toml exists.
    pub has_config: bool,
    /// Unix socket path for this project's server.
    /// Generated from project_id: /tmp/ryo-{project_id[..8]}.sock
    #[serde(default)]
    pub socket: Option<PathBuf>,
    /// Process ID of the running server (None if not running).
    #[serde(default)]
    pub server_pid: Option<u32>,
    /// Per-project server options (overrides global config).
    #[serde(default)]
    pub server_options: ProjectServerOptions,
}

impl ProjectMeta {
    /// Create new project metadata.
    ///
    /// The path is automatically canonicalized to ensure consistent lookups.
    /// If canonicalization fails (e.g., path doesn't exist), the original path is used.
    pub fn new(
        project_id: String,
        name: String,
        path: PathBuf,
        file_count: usize,
        total_lines: usize,
    ) -> Self {
        let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
        let socket = Self::generate_socket_path(&project_id);
        // Canonicalize path for consistent lookups
        let canonical_path = path.canonicalize().unwrap_or(path);
        Self {
            project_id,
            name,
            path: canonical_path,
            imported_at: now.clone(),
            last_accessed: now,
            file_count,
            total_lines,
            description: None,
            tags: Vec::new(),
            has_config: false,
            socket: Some(socket),
            server_pid: None,
            server_options: ProjectServerOptions::default(),
        }
    }

    /// Generate socket path from project ID.
    /// Format: /tmp/ryo-{project_id[..8]}.sock
    pub fn generate_socket_path(project_id: &str) -> PathBuf {
        let short_id = &project_id[..8.min(project_id.len())];
        PathBuf::from(format!("/tmp/ryo-{}.sock", short_id))
    }

    /// Get socket path, generating if not set.
    pub fn socket_path(&self) -> PathBuf {
        self.socket
            .clone()
            .unwrap_or_else(|| Self::generate_socket_path(&self.project_id))
    }

    /// Check if server is running (process exists).
    pub fn is_server_running(&self) -> bool {
        if let Some(pid) = self.server_pid {
            is_process_alive(pid)
        } else {
            false
        }
    }

    /// Set server PID.
    pub fn set_server_pid(&mut self, pid: Option<u32>) {
        self.server_pid = pid;
    }

    /// Clear server PID if process is dead.
    pub fn cleanup_dead_server(&mut self) -> bool {
        if let Some(pid) = self.server_pid {
            if !is_process_alive(pid) {
                self.server_pid = None;
                return true;
            }
        }
        false
    }

    /// Update last accessed time.
    pub fn touch(&mut self) {
        self.last_accessed = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
    }

    /// Add a description.
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    /// Add tags.
    pub fn with_tags(mut self, tags: Vec<String>) -> Self {
        self.tags = tags;
        self
    }

    /// Set config presence.
    pub fn with_config(mut self, has_config: bool) -> Self {
        self.has_config = has_config;
        self
    }
}

/// Index of all imported projects.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProjectIndex {
    /// All projects, keyed by project ID.
    projects: HashMap<String, ProjectMeta>,
    /// Projects indexed by path for fast lookup.
    #[serde(skip)]
    by_path: HashMap<PathBuf, String>,
    /// Index version for future migrations.
    #[serde(default = "default_version")]
    version: u32,
}

fn default_version() -> u32 {
    1
}

impl ProjectIndex {
    /// Create a new empty index.
    pub fn new() -> Self {
        Self {
            projects: HashMap::new(),
            by_path: HashMap::new(),
            version: 1,
        }
    }

    /// Add a project to the index.
    pub fn add(&mut self, meta: ProjectMeta) {
        let project_id = meta.project_id.clone();
        let path = meta.path.clone();

        self.projects.insert(project_id.clone(), meta);
        self.by_path.insert(path, project_id);
    }

    /// Remove a project from the index.
    pub fn remove(&mut self, project_id: &str) -> Option<ProjectMeta> {
        if let Some(meta) = self.projects.remove(project_id) {
            self.by_path.remove(&meta.path);
            Some(meta)
        } else {
            None
        }
    }

    /// Get a project by ID.
    ///
    /// Supports both full UUID and short ID prefix (minimum 4 characters).
    pub fn get(&self, project_id: &str) -> Option<&ProjectMeta> {
        // Try exact match first
        if let Some(meta) = self.projects.get(project_id) {
            return Some(meta);
        }

        // Try prefix match for short IDs (minimum 4 chars to avoid ambiguity)
        if project_id.len() >= 4 {
            let matches: Vec<_> = self
                .projects
                .iter()
                .filter(|(id, _)| id.starts_with(project_id))
                .collect();

            if matches.len() == 1 {
                return Some(matches[0].1);
            }
        }

        None
    }

    /// Get a mutable project by ID.
    ///
    /// Supports both full UUID and short ID prefix (minimum 4 characters).
    pub fn get_mut(&mut self, project_id: &str) -> Option<&mut ProjectMeta> {
        // Try exact match first
        if self.projects.contains_key(project_id) {
            return self.projects.get_mut(project_id);
        }

        // Try prefix match for short IDs
        if project_id.len() >= 4 {
            let matching_id = self
                .projects
                .keys()
                .find(|id| id.starts_with(project_id))
                .cloned();

            if let Some(id) = matching_id {
                // Verify it's the only match
                let count = self
                    .projects
                    .keys()
                    .filter(|k| k.starts_with(project_id))
                    .count();
                if count == 1 {
                    return self.projects.get_mut(&id);
                }
            }
        }

        None
    }

    /// Get a project by path.
    ///
    /// The input path is canonicalized before lookup to ensure consistent matching.
    pub fn get_by_path(&self, path: &Path) -> Option<&ProjectMeta> {
        // Try with canonicalized path first
        if let Ok(canonical) = path.canonicalize() {
            if let Some(id) = self.by_path.get(&canonical) {
                return self.projects.get(id);
            }
        }

        // Fall back to direct lookup (for paths that don't exist on disk)
        self.by_path.get(path).and_then(|id| self.projects.get(id))
    }

    /// Check if a project with the given path exists.
    ///
    /// The input path is canonicalized before lookup.
    pub fn contains_path(&self, path: &Path) -> bool {
        // Try with canonicalized path first
        if let Ok(canonical) = path.canonicalize() {
            if self.by_path.contains_key(&canonical) {
                return true;
            }
        }

        // Fall back to direct lookup
        self.by_path.contains_key(path)
    }

    /// List all projects, sorted by last accessed (most recent first).
    pub fn list(&self) -> Vec<&ProjectMeta> {
        let mut projects: Vec<_> = self.projects.values().collect();
        projects.sort_by(|a, b| b.last_accessed.cmp(&a.last_accessed));
        projects
    }

    /// List projects by import date (newest first).
    pub fn list_by_import_date(&self) -> Vec<&ProjectMeta> {
        let mut projects: Vec<_> = self.projects.values().collect();
        projects.sort_by(|a, b| b.imported_at.cmp(&a.imported_at));
        projects
    }

    /// Search projects by name pattern.
    pub fn search_by_name(&self, pattern: &str) -> Vec<&ProjectMeta> {
        let pattern_lower = pattern.to_lowercase();
        self.projects
            .values()
            .filter(|p| p.name.to_lowercase().contains(&pattern_lower))
            .collect()
    }

    /// Search projects by tags.
    pub fn search_by_tags(&self, tags: &[String]) -> Vec<&ProjectMeta> {
        self.projects
            .values()
            .filter(|p| tags.iter().any(|t| p.tags.contains(t)))
            .collect()
    }

    /// Count total projects.
    pub fn count(&self) -> usize {
        self.projects.len()
    }

    /// Rebuild the by_path index (call after deserialization).
    pub fn rebuild_path_index(&mut self) {
        self.by_path.clear();
        for (project_id, meta) in &self.projects {
            self.by_path.insert(meta.path.clone(), project_id.clone());
        }
    }

    /// Cleanup all dead server PIDs.
    ///
    /// Checks each project's server_pid and clears it if the process is no longer running.
    /// Returns the number of projects that were cleaned up.
    pub fn cleanup_dead_servers(&mut self) -> usize {
        let mut cleaned = 0;
        for meta in self.projects.values_mut() {
            if meta.cleanup_dead_server() {
                cleaned += 1;
            }
        }
        cleaned
    }

    /// Get total lines of code across all projects.
    pub fn total_lines(&self) -> usize {
        self.projects.values().map(|p| p.total_lines).sum()
    }

    /// Get total file count across all projects.
    pub fn total_files(&self) -> usize {
        self.projects.values().map(|p| p.file_count).sum()
    }
}

// Custom deserialize to rebuild path index
impl<'de> serde::de::Deserialize<'de> for ProjectIndex {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::de::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct IndexData {
            projects: HashMap<String, ProjectMeta>,
            #[serde(default = "default_version")]
            version: u32,
        }

        let data = IndexData::deserialize(deserializer)?;
        let mut index = ProjectIndex {
            projects: data.projects,
            by_path: HashMap::new(),
            version: data.version,
        };
        index.rebuild_path_index();
        Ok(index)
    }
}

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

    fn create_test_meta(id: &str, name: &str, path: &str) -> ProjectMeta {
        ProjectMeta {
            project_id: id.to_string(),
            name: name.to_string(),
            path: PathBuf::from(path),
            imported_at: "2024-01-01T10:00:00Z".to_string(),
            last_accessed: "2024-01-01T10:00:00Z".to_string(),
            file_count: 10,
            total_lines: 500,
            description: None,
            tags: Vec::new(),
            has_config: false,
            socket: Some(ProjectMeta::generate_socket_path(id)),
            server_pid: None,
            server_options: ProjectServerOptions::default(),
        }
    }

    #[test]
    fn test_add_and_get() {
        let mut index = ProjectIndex::new();
        let meta = create_test_meta("p1", "MyProject", "/projects/my-project");
        index.add(meta);

        assert!(index.get("p1").is_some());
        assert!(index.get("p2").is_none());
    }

    #[test]
    fn test_get_by_path() {
        let mut index = ProjectIndex::new();
        index.add(create_test_meta("p1", "MyProject", "/projects/my-project"));

        assert!(index
            .get_by_path(Path::new("/projects/my-project"))
            .is_some());
        assert!(index.get_by_path(Path::new("/other/path")).is_none());
    }

    #[test]
    fn test_remove() {
        let mut index = ProjectIndex::new();
        index.add(create_test_meta("p1", "MyProject", "/projects/my-project"));

        let removed = index.remove("p1");
        assert!(removed.is_some());
        assert!(index.get("p1").is_none());
        assert!(!index.contains_path(Path::new("/projects/my-project")));
    }

    #[test]
    fn test_search_by_name() {
        let mut index = ProjectIndex::new();
        index.add(create_test_meta("p1", "TodoApp", "/projects/todo"));
        index.add(create_test_meta("p2", "WebServer", "/projects/web"));
        index.add(create_test_meta("p3", "TodoBackend", "/projects/todo-be"));

        let results = index.search_by_name("todo");
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_serialization_roundtrip() {
        let mut index = ProjectIndex::new();
        index.add(create_test_meta("p1", "Project1", "/path/1"));
        index.add(create_test_meta("p2", "Project2", "/path/2"));

        let json = serde_json::to_string(&index).unwrap();
        let restored: ProjectIndex = serde_json::from_str(&json).unwrap();

        assert_eq!(restored.count(), 2);
        assert!(restored.get("p1").is_some());
        assert!(restored.get_by_path(Path::new("/path/2")).is_some());
    }
}