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
#![feature(test)]
extern crate test;
extern crate bincode;
extern crate rustc_serialize;
#[macro_use]
extern crate log;
use std::collections::HashMap;
use std::fs;
use std::fs::File;
use std::fs::OpenOptions;
use std::path::Path;
use std::io::prelude::*;
use std::hash::Hash;
use bincode::SizeLimit;
use bincode::rustc_serialize::{ encode, decode };
use rustc_serialize::{ Encodable, Decodable };
const MAX_RETRIES:i32 = 5;
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
pub enum Value {
String(String),
Int(i32),
Float(f32),
Map(HashMap<String, Value>),
}
type KVResult = Result<bool, &'static str>;
pub struct KV<K,V> {
cab: HashMap<K, V>,
file: File,
}
impl<K: Clone + Encodable + Decodable + Eq + Hash, V: Clone + Encodable + Decodable> KV<K,V> {
pub fn new(p:&'static str) -> KV<K,V> {
if !Path::new(p).exists() {
for i in 0..MAX_RETRIES {
match File::create(p) {
Ok(_) => break,
Err(e) => {
error!("{}", e);
if i >= MAX_RETRIES - 1 {
panic!("Could not create file after retries");
}
continue;
},
}
}
}
fn retry_get_file(p:&'static str) -> File {
for _ in 0..MAX_RETRIES {
let mut perms = match fs::metadata(p) {
Ok(f) => f.permissions(),
Err(e) => {
error!("{}", e);
continue;
},
};
perms.set_readonly(false);
match fs::set_permissions(p, perms) {
Ok(_) => (),
Err(e) => {
error!("{}", e);
continue;
}
}
match OpenOptions::new().read(true).write(true).open(p) {
Ok(f) => { return f; },
Err(e) => {
error!("{}", e);
continue;
}
};
}
panic!("retry_get_file: Failed to get file");
}
let mut store = KV {
cab: HashMap::new(),
file: retry_get_file(p),
};
store.lock_cab(true);
match store.load_from_persist() {
Ok(f) => trace!("{}", f),
Err(e) => {
warn!("{}", e);
},
};
store
}
pub fn insert(&mut self, key: K, value: V) -> KVResult {
let _ = self.load_from_persist();
self.cab.insert(key, value);
self.write_to_persist()
}
pub fn get(&mut self, key: K) -> Option<V> {
let _ = self.load_from_persist();
match self.cab.get(&key) {
Some(v) => Some((*v).clone()),
None => None
}
}
pub fn remove(&mut self, key: K) -> KVResult {
let _ = self.load_from_persist();
self.cab.remove(&key);
self.write_to_persist()
}
pub fn keys(&mut self) -> Vec<K> {
let _ = self.load_from_persist();
self.cab.keys().map(|k| k.clone()).collect()
}
fn lock_cab(&mut self, readonly:bool) {
for i in 0..MAX_RETRIES {
let mut perms = match self.file.metadata() {
Ok(f) => f.permissions(),
Err(e) => {
error!("{}", e);
if i >= MAX_RETRIES - 1 {
panic!("Could not set permissions after retries");
}
continue;
},
};
perms.set_readonly(readonly);
match self.file.set_permissions(perms) {
Ok(_) => {
let _ = self.file.sync_all();
break;
},
Err(e) => {
error!("{}", e);
if i >= MAX_RETRIES - 1 {
panic!("Could not set permissions after retries");
}
continue;
},
}
}
}
fn wait_for_free(&mut self, lock:bool) -> KVResult {
loop {
let _ = self.file.sync_all();
let metadata = match self.file.metadata() {
Ok(m) => m,
Err(_) => return Err("File doesn't exist or is not readeable"),
};
if metadata.permissions().readonly() {
if lock {
self.lock_cab(false);
}
break;
}
}
Ok(true)
}
fn write_to_persist(&mut self) -> KVResult {
let byte_vec: Vec<u8> = match encode(&mut self.cab, SizeLimit::Infinite) {
Ok(bv) => bv,
Err(e) => {
error!("encode: {}", e);
return Err("Could not encode cab");
},
};
if !self.wait_for_free(true).is_ok() {
return Err("File doesn't exist or is not readeable");
}
for i in 0..MAX_RETRIES {
match self.file.write_all(byte_vec.as_slice()) {
Ok(_) => (),
Err(e) => {
error!("file.write_all/retry: {}", e);
if i >= MAX_RETRIES - 1 {
panic!("Could not write to file after retries");
}
continue;
},
}
let _ = self.file.flush();
self.lock_cab(true);
break;
}
Ok(true)
}
fn load_from_persist(&mut self) -> KVResult {
let mut byte_vec = Vec::new();
if !self.wait_for_free(false).is_ok() {
return Err("File doesn't exist or is not readeable");
}
let _ = self.file.read_to_end(&mut byte_vec);
let decoded: HashMap<K, V> = match decode(byte_vec.as_slice()) {
Ok(f) => f,
Err(e) => {
warn!("{}", e);
return Err("Couldn't decode cab");
},
};
self.cab = decoded;
Ok(true)
}
}
#[cfg(test)]
mod benches {
use super::*;
use test::Bencher;
macro_rules! bench_teardown {
( $p:ident ) => {
use std::{thread, time};
thread::sleep(time::Duration::from_secs(2));
let _ = std::fs::remove_file($p);
}
}
#[bench]
fn bench_get_int(b: &mut Bencher) {
let test_cab_path = "./bench_get_many.cab";
let mut test_store = KV::<String, Value>::new(test_cab_path);
let _ = test_store.insert("test".to_string(), Value::Int(1));
b.iter(|| {
test_store.get("test".to_string());
});
bench_teardown!(test_cab_path);
}
#[bench]
fn bench_insert_int(b: &mut Bencher) {
let test_cab_path = "./bench_insert_many.cab";
let mut test_store = KV::<String, Value>::new(test_cab_path);
b.iter(|| {
let _ = test_store.insert("test".to_string(), Value::Int(1));
});
bench_teardown!(test_cab_path);
}
}