summaryrefslogtreecommitdiff
path: root/src/cache/data_file.rs
blob: c193d9cb58d52df7c5b7096303abce3966468983 (plain)
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
use crate::cache::cache::CacheEntry;
use crate::error::{SpandxError, SpandxResult};
use camino::{Utf8Path, Utf8PathBuf};
use tokio::fs::{File, OpenOptions};
use tokio::io::{AsyncBufReadExt, AsyncSeekExt, AsyncWriteExt, BufReader};
use tracing::{debug, warn};

/// Handles CSV data files containing package information
#[derive(Debug)]
pub struct DataFile {
    path: Utf8PathBuf,
    file: Option<File>,
    current_offset: u64,
}

impl DataFile {
    pub async fn create<P: AsRef<Utf8Path>>(path: P) -> SpandxResult<Self> {
        let path = path.as_ref().to_path_buf();
        
        // Ensure parent directory exists
        if let Some(parent) = path.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }
        
        let file = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(&path)
            .await?;
            
        Ok(Self {
            path,
            file: Some(file),
            current_offset: 0,
        })
    }

    pub async fn open<P: AsRef<Utf8Path>>(path: P) -> SpandxResult<Self> {
        let path = path.as_ref().to_path_buf();
        
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .open(&path)
            .await?;
            
        Ok(Self {
            path,
            file: Some(file),
            current_offset: 0,
        })
    }

    pub fn current_offset(&self) -> u64 {
        self.current_offset
    }

    pub async fn append_entry(&mut self, entry: &CacheEntry) -> SpandxResult<()> {
        if let Some(ref mut file) = self.file {
            let csv_line = entry.to_csv_line();
            let line_with_newline = format!("{}\n", csv_line);
            
            file.write_all(line_with_newline.as_bytes()).await?;
            file.flush().await?;
            
            self.current_offset += line_with_newline.len() as u64;
            
            debug!("Appended entry to {}: {}", self.path, csv_line);
        } else {
            return Err(SpandxError::CacheError {
                operation: "append_entry".to_string(),
                source: Some(Box::new(std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    "Data file not open for writing"
                )))
            });
        }
        
        Ok(())
    }

    pub async fn read_entry_at_offset(&self, offset: u64) -> SpandxResult<Option<CacheEntry>> {
        let file = File::open(&self.path).await?;
        let mut reader = BufReader::new(file);
        
        reader.seek(std::io::SeekFrom::Start(offset)).await?;
        
        let mut line = String::new();
        let bytes_read = reader.read_line(&mut line).await?;
        
        if bytes_read == 0 {
            return Ok(None);
        }
        
        // Remove trailing newline
        if line.ends_with('\n') {
            line.pop();
        }
        if line.ends_with('\r') {
            line.pop();
        }
        
        match CacheEntry::from_csv_line(&line) {
            Ok(entry) => Ok(Some(entry)),
            Err(e) => {
                warn!("Failed to parse CSV line at offset {}: {} - {}", offset, line, e);
                Ok(None)
            }
        }
    }

    pub async fn read_all_entries(&self) -> SpandxResult<Vec<CacheEntry>> {
        let file = File::open(&self.path).await?;
        let reader = BufReader::new(file);
        let mut lines = reader.lines();
        let mut entries = Vec::new();
        
        while let Some(line) = lines.next_line().await? {
            if !line.trim().is_empty() {
                match CacheEntry::from_csv_line(&line) {
                    Ok(entry) => entries.push(entry),
                    Err(e) => {
                        warn!("Failed to parse CSV line: {} - {}", line, e);
                    }
                }
            }
        }
        
        Ok(entries)
    }

    pub async fn count_entries(&self) -> SpandxResult<usize> {
        let file = File::open(&self.path).await?;
        let reader = BufReader::new(file);
        let mut lines = reader.lines();
        let mut count = 0;
        
        while let Some(line) = lines.next_line().await? {
            if !line.trim().is_empty() {
                count += 1;
            }
        }
        
        Ok(count)
    }

    pub async fn iterate_entries<F>(&self, mut callback: F) -> SpandxResult<()>
    where
        F: FnMut(&CacheEntry) -> bool, // Return false to stop iteration
    {
        let file = File::open(&self.path).await?;
        let reader = BufReader::new(file);
        let mut lines = reader.lines();
        
        while let Some(line) = lines.next_line().await? {
            if !line.trim().is_empty() {
                match CacheEntry::from_csv_line(&line) {
                    Ok(entry) => {
                        if !callback(&entry) {
                            break;
                        }
                    }
                    Err(e) => {
                        warn!("Failed to parse CSV line during iteration: {} - {}", line, e);
                    }
                }
            }
        }
        
        Ok(())
    }

    pub fn path(&self) -> &Utf8Path {
        &self.path
    }
}

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

    #[tokio::test]
    async fn test_data_file_create_and_append() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = Utf8PathBuf::from_path_buf(temp_dir.path().join("test.csv")).unwrap();
        
        let mut data_file = DataFile::create(&file_path).await.unwrap();
        
        let entry = CacheEntry::new(
            "rails".to_string(),
            "7.0.0".to_string(),
            vec!["MIT".to_string()],
        );
        
        let initial_offset = data_file.current_offset();
        data_file.append_entry(&entry).await.unwrap();
        
        assert!(data_file.current_offset() > initial_offset);
        assert!(file_path.exists());
    }

    #[tokio::test]
    async fn test_data_file_read_entry_at_offset() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = Utf8PathBuf::from_path_buf(temp_dir.path().join("test.csv")).unwrap();
        
        let mut data_file = DataFile::create(&file_path).await.unwrap();
        
        let entry1 = CacheEntry::new(
            "rails".to_string(),
            "7.0.0".to_string(),
            vec!["MIT".to_string()],
        );
        let entry2 = CacheEntry::new(
            "sinatra".to_string(),
            "2.0.0".to_string(),
            vec!["MIT".to_string(), "Apache-2.0".to_string()],
        );
        
        let offset1 = data_file.current_offset();
        data_file.append_entry(&entry1).await.unwrap();
        
        let offset2 = data_file.current_offset();
        data_file.append_entry(&entry2).await.unwrap();
        
        // Read entries back
        let read_entry1 = data_file.read_entry_at_offset(offset1).await.unwrap().unwrap();
        let read_entry2 = data_file.read_entry_at_offset(offset2).await.unwrap().unwrap();
        
        assert_eq!(read_entry1, entry1);
        assert_eq!(read_entry2, entry2);
    }

    #[tokio::test]
    async fn test_data_file_read_all_entries() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = Utf8PathBuf::from_path_buf(temp_dir.path().join("test.csv")).unwrap();
        
        let mut data_file = DataFile::create(&file_path).await.unwrap();
        
        let entries = vec![
            CacheEntry::new("rails".to_string(), "7.0.0".to_string(), vec!["MIT".to_string()]),
            CacheEntry::new("sinatra".to_string(), "2.0.0".to_string(), vec!["MIT".to_string()]),
            CacheEntry::new("rack".to_string(), "2.0.0".to_string(), vec!["MIT".to_string()]),
        ];
        
        for entry in &entries {
            data_file.append_entry(entry).await.unwrap();
        }
        
        let read_entries = data_file.read_all_entries().await.unwrap();
        assert_eq!(read_entries, entries);
    }

    #[tokio::test]
    async fn test_data_file_count_entries() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = Utf8PathBuf::from_path_buf(temp_dir.path().join("test.csv")).unwrap();
        
        let mut data_file = DataFile::create(&file_path).await.unwrap();
        
        assert_eq!(data_file.count_entries().await.unwrap(), 0);
        
        data_file.append_entry(&CacheEntry::new("rails".to_string(), "7.0.0".to_string(), vec!["MIT".to_string()])).await.unwrap();
        assert_eq!(data_file.count_entries().await.unwrap(), 1);
        
        data_file.append_entry(&CacheEntry::new("sinatra".to_string(), "2.0.0".to_string(), vec!["MIT".to_string()])).await.unwrap();
        assert_eq!(data_file.count_entries().await.unwrap(), 2);
    }

    #[tokio::test]
    async fn test_data_file_iterate_entries() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = Utf8PathBuf::from_path_buf(temp_dir.path().join("test.csv")).unwrap();
        
        let mut data_file = DataFile::create(&file_path).await.unwrap();
        
        let entries = vec![
            CacheEntry::new("rails".to_string(), "7.0.0".to_string(), vec!["MIT".to_string()]),
            CacheEntry::new("sinatra".to_string(), "2.0.0".to_string(), vec!["MIT".to_string()]),
            CacheEntry::new("rack".to_string(), "2.0.0".to_string(), vec!["MIT".to_string()]),
        ];
        
        for entry in &entries {
            data_file.append_entry(entry).await.unwrap();
        }
        
        let mut collected_entries = Vec::new();
        data_file.iterate_entries(|entry| {
            collected_entries.push(entry.clone());
            true // Continue iteration
        }).await.unwrap();
        
        assert_eq!(collected_entries, entries);
        
        // Test early termination
        let mut limited_entries = Vec::new();
        data_file.iterate_entries(|entry| {
            limited_entries.push(entry.clone());
            limited_entries.len() < 2 // Stop after 2 entries
        }).await.unwrap();
        
        assert_eq!(limited_entries.len(), 2);
    }
}