Skip to main content

vibe_ticket/storage/
file.rs

1use std::fs;
2use std::path::PathBuf;
3use std::sync::Arc;
4
5use crate::cache::TicketCache;
6use crate::core::{Ticket, TicketId};
7
8use crate::error::{ErrorContext, Result, VibeTicketError};
9
10/// File-based storage implementation for tickets
11///
12/// This implementation stores tickets as YAML files in a directory structure
13/// within the project's .vibe-ticket directory.
14#[derive(Clone)]
15pub struct FileStorage {
16    /// Base directory for storing ticket data
17    base_dir: PathBuf,
18    /// Cache for improved performance
19    pub(crate) cache: Arc<TicketCache>,
20}
21
22impl FileStorage {
23    /// Creates a new `FileStorage` instance
24    pub fn new(base_dir: impl Into<PathBuf>) -> Self {
25        Self {
26            base_dir: base_dir.into(),
27            cache: Arc::new(TicketCache::with_default_ttl()),
28        }
29    }
30
31    /// Returns the path to the tickets directory
32    fn tickets_dir(&self) -> PathBuf {
33        self.get_path("tickets")
34    }
35
36    /// Returns the path to a specific ticket file
37    pub(crate) fn ticket_path(&self, id: &TicketId) -> PathBuf {
38        self.tickets_dir().join(format!("{id}.yaml"))
39    }
40
41    /// Returns the path to the active ticket file
42    fn active_ticket_path(&self) -> PathBuf {
43        self.get_path("active_ticket")
44    }
45
46    /// Returns the path to the active tickets file (new format supporting multiple tickets)
47    fn active_tickets_path(&self) -> PathBuf {
48        self.get_path("active_tickets.yaml")
49    }
50
51    /// Returns the path to the project state file
52    fn state_path(&self) -> PathBuf {
53        self.get_path("state.yaml")
54    }
55
56    /// Helper method to get a path relative to base directory
57    fn get_path(&self, name: &str) -> PathBuf {
58        self.base_dir.join(name)
59    }
60
61    /// Ensures the storage directories exist
62    pub fn ensure_directories(&self) -> Result<()> {
63        fs::create_dir_all(self.tickets_dir()).context("Failed to create tickets directory")?;
64        Ok(())
65    }
66
67    /// Saves a ticket to storage with file locking for concurrent access protection
68    pub fn save_ticket(&self, ticket: &Ticket) -> Result<()> {
69        self.ensure_directories()?;
70
71        let path = self.ticket_path(&ticket.id);
72
73        // Acquire lock before modifying the file
74        let _lock =
75            super::FileLock::acquire(&path, Some("save_ticket".to_string())).map_err(|e| {
76                VibeTicketError::custom(format!("Failed to acquire lock for saving ticket: {e}"))
77            })?;
78
79        let yaml = serde_yaml::to_string(ticket).context("Failed to serialize ticket")?;
80
81        fs::write(&path, yaml)
82            .with_context(|| format!("Failed to write ticket to {}", path.display()))?;
83
84        // Invalidate cache for this ticket
85        self.cache.invalidate_ticket(&ticket.id);
86
87        Ok(())
88    }
89
90    /// Loads a ticket from storage by ID with read locking
91    pub fn load_ticket(&self, id: &TicketId) -> Result<Ticket> {
92        // Check cache first
93        if let Some(ticket) = self.cache.get_ticket(id) {
94            return Ok(ticket);
95        }
96
97        let path = self.ticket_path(id);
98
99        if !path.exists() {
100            return Err(VibeTicketError::TicketNotFound { id: id.to_string() });
101        }
102
103        // Acquire lock for reading to ensure consistency
104        let _lock =
105            super::FileLock::acquire(&path, Some("load_ticket".to_string())).map_err(|e| {
106                VibeTicketError::custom(format!("Failed to acquire lock for loading ticket: {e}"))
107            })?;
108
109        let yaml = fs::read_to_string(&path)
110            .with_context(|| format!("Failed to read ticket from {}", path.display()))?;
111
112        let ticket: Ticket = serde_yaml::from_str(&yaml).context("Failed to deserialize ticket")?;
113
114        // Cache the loaded ticket
115        self.cache.cache_ticket(&ticket);
116
117        Ok(ticket)
118    }
119
120    /// Loads all tickets from storage
121    pub fn load_all_tickets(&self) -> Result<Vec<Ticket>> {
122        // Check cache first
123        if let Some(tickets) = self.cache.get_all_tickets() {
124            return Ok(tickets);
125        }
126
127        let tickets_dir = self.tickets_dir();
128
129        if !tickets_dir.exists() {
130            return Ok(Vec::new());
131        }
132
133        let mut tickets = Vec::new();
134
135        for entry in fs::read_dir(&tickets_dir).context("Failed to read tickets directory")? {
136            let entry = entry.context("Failed to read directory entry")?;
137            let path = entry.path();
138
139            if path.extension().and_then(|s| s.to_str()) == Some("yaml") {
140                let yaml = fs::read_to_string(&path)
141                    .with_context(|| format!("Failed to read {}", path.display()))?;
142
143                match serde_yaml::from_str::<Ticket>(&yaml) {
144                    Ok(ticket) => tickets.push(ticket),
145                    Err(e) => {
146                        // Log error but continue loading other tickets
147                        eprintln!(
148                            "Warning: Failed to load ticket from {}: {e}",
149                            path.display()
150                        );
151                    },
152                }
153            }
154        }
155
156        // Cache all loaded tickets
157        self.cache.cache_all_tickets(&tickets);
158
159        Ok(tickets)
160    }
161
162    /// Deletes a ticket from storage with locking
163    pub fn delete_ticket(&self, id: &TicketId) -> Result<()> {
164        let path = self.ticket_path(id);
165
166        if !path.exists() {
167            return Err(VibeTicketError::TicketNotFound { id: id.to_string() });
168        }
169
170        // Acquire lock before deleting
171        let _lock =
172            super::FileLock::acquire(&path, Some("delete_ticket".to_string())).map_err(|e| {
173                VibeTicketError::custom(format!("Failed to acquire lock for deleting ticket: {e}"))
174            })?;
175
176        fs::remove_file(&path)
177            .with_context(|| format!("Failed to delete ticket at {}", path.display()))?;
178
179        // Invalidate cache for this ticket
180        self.cache.invalidate_ticket(id);
181
182        Ok(())
183    }
184
185    /// Sets the active ticket with locking
186    pub fn set_active_ticket(&self, id: &TicketId) -> Result<()> {
187        let path = self.active_ticket_path();
188
189        // Acquire lock for the active ticket file
190        let _lock = super::FileLock::acquire(&path, Some("set_active_ticket".to_string()))
191            .map_err(|e| {
192                VibeTicketError::custom(format!(
193                    "Failed to acquire lock for setting active ticket: {e}"
194                ))
195            })?;
196
197        fs::write(&path, id.to_string()).context("Failed to write active ticket")?;
198        Ok(())
199    }
200
201    /// Gets the active ticket ID
202    pub fn get_active_ticket(&self) -> Result<Option<TicketId>> {
203        let path = self.active_ticket_path();
204
205        if !path.exists() {
206            return Ok(None);
207        }
208
209        let content = fs::read_to_string(&path).context("Failed to read active ticket")?;
210
211        let id = TicketId::parse_str(content.trim()).context("Failed to parse active ticket ID")?;
212
213        Ok(Some(id))
214    }
215
216    /// Clears the active ticket with locking
217    pub fn clear_active_ticket(&self) -> Result<()> {
218        let path = self.active_ticket_path();
219
220        if path.exists() {
221            // Acquire lock before removing
222            let _lock = super::FileLock::acquire(&path, Some("clear_active_ticket".to_string()))
223                .map_err(|e| {
224                    VibeTicketError::custom(format!(
225                        "Failed to acquire lock for clearing active ticket: {e}"
226                    ))
227                })?;
228
229            fs::remove_file(&path).context("Failed to clear active ticket")?;
230        }
231
232        Ok(())
233    }
234
235    /// Adds a ticket to the list of active tickets
236    ///
237    /// This method adds a ticket ID to the active tickets list stored in
238    /// `active_tickets.yaml`. If the file doesn't exist, it creates it.
239    pub fn add_active_ticket(&self, id: &TicketId) -> Result<()> {
240        let path = self.active_tickets_path();
241
242        // Acquire lock for the active tickets file
243        let _lock = super::FileLock::acquire(&path, Some("add_active_ticket".to_string()))
244            .map_err(|e| {
245                VibeTicketError::custom(format!(
246                    "Failed to acquire lock for adding active ticket: {e}"
247                ))
248            })?;
249
250        // Load existing active tickets
251        let mut active_ids = if path.exists() {
252            let content = fs::read_to_string(&path).context("Failed to read active tickets")?;
253            serde_yaml::from_str::<Vec<String>>(&content)
254                .context("Failed to parse active tickets")?
255                .into_iter()
256                .filter_map(|s| TicketId::parse_str(&s).ok())
257                .collect::<Vec<_>>()
258        } else {
259            Vec::new()
260        };
261
262        // Add if not already present
263        if !active_ids.contains(id) {
264            active_ids.push(id.clone());
265        }
266
267        // Save back
268        let yaml = serde_yaml::to_string(
269            &active_ids
270                .iter()
271                .map(|id| id.to_string())
272                .collect::<Vec<_>>(),
273        )
274        .context("Failed to serialize active tickets")?;
275
276        fs::write(&path, yaml).context("Failed to write active tickets")?;
277
278        Ok(())
279    }
280
281    /// Removes a ticket from the list of active tickets
282    pub fn remove_active_ticket(&self, id: &TicketId) -> Result<()> {
283        let path = self.active_tickets_path();
284
285        if !path.exists() {
286            return Ok(()); // Nothing to remove
287        }
288
289        // Acquire lock for the active tickets file
290        let _lock = super::FileLock::acquire(&path, Some("remove_active_ticket".to_string()))
291            .map_err(|e| {
292                VibeTicketError::custom(format!(
293                    "Failed to acquire lock for removing active ticket: {e}"
294                ))
295            })?;
296
297        // Load existing active tickets
298        let content = fs::read_to_string(&path).context("Failed to read active tickets")?;
299        let mut active_ids = serde_yaml::from_str::<Vec<String>>(&content)
300            .context("Failed to parse active tickets")?
301            .into_iter()
302            .filter_map(|s| TicketId::parse_str(&s).ok())
303            .collect::<Vec<_>>();
304
305        // Remove the ticket
306        active_ids.retain(|tid| tid != id);
307
308        if active_ids.is_empty() {
309            // Remove file if no active tickets
310            fs::remove_file(&path).context("Failed to remove active tickets file")?;
311        } else {
312            // Save back
313            let yaml = serde_yaml::to_string(
314                &active_ids
315                    .iter()
316                    .map(|id| id.to_string())
317                    .collect::<Vec<_>>(),
318            )
319            .context("Failed to serialize active tickets")?;
320
321            fs::write(&path, yaml).context("Failed to write active tickets")?;
322        }
323
324        Ok(())
325    }
326
327    /// Gets all active ticket IDs
328    ///
329    /// This method reads from both the new `active_tickets.yaml` and legacy
330    /// `active_ticket` files for backward compatibility.
331    pub fn get_all_active_tickets(&self) -> Result<Vec<TicketId>> {
332        let mut active_ids = Vec::new();
333
334        // Try new format first
335        let new_path = self.active_tickets_path();
336        if new_path.exists() {
337            let content = fs::read_to_string(&new_path).context("Failed to read active tickets")?;
338            active_ids = serde_yaml::from_str::<Vec<String>>(&content)
339                .context("Failed to parse active tickets")?
340                .into_iter()
341                .filter_map(|s| TicketId::parse_str(&s).ok())
342                .collect();
343        } else {
344            // Fall back to legacy format
345            if let Some(id) = self.get_active_ticket()? {
346                active_ids.push(id);
347            }
348        }
349
350        Ok(active_ids)
351    }
352
353    /// Checks if a ticket with the given slug already exists
354    pub fn ticket_exists_with_slug(&self, slug: &str) -> Result<bool> {
355        let tickets = self.load_all_tickets()?;
356        Ok(tickets.iter().any(|t| t.slug == slug))
357    }
358
359    /// Finds a ticket by its slug
360    pub fn find_ticket_by_slug(&self, slug: &str) -> Result<Option<Ticket>> {
361        let tickets = self.load_all_tickets()?;
362        Ok(tickets.into_iter().find(|t| t.slug == slug))
363    }
364}
365
366/// Project state stored in the .vibe-ticket directory
367#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
368pub struct ProjectState {
369    /// Project name
370    pub name: String,
371
372    /// Project description
373    pub description: Option<String>,
374
375    /// Creation timestamp
376    pub created_at: chrono::DateTime<chrono::Utc>,
377
378    /// Last modified timestamp
379    pub updated_at: chrono::DateTime<chrono::Utc>,
380
381    /// Total number of tickets created (for ID generation)
382    pub ticket_count: u64,
383}
384
385impl FileStorage {
386    /// Saves the project state
387    pub fn save_state(&self, state: &ProjectState) -> Result<()> {
388        let path = self.state_path();
389        let yaml = serde_yaml::to_string(state).context("Failed to serialize project state")?;
390
391        fs::write(&path, yaml).context("Failed to write project state")?;
392
393        Ok(())
394    }
395
396    /// Loads the project state
397    pub fn load_state(&self) -> Result<ProjectState> {
398        let path = self.state_path();
399
400        if !path.exists() {
401            return Err(VibeTicketError::ProjectNotInitialized);
402        }
403
404        let yaml = fs::read_to_string(&path).context("Failed to read project state")?;
405
406        let state: ProjectState =
407            serde_yaml::from_str(&yaml).context("Failed to deserialize project state")?;
408
409        Ok(state)
410    }
411}
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416    use tempfile::TempDir;
417
418    fn create_test_storage() -> (FileStorage, TempDir) {
419        let temp_dir = TempDir::new().unwrap();
420        let storage = FileStorage::new(temp_dir.path());
421        (storage, temp_dir)
422    }
423
424    #[test]
425    fn test_save_and_load_ticket() {
426        let (storage, _temp) = create_test_storage();
427        let mut ticket = Ticket::new("test-ticket", "Test Ticket");
428        ticket.description = "Test description".to_string();
429
430        storage.save_ticket(&ticket).unwrap();
431        let loaded = storage.load_ticket(&ticket.id).unwrap();
432
433        assert_eq!(loaded.slug, ticket.slug);
434        assert_eq!(loaded.title, ticket.title);
435        assert_eq!(loaded.description, ticket.description);
436    }
437
438    #[test]
439    fn test_load_all_tickets() {
440        let (storage, _temp) = create_test_storage();
441
442        let first_ticket = Ticket::new("ticket-1", "Ticket 1");
443        let second_ticket = Ticket::new("ticket-2", "Ticket 2");
444
445        storage.save_ticket(&first_ticket).unwrap();
446        storage.save_ticket(&second_ticket).unwrap();
447
448        let all_tickets = storage.load_all_tickets().unwrap();
449        assert_eq!(all_tickets.len(), 2);
450    }
451
452    #[test]
453    fn test_active_ticket() {
454        let (storage, _temp) = create_test_storage();
455        let ticket = Ticket::new("test", "Test");
456
457        storage.save_ticket(&ticket).unwrap();
458        storage.set_active_ticket(&ticket.id).unwrap();
459
460        let active_id = storage.get_active_ticket().unwrap();
461        assert_eq!(active_id, Some(ticket.id));
462
463        storage.clear_active_ticket().unwrap();
464        let active_id = storage.get_active_ticket().unwrap();
465        assert_eq!(active_id, None);
466    }
467}
468// Include concurrent tests
469#[cfg(test)]
470#[path = "concurrent_tests.rs"]
471mod concurrent_tests;