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
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
mod async_externalities;
#[cfg(feature = "std")]
pub use async_externalities::{new_async_externalities, AsyncExternalities};
#[cfg(feature = "std")]
mod inner {
use sp_core::traits::TaskExecutorExt;
use sp_externalities::ExternalitiesExt as _;
use std::{panic::AssertUnwindSafe, sync::mpsc};
#[must_use]
pub struct DataJoinHandle {
receiver: mpsc::Receiver<Vec<u8>>,
}
impl DataJoinHandle {
pub fn join(self) -> Vec<u8> {
self.receiver
.recv()
.expect("Spawned runtime task terminated before sending result.")
}
}
pub fn spawn(entry_point: fn(Vec<u8>) -> Vec<u8>, data: Vec<u8>) -> DataJoinHandle {
let scheduler = sp_externalities::with_externalities(|mut ext| {
ext.extension::<TaskExecutorExt>()
.expect("No task executor associated with the current context!")
.clone()
})
.expect("Spawn called outside of externalities context!");
let (sender, receiver) = mpsc::channel();
let extra_scheduler = scheduler.clone();
scheduler.spawn(
"parallel-runtime-spawn",
Box::pin(async move {
let result = match crate::new_async_externalities(extra_scheduler) {
Ok(mut ext) => {
let mut ext = AssertUnwindSafe(&mut ext);
match std::panic::catch_unwind(move || {
sp_externalities::set_and_run_with_externalities(
&mut **ext,
move || entry_point(data),
)
}) {
Ok(result) => result,
Err(panic) => {
log::error!(
target: "runtime",
"Spawned task panicked: {:?}",
panic,
);
return
},
}
},
Err(e) => {
log::error!(
target: "runtime",
"Unable to run async task: {}",
e,
);
return
},
};
let _ = sender.send(result);
}),
);
DataJoinHandle { receiver }
}
}
#[cfg(not(feature = "std"))]
mod inner {
use core::mem;
use sp_std::prelude::*;
extern "C" fn dispatch_wrapper(
func_ref: *const u8,
payload_ptr: *mut u8,
payload_len: u32,
) -> u64 {
let payload_len = payload_len as usize;
let output = unsafe {
let payload = Vec::from_raw_parts(payload_ptr, payload_len, payload_len);
let ptr: fn(Vec<u8>) -> Vec<u8> = mem::transmute(func_ref);
(ptr)(payload)
};
sp_runtime_interface::pack_ptr_and_len(output.as_ptr() as usize as _, output.len() as _)
}
pub fn spawn(entry_point: fn(Vec<u8>) -> Vec<u8>, payload: Vec<u8>) -> DataJoinHandle {
let func_ptr: usize = unsafe { mem::transmute(entry_point) };
let handle =
sp_io::runtime_tasks::spawn(dispatch_wrapper as usize as _, func_ptr as u32, payload);
DataJoinHandle { handle }
}
#[must_use]
pub struct DataJoinHandle {
handle: u64,
}
impl DataJoinHandle {
pub fn join(self) -> Vec<u8> {
sp_io::runtime_tasks::join(self.handle)
}
}
}
pub use inner::{spawn, DataJoinHandle};
#[cfg(test)]
mod tests {
use super::*;
fn async_runner(mut data: Vec<u8>) -> Vec<u8> {
data.sort();
data
}
fn async_panicker(_data: Vec<u8>) -> Vec<u8> {
panic!("panic in async panicker!")
}
#[test]
fn basic() {
sp_io::TestExternalities::default().execute_with(|| {
let a1 = spawn(async_runner, vec![5, 2, 1]).join();
assert_eq!(a1, vec![1, 2, 5]);
})
}
#[test]
fn panicking() {
let res = sp_io::TestExternalities::default().execute_with_safe(|| {
spawn(async_panicker, vec![5, 2, 1]).join();
});
assert!(res.unwrap_err().contains("Closure panicked"));
}
#[test]
fn many_joins() {
sp_io::TestExternalities::default()
.execute_with_safe(|| {
let mut running_val = 9780657630u64;
let mut data = vec![];
let handles = (0..1024)
.map(|_| {
running_val = if running_val % 2 == 0 {
running_val / 2
} else {
3 * running_val + 1
};
data.push(running_val as u8);
(spawn(async_runner, data.clone()), data.clone())
})
.collect::<Vec<_>>();
for (handle, mut data) in handles {
let result = handle.join();
data.sort();
assert_eq!(result, data);
}
})
.expect("Failed to run with externalities");
}
}