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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
use crate::result::Result;
use crate::cell::LazyCell;
use crate::{TxInSafe, TxOutSafe, utils};
use std::collections::hash_map::HashMap;
use std::fmt::{self, Debug};
use std::fs::OpenOptions;
use std::io::{self, Error, Write};
use std::panic::{RefUnwindSafe, UnwindSafe};
use std::path::Path;
use std::sync::Mutex;
use std::thread::ThreadId;
use std::{mem, panic, ptr, slice, str, thread};
const MAX_TRANS: usize = 4096;
pub struct Chaperon {
len: usize,
completed: bool,
done: [bool; MAX_TRANS],
filename: [u8; 4096],
filename_len: usize,
vdata: Option<VData>,
}
struct VData {
mmap: memmap::MmapMut,
delayed_commit: HashMap<ThreadId, Vec<unsafe fn() -> ()>>,
delayed_rollback: HashMap<ThreadId, Vec<unsafe fn() -> ()>>,
delayed_clear: HashMap<ThreadId, Vec<unsafe fn() -> ()>>,
mutex: u8,
}
impl VData {
pub fn new(mmap: memmap::MmapMut) -> Self {
Self {
mmap,
delayed_commit: HashMap::new(),
delayed_rollback: HashMap::new(),
delayed_clear: HashMap::new(),
mutex: 0,
}
}
}
impl !TxOutSafe for Chaperon {}
impl UnwindSafe for Chaperon {}
impl RefUnwindSafe for Chaperon {}
unsafe impl TxInSafe for Chaperon {}
unsafe impl Send for Chaperon {}
unsafe impl Sync for Chaperon {}
struct SyncBox<T: ?Sized> {
data: *mut T
}
impl<T: ?Sized> SyncBox<T> {
fn new(data: *mut T) -> Self {
Self { data }
}
fn get(&self) -> *mut T {
self.data
}
}
unsafe impl<T:?Sized> Sync for SyncBox<T> {}
unsafe impl<T:?Sized> Send for SyncBox<T> {}
static mut CLIST: LazyCell<Mutex<HashMap<ThreadId, SyncBox<Chaperon>>>> =
LazyCell::new(|| Mutex::new(HashMap::new()));
fn new_chaperon(filename: &str) -> Result<*mut Chaperon> {
let mut clist = match unsafe { CLIST.lock() } {
Ok(g) => g,
Err(p) => p.into_inner()
};
let tid = thread::current().id();
if clist.contains_key(&tid) {
return Err("Another chaperoned transaction is open".to_string());
}
let c = Chaperon::new(filename.to_string())
.expect(&format!("could not create chaperon file `{}`", filename));
clist.entry(tid).or_insert(SyncBox::new(c));
Ok(clist.get(&tid).unwrap().get())
}
fn drop_chaperon() {
let mut clist = match unsafe { CLIST.lock() } {
Ok(g) => g,
Err(p) => p.into_inner()
};
let tid = thread::current().id();
clist.remove(&tid);
}
fn current_chaperon() -> Option<*mut Chaperon> {
let clist = match unsafe { CLIST.lock() } {
Ok(g) => g,
Err(p) => p.into_inner()
};
let tid = thread::current().id();
if clist.contains_key(&tid) {
Some(clist.get(&tid).unwrap().get())
} else {
None
}
}
impl Chaperon {
pub(crate) fn new(filename: String) -> io::Result<&'static mut Self> {
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(&filename)?;
file.set_len(1024 * 1024 * 1)?;
let mut a = Self {
len: 0,
completed: false,
done: [true; MAX_TRANS],
filename: [0; 4096],
filename_len: filename.len(),
vdata: None,
};
let bytes = filename.as_bytes();
for i in 0..4096.min(filename.len()) {
a.filename[i] = bytes[i];
}
file.write_all(a.as_bytes()).unwrap();
unsafe { Self::load(&filename) }
}
fn deref(raw: *mut u8) -> &'static mut Self {
unsafe { utils::read(raw) }
}
fn as_bytes(&self) -> &[u8] {
let ptr = self as *const Self;
let ptr = ptr as *const u8;
unsafe { std::slice::from_raw_parts(ptr, std::mem::size_of::<Self>()) }
}
pub unsafe fn load(filename: &str) -> io::Result<&'static mut Self> {
if Path::new(&filename).exists() {
let file = OpenOptions::new().read(true).write(true).open(&filename)?;
let mut mmap = memmap::MmapOptions::new().map_mut(&file).unwrap();
let slf = Self::deref(mmap.get_mut(0).unwrap());
mem::forget(ptr::replace(&mut slf.vdata, Some(VData::new(mmap))));
Ok(slf)
} else {
Err(Error::last_os_error())
}
}
pub(crate) fn current() -> Option<*mut Chaperon> {
current_chaperon()
}
pub(crate) fn new_section(&mut self) -> usize {
use crate::ll::persist_obj;
assert!(self.len < MAX_TRANS, "reached max number of attachments");
self.len += 1;
self.done[self.len - 1] = false;
persist_obj(self, true);
self.len
}
#[inline]
pub(crate) fn is_done(&self, id: usize) -> bool {
let id = id - 1;
assert!(id < self.len, "index out of range");
self.done[id]
}
#[inline]
pub(crate) fn finish(&mut self, id: usize) {
let id = id - 1;
assert!(id < self.len, "index out of range");
self.done[id] = true;
if self.completed() {
self.close();
}
}
pub(crate) fn completed(&mut self) -> bool {
if self.completed {
true
} else {
for i in 0..self.len {
if !self.done[i] {
return false;
}
}
self.completed = true;
true
}
}
fn close(&self) {
}
pub fn filename(&self) -> &str {
unsafe {
let slice = slice::from_raw_parts(&self.filename[0], self.filename_len);
str::from_utf8(slice).unwrap()
}
}
pub(crate) fn postpone(
&mut self,
commit: unsafe fn()->(),
rollback: unsafe fn()->(),
clear: unsafe fn()->(),
) {
if let Some(vdata) = self.vdata.as_mut() {
let tid = thread::current().id();
let commits = vdata.delayed_commit.entry(tid).or_insert(Vec::new());
let rollbacks = vdata.delayed_rollback.entry(tid).or_insert(Vec::new());
let clears = vdata.delayed_clear.entry(tid).or_insert(Vec::new());
commits.push(commit);
rollbacks.push(rollback);
clears.push(clear);
}
}
fn execute_delayed_commits(&mut self) {
if let Some(vdata) = self.vdata.as_mut() {
let tid = thread::current().id();
let commits = vdata.delayed_commit.entry(tid).or_insert(Vec::new());
let clears = vdata.delayed_clear.entry(tid).or_insert(Vec::new());
for commit in commits {
unsafe { commit(); }
}
self.completed = true;
for clear in clears {
unsafe { clear(); }
}
vdata.delayed_commit.remove(&tid);
vdata.delayed_clear.remove(&tid);
}
}
fn execute_delayed_rollbacks(&mut self) {
if let Some(vdata) = self.vdata.as_mut() {
let tid = thread::current().id();
let rollbacks = vdata.delayed_rollback.entry(tid).or_insert(Vec::new());
let clears = vdata.delayed_clear.entry(tid).or_insert(Vec::new());
for rollback in rollbacks {
unsafe { rollback(); }
}
self.completed = true;
for clear in clears {
unsafe { clear(); }
}
vdata.delayed_rollback.remove(&tid);
vdata.delayed_clear.remove(&tid);
}
}
#[inline]
pub fn session<T, F: FnOnce() -> T>(filename: &str, body: F) -> Result<T>
where
F: panic::UnwindSafe,
T: panic::UnwindSafe + TxOutSafe,
{
let chaperon = unsafe { &mut *new_chaperon(filename)? };
let res = panic::catch_unwind(|| body());
if let Ok(res) = res {
chaperon.execute_delayed_commits();
drop_chaperon();
Ok(res)
} else {
chaperon.execute_delayed_rollbacks();
drop_chaperon();
Err("Unsuccessful chaperoned transaction".to_string())
}
}
}
impl Drop for Chaperon {
fn drop(&mut self) {
if let Some(vdata) = self.vdata.as_ref() {
vdata.mmap.flush().unwrap();
}
}
}
impl Debug for Chaperon {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{{ filename: {}, len: {}, [", self.filename(), self.len)?;
for i in 0..self.len {
write!(f, "{}{}", if i == 0 { "" } else { ", " }, self.done[i])?;
}
write!(f, "] }}")
}
}