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
use std::fs::{File, OpenOptions};
use std::io::{self, BufRead, BufReader, BufWriter, Write};
use std::path::Path;
pub struct Storage {
file: BufWriter<File>,
path: String,
}
impl Storage {
/// Creates a new storage instance.
///
/// # Arguments
///
/// * `path` - The path to the storage file.
///
/// # Examples
///
/// ```
/// use rust_kafka_like::broker::storage::Storage;
///
/// let storage = Storage::new("test_logs").unwrap();
/// ```
pub fn new(path: &str) -> io::Result<Self> {
let file = BufWriter::new(
OpenOptions::new()
.create(true)
.write(true)
.append(true)
.open(path)?,
);
Ok(Storage {
path: path.to_string(),
file,
})
}
/// Writes a message to the storage.
///
/// # Arguments
///
/// * `message` - The message to write.
///
/// # Examples
///
/// ```
/// use rust_kafka_like::broker::storage::Storage;
///
/// let mut storage = Storage::new("test_logs").unwrap();
/// storage.write_message("test_message").unwrap();
/// ```
pub fn write_message(&mut self, message: &str) -> io::Result<()> {
self.file.write_all(message.as_bytes())?;
self.file.write_all(b"\n")?;
self.file.flush()?;
Ok(())
}
/// Reads all messages from the storage.
///
/// # Examples
///
/// ```
/// use rust_kafka_like::broker::storage::Storage;
///
/// let storage = Storage::new("test_logs").unwrap();
/// let messages = storage.read_messages().unwrap();
/// ```
pub fn read_messages(&self) -> io::Result<Vec<String>> {
let file = File::open(&self.path)?;
let reader = BufReader::new(file);
let mut messages = Vec::new();
for line in reader.lines() {
messages.push(line?);
}
Ok(messages)
}
/// Rotates the current log file.
///
/// # Examples
///
/// ```
/// use rust_kafka_like::broker::storage::Storage;
///
/// let mut storage = Storage::new("test_logs").unwrap();
/// storage.rotate_logs().unwrap();
/// ```
pub fn rotate_logs(&mut self) -> io::Result<()> {
let new_path = format!("{}.old", self.path);
std::fs::rename(&self.path, &new_path)?;
self.file = BufWriter::new(
OpenOptions::new()
.create(true)
.write(true)
.append(true)
.open(&self.path)?,
);
Ok(())
}
/// Cleans up the old logs.
///
/// # Examples
///
/// ```
/// use rust_kafka_like::broker::storage::Storage;
///
/// let mut storage = Storage::new("test_logs").unwrap();
/// storage.write_message("test_message").unwrap();
/// storage.rotate_logs().unwrap();
/// storage.cleanup_logs().unwrap();
/// ```
pub fn cleanup_logs(&self) -> io::Result<()> {
let old_path = format!("{}.old", self.path);
if Path::new(&old_path).exists() {
std::fs::remove_file(&old_path)?;
} else {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"Old log file does not exist",
));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;
#[test]
fn test_write_message_to_invalid_path() {
let invalid_path = "/invalid_path/test_logs";
let result = Storage::new(invalid_path);
assert!(result.is_err());
}
#[test]
fn test_read_message_from_nonexistent_file() {
let test_log = format!("/tmp/test_log_{}", std::process::id());
assert!(!Path::new(&test_log).exists());
let storage = Storage::new(&test_log).unwrap();
std::fs::remove_file(&test_log).unwrap_or(());
let result = storage.read_messages();
assert!(
result.is_err(),
"Loading a non-existent file should return an error"
);
}
#[test]
fn test_rotate_logs_with_invalid_path() {
let invalid_path = "/invalid_path/test_logs";
let mut storage = Storage::new(invalid_path).unwrap_or_else(|_| Storage {
path: invalid_path.to_string(),
file: BufWriter::new(File::create("/dev/null").unwrap()),
});
let result = storage.rotate_logs();
assert!(result.is_err());
}
#[test]
fn test_cleanup_logs_with_invalid_path() {
let invalid_path = format!("/tmp/nonexistent_{}/test.log", std::process::id());
assert!(!Path::new(&invalid_path).exists());
let storage = Storage {
path: invalid_path,
file: BufWriter::new(File::create("/dev/null").unwrap()),
};
let result = storage.cleanup_logs();
assert!(
result.is_err(),
"Deleting a file that does not exist should return an error"
);
}
}