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
use crate::RunnerError;
use crate::RunnerResult;
use air_interpreter_interface::InterpreterOutcome;
use air_utils::measure;
use avm_interface::raw_outcome::RawAVMOutcome;
use avm_interface::CallResults;
use marine::IValue;
use marine::Marine;
use marine::MarineConfig;
use marine::ModuleDescriptor;
use std::path::PathBuf;
pub struct AVMRunner {
marine: Marine,
current_peer_id: String,
wasm_filename: String,
}
pub struct AVMMemoryStats {
pub memory_size: usize,
pub max_memory_size: Option<usize>,
}
impl AVMRunner {
pub fn new(
air_wasm_path: PathBuf,
current_peer_id: impl Into<String>,
max_heap_size: Option<u64>,
logging_mask: i32,
) -> RunnerResult<Self> {
let (wasm_dir, wasm_filename) = split_dirname(air_wasm_path)?;
let marine_config =
make_marine_config(wasm_dir, &wasm_filename, max_heap_size, logging_mask);
let marine = Marine::with_raw_config(marine_config)?;
let current_peer_id = current_peer_id.into();
let avm = Self {
marine,
current_peer_id,
wasm_filename,
};
Ok(avm)
}
#[allow(clippy::too_many_arguments)]
#[tracing::instrument(skip_all)]
pub fn call(
&mut self,
air: impl Into<String>,
prev_data: impl Into<Vec<u8>>,
data: impl Into<Vec<u8>>,
init_peer_id: impl Into<String>,
timestamp: u64,
ttl: u32,
call_results: CallResults,
) -> RunnerResult<RawAVMOutcome> {
let args = prepare_args(
air,
prev_data,
data,
self.current_peer_id.clone(),
init_peer_id.into(),
timestamp,
ttl,
call_results,
);
let result = measure!(
self.marine
.call_with_ivalues(&self.wasm_filename, "invoke", &args, <_>::default())?,
tracing::Level::INFO,
"marine.call_with_ivalues",
method = "invoke",
);
let result = try_as_one_value_vec(result)?;
let outcome = InterpreterOutcome::from_ivalue(result)
.map_err(RunnerError::InterpreterResultDeError)?;
let outcome = RawAVMOutcome::from_interpreter_outcome(outcome)?;
Ok(outcome)
}
#[allow(clippy::too_many_arguments)]
#[tracing::instrument(skip_all)]
pub fn call_tracing(
&mut self,
air: impl Into<String>,
prev_data: impl Into<Vec<u8>>,
data: impl Into<Vec<u8>>,
init_peer_id: impl Into<String>,
timestamp: u64,
ttl: u32,
call_results: CallResults,
tracing_params: String,
tracing_output_mode: u8,
) -> RunnerResult<RawAVMOutcome> {
let mut args = prepare_args(
air,
prev_data,
data,
self.current_peer_id.clone(),
init_peer_id.into(),
timestamp,
ttl,
call_results,
);
args.push(IValue::String(tracing_params));
args.push(IValue::U8(tracing_output_mode));
let result = measure!(
self.marine.call_with_ivalues(
&self.wasm_filename,
"invoke_tracing",
&args,
<_>::default(),
)?,
tracing::Level::INFO,
"marine.call_with_ivalues",
method = "invoke_tracing",
);
let result = try_as_one_value_vec(result)?;
let outcome = InterpreterOutcome::from_ivalue(result)
.map_err(RunnerError::InterpreterResultDeError)?;
let outcome = RawAVMOutcome::from_interpreter_outcome(outcome)?;
Ok(outcome)
}
pub fn memory_stats(&self) -> AVMMemoryStats {
let stats = self.marine.module_memory_stats();
debug_assert!(stats.len() == 1);
AVMMemoryStats {
memory_size: stats[0].memory_size,
max_memory_size: stats[0].max_memory_size,
}
}
#[inline]
pub fn set_peer_id(&mut self, current_peer_id: impl Into<String>) {
self.current_peer_id = current_peer_id.into();
}
}
#[allow(clippy::too_many_arguments)]
#[tracing::instrument(skip(air, prev_data, data, call_results))]
fn prepare_args(
air: impl Into<String>,
prev_data: impl Into<Vec<u8>>,
data: impl Into<Vec<u8>>,
current_peer_id: String,
init_peer_id: String,
timestamp: u64,
ttl: u32,
call_results: CallResults,
) -> Vec<IValue> {
let run_parameters = air_interpreter_interface::RunParameters::new(
init_peer_id,
current_peer_id,
timestamp,
ttl,
)
.into_ivalue();
let call_results = avm_interface::into_raw_result(call_results);
let call_results = measure!(
serde_json::to_vec(&call_results).expect("the default serializer shouldn't fail"),
tracing::Level::INFO,
"serde_json::to_vec call_results"
);
vec![
IValue::String(air.into()),
IValue::ByteArray(prev_data.into()),
IValue::ByteArray(data.into()),
run_parameters,
IValue::ByteArray(call_results),
]
}
fn split_dirname(path: PathBuf) -> RunnerResult<(PathBuf, String)> {
use RunnerError::InvalidAIRPath;
let metadata = path.metadata().map_err(|err| InvalidAIRPath {
invalid_path: path.clone(),
reason: "failed to get file's metadata (doesn't exist or invalid permissions)",
io_error: Some(err),
})?;
if !metadata.is_file() {
return Err(InvalidAIRPath {
invalid_path: path,
reason: "is not a file",
io_error: None,
});
}
let file_name = path
.file_name()
.expect("checked to be a file, file name must be defined");
let file_name = file_name.to_string_lossy().into_owned();
let mut path = path;
path.pop();
Ok((path, file_name))
}
fn make_marine_config(
air_wasm_dir: PathBuf,
air_wasm_file: &str,
max_heap_size: Option<u64>,
logging_mask: i32,
) -> MarineConfig {
let air_module_config = marine::MarineModuleConfig {
mem_pages_count: None,
max_heap_size,
logger_enabled: true,
host_imports: <_>::default(),
wasi: None,
logging_mask,
};
MarineConfig {
modules_dir: Some(air_wasm_dir),
modules_config: vec![ModuleDescriptor {
load_from: None,
file_name: String::from(air_wasm_file),
import_name: String::from(air_wasm_file),
config: air_module_config,
}],
default_modules_config: None,
}
}
fn try_as_one_value_vec(mut ivalues: Vec<IValue>) -> RunnerResult<IValue> {
use RunnerError::IncorrectInterpreterResult;
if ivalues.len() != 1 {
return Err(IncorrectInterpreterResult(ivalues));
}
Ok(ivalues.remove(0))
}