Repository navigation
Expand file tree
/
Copy pathrecorder.rs
More file actions
173 lines (151 loc) · 5.7 KB
/
Copy pathrecorder.rs
File metadata and controls
173 lines (151 loc) · 5.7 KB
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
use std::{
borrow::Cow,
fs,
io::{BufWriter, Write},
path::{Path, PathBuf},
sync::{Mutex, TryLockError},
};
use crate::{
p2p::identity::SecretKey as P2pSecretKey, Action, ActionWithMeta, EventSourceAction, State,
};
use super::{RecordedActionWithMeta, RecordedInitialState};
static ACTIONS_F: Mutex<Vec<Option<fs::File>>> = Mutex::new(Vec::new());
/// Panics: if all the `Recorder` instances aren't in the same thread.
pub enum Recorder {
None,
OnlyInputActions {
recorder_i: usize,
recorder_path: PathBuf,
actions_f_bytes_written: u64,
actions_f_index: usize,
},
}
impl Recorder {
pub fn only_input_actions<P: AsRef<Path>>(work_dir: P) -> Self {
let path = work_dir.as_ref().join("recorder");
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("creating dir for openmina recorder failed!");
let actions_f_index = 1;
let actions_path = super::actions_path(&path, actions_f_index);
let file = fs::File::create(actions_path)
.expect("creating file for openmina recorder initial state failed!");
let mut actions_files = ACTIONS_F.try_lock().unwrap();
actions_files.push(Some(file));
Self::OnlyInputActions {
recorder_i: actions_files.len().saturating_sub(1),
recorder_path: path,
actions_f_bytes_written: 0,
actions_f_index,
}
}
pub fn initial_state(&mut self, rng_seed: [u8; 32], p2p_sec_key: P2pSecretKey, state: &State) {
match self {
Self::None => {}
Self::OnlyInputActions { recorder_path, .. } => {
let initial_state = RecordedInitialState {
rng_seed,
p2p_sec_key,
state: Cow::Borrowed(state),
};
let initial_state_path = super::initial_state_path(recorder_path);
let mut initial_state_f = fs::File::create(initial_state_path)
.expect("creating file for openmina recorder initial state failed!");
initial_state.write_to(&mut initial_state_f).unwrap();
initial_state_f.sync_all().unwrap();
}
}
}
pub fn action(&mut self, action: &ActionWithMeta) {
match self {
Self::None => {}
Self::OnlyInputActions {
recorder_i,
recorder_path,
actions_f_bytes_written,
actions_f_index,
..
} => {
let is_input = match action.action() {
Action::CheckTimeouts(_) => true,
Action::EventSource(e) => match e {
EventSourceAction::NewEvent { .. } => true,
_ => return,
},
_ => false,
};
let data = if !is_input {
let kind = action.action().kind();
RecordedActionWithMeta::from((kind, action.meta().clone()))
} else {
RecordedActionWithMeta::from(action)
};
let mut files = ACTIONS_F.try_lock().unwrap();
let cur_f = files.get_mut(*recorder_i).unwrap(); // TODO: error propagation
let file = if *actions_f_bytes_written > 64 * 1024 * 1024 {
cur_f.take().unwrap().sync_all().unwrap();
*actions_f_bytes_written = 0;
*actions_f_index = actions_f_index
.checked_add(1)
.expect("overflow in actions_f_index");
cur_f.insert(
fs::File::create(super::actions_path(recorder_path, *actions_f_index))
.unwrap(),
)
} else {
cur_f.as_mut().unwrap()
};
let mut writer = BufWriter::new(file);
let encoded = data.encode().unwrap();
// RecordedActionWithMeta::decode(&encoded)
// .expect(&format!("failed to decode encoded message: {:?}", data));
writer
.write_all(&(encoded.len() as u64).to_be_bytes())
.unwrap();
writer.write_all(&encoded).unwrap();
writer.flush().unwrap();
*actions_f_bytes_written = actions_f_bytes_written
.checked_add(
8u64.checked_add(encoded.len() as u64)
.expect("overflow in encoded len"),
)
.expect("overflow in actions_f_bytes_written");
}
}
}
pub fn graceful_shutdown() {
graceful_shutdown(None)
}
}
impl Default for Recorder {
fn default() -> Self {
Self::None
}
}
impl Drop for Recorder {
fn drop(&mut self) {
match self {
Self::None => {}
Self::OnlyInputActions { recorder_i, .. } => graceful_shutdown(Some(*recorder_i)),
}
}
}
fn graceful_shutdown(only_i: Option<usize>) {
let Some(mut files) = ACTIONS_F.try_lock().map_or_else(
|err| match err {
TryLockError::WouldBlock => None,
TryLockError::Poisoned(v) => Some(v.into_inner()),
},
Some,
) else {
return;
};
let files_iter = files
.iter_mut()
.enumerate()
.filter(|(i, _)| only_i.is_none_or(|only_i| only_i == *i))
.filter_map(|(i, v)| Some((i, v.take()?)));
for (i, file) in files_iter {
eprintln!("Flushing recorded actions to disk before shutdown. i={i}");
let _ = file.sync_all();
}
}