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
use indoc::indoc;
use clap::{Parser, Subcommand};
use env_logger;
use log::{error, info, warn};
use simd_r_drive::AppendStorage;
mod format_bytes;
use format_bytes::format_bytes;
use std::path::PathBuf;
use stdin_nonblocking::get_stdin_or_default;
use std::io::{self, IsTerminal, Write};
// Help text template with placeholder
const HELP_TEMPLATE: &str = indoc! {r#"
Examples:
%BINARY_NAME% data.bin write mykey "Hello, world!"
%BINARY_NAME% data.bin read mykey
%BINARY_NAME% data.bin delete mykey
"#};
/// Append-Only Storage Engine CLI
#[derive(Parser)]
#[command(
name = env!("CARGO_PKG_NAME"),
version = env!("CARGO_PKG_VERSION"),
about = env!("CARGO_PKG_DESCRIPTION"),
long_about = None
)]
#[command(
after_help = HELP_TEMPLATE.replace("%BINARY_NAME%", env!("CARGO_PKG_NAME"))
)]
struct Cli {
/// The file where data is stored (automatically created if it does not exist).
#[arg(value_name = "storage", help = "Path to the storage file. If the file does not exist, it will be created automatically.")]
storage: PathBuf,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Read the value associated with a key
Read {
/// The key to read
key: String,
},
/// Write a value for a given key
Write {
/// The key to write
key: String,
/// The value to store (optional; reads from stdin if not provided)
value: Option<String>,
},
/// Copy an entry from one storage file to another
Copy {
/// The key to copy
key: String,
/// Target storage file
#[arg(value_name = "target")]
target: PathBuf,
},
/// Move an entry from one storage file to another (copy and delete)
Move {
/// The key to move
key: String,
/// Target storage file
#[arg(value_name = "target")]
target: PathBuf,
},
/// Delete a key
Delete {
/// The key to delete
key: String,
},
/// Compact the storage file to remove old entries
Compact,
/// Get current state of storage file
Info,
/// Access the metadata of a key
Metadata {
// The key to query
key: String
}
}
fn main() {
let stdin_input = get_stdin_or_default(None);
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
let cli = Cli::parse();
match &cli.command {
Commands::Read { key } => {
let storage = AppendStorage::open(&cli.storage).expect("Failed to open storage");
match storage.get_entry_by_key(key.as_bytes()) {
Some(value) => {
let stdout = io::stdout();
let mut handle = stdout.lock();
if stdout.is_terminal() {
// If writing to a terminal, use UTF-8 safe string output
writeln!(handle, "{}", String::from_utf8_lossy(&value.as_slice()))
.expect("Failed to write output");
} else {
// If redirected, output raw binary
handle.write_all(&value.as_slice()).expect("Failed to write binary output");
handle.flush().expect("Failed to flush output");
}
}
None => {
error!("Error: Key '{}' not found", key);
std::process::exit(1);
}
}
}
Commands::Write { key, value } => {
let mut storage = AppendStorage::open(&cli.storage).expect("Failed to open storage");
// Convert `Option<String>` to `Option<Vec<u8>>` (binary format)
let value_bytes = value.as_ref().map(|s| s.as_bytes().to_vec());
// `stdin_input` is already `Option<Vec<u8>>`, so merge them properly
let final_value = value_bytes.or_else(|| stdin_input.clone());
// Check if the final value is `None` or an empty binary array
if final_value.as_deref().map_or(true, |v| v.is_empty()) {
error!("Error: No value provided and stdin is empty.");
std::process::exit(1);
}
// Unwrap safely since we checked for `None`
let final_value = final_value.unwrap();
storage
.append_entry(key.as_bytes(), &final_value)
.expect("Failed to write entry");
info!(
"Stored '{}'",
key,
);
}
Commands::Copy { key, target } => {
let source_storage = AppendStorage::open(&cli.storage).expect("Failed to open source storage");
let mut target_storage = AppendStorage::open(target).expect("Failed to open target storage");
source_storage
.copy_entry(key.as_bytes(), &mut target_storage)
.map_err(|err| {
error!("Could not copy entry. Received error: {}", err.to_string());
std::process::exit(1);
})
.ok(); // Ignore the success case
info!("Copied key '{}' to {:?}", key, target);
},
Commands::Move { key, target } => {
let mut source_storage = AppendStorage::open(&cli.storage).expect("Failed to open source storage");
let mut target_storage = AppendStorage::open(target).expect("Failed to open target storage");
source_storage
.move_entry(key.as_bytes(), &mut target_storage)
.map_err(|err| {
error!("Could not copy entry. Received error: {}", err.to_string());
std::process::exit(1);
})
.ok(); // Ignore the success case
info!("Moved key '{}' to {:?}", key, target);
},
Commands::Delete { key } => {
let mut storage = AppendStorage::open(&cli.storage).expect("Failed to open storage");
storage
.delete_entry(key.as_bytes())
.expect("Failed to delete entry");
warn!("Deleted key '{}'", key);
}
Commands::Compact => {
let mut storage = AppendStorage::open(&cli.storage).expect("Failed to open storage");
info!("Starting compaction...");
if let Err(e) = storage.compact() {
error!("Compaction failed: {}", e);
std::process::exit(1);
}
info!("Compaction completed successfully.");
}
Commands::Metadata { key } => {
let storage = AppendStorage::open(&cli.storage).expect("Failed to open storage");
match storage.get_entry_by_key(key.as_bytes()) {
Some(entry) => {
println!(
"\n{:=^50}\n\
{:<25} \"{}\"\n\
{:-<50}\n\
{:<25} {} bytes\n\
{:<25} {} bytes\n\
{:<25} {:?}\n\
{:<25} {:?}\n\
{:<25} {}\n\
{:<25} {}\n\
{:<25} {}\n\
{:-<50}\n\
{:<25} {:?}\n\
{:=<50}",
" METADATA SUMMARY ", // Centered Header
"ENTRY FOR:", key, // Key Name
"", // Separator
"PAYLOAD SIZE:", entry.size(),
"TOTAL SIZE (W/ METADATA):", entry.size_with_metadata(),
"OFFSET RANGE:", entry.offset_range(),
"MEMORY ADDRESS:", entry.address_range(),
"KEY HASH:", entry.key_hash(),
"CHECKSUM:", entry.checksum(),
"CHECKSUM VALIDITY:", if entry.is_valid_checksum() { "VALID" } else { "INVALID" },
"", // Separator
"STORED METADATA:", entry.metadata(),
"=" // Footer Line
);
}
None => {
error!("Error: Key '{}' not found", key);
std::process::exit(1);
}
}
}
Commands::Info => {
let storage = AppendStorage::open(&cli.storage).expect("Failed to open storage");
// Retrieve storage file size
let storage_size = storage.get_storage_size().unwrap_or(0);
// Get compaction savings estimate
let savings_estimate = storage.estimate_compaction_savings();
// Count active entries
let entry_count = storage.count();
println!(
"\n{:=^50}\n\
{:<25} {:?}\n\
{:-<50}\n\
{:<25} {}\n\
{:<25} {}\n\
{:<25} {}\n\
{:=<50}",
" STORAGE INFO ", // Centered Header
"STORAGE FILE:", cli.storage, // File Path
"", // Separator
"TOTAL SIZE:", format_bytes(storage_size),
"ACTIVE ENTRIES:", entry_count,
"COMPACTION SAVINGS:", format_bytes(savings_estimate),
"=" // Footer
);
}
}
}