-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmod.rs
417 lines (372 loc) · 16.5 KB
/
mod.rs
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use ::futures::Future;
use deno_core::anyhow::anyhow;
use deno_core::error::AnyError;
use deno_core::{resolve_url_or_path, v8, PollEventLoopOptions};
use deno_runtime::worker::MainWorker;
use deno_runtime::{permissions::PermissionsContainer, BootstrapOptions};
use holochain::prelude::{ExternIO, Signal};
use once_cell::sync::Lazy;
use std::env::current_dir;
use std::sync::Arc;
use tokio::runtime::Builder;
use tokio::sync::broadcast;
use tokio::sync::Mutex as TokioMutex;
use tokio::sync::{
broadcast::{Receiver, Sender},
mpsc::{self, UnboundedReceiver, UnboundedSender},
oneshot
};
use log::{error, info};
use options::{main_module_url, main_worker_options};
mod agent_extension;
mod futures;
mod options;
mod languages_extension;
mod pubsub_extension;
mod signature_extension;
mod string_module_loader;
mod utils_extension;
mod wallet_extension;
mod utils;
use self::futures::{EventLoopFuture, SmartGlobalVariableFuture};
use crate::holochain_service::maybe_get_holochain_service;
use crate::Ad4mConfig;
pub(crate) static JS_CORE_HANDLE: Lazy<Arc<TokioMutex<Option<JsCoreHandle>>>> =
Lazy::new(|| Arc::new(TokioMutex::new(None)));
pub struct JsCoreHandle {
rx: Receiver<JsCoreResponse>,
tx: UnboundedSender<JsCoreRequest>,
tx_module_load: UnboundedSender<JsCoreRequest>,
broadcast_tx: Sender<JsCoreResponse>
}
impl Clone for JsCoreHandle {
fn clone(&self) -> Self {
JsCoreHandle {
rx: self.broadcast_tx.subscribe(),
tx: self.tx.clone(),
tx_module_load: self.tx_module_load.clone(),
broadcast_tx: self.broadcast_tx.clone()
}
}
}
impl JsCoreHandle {
pub async fn initialized(&mut self) {
self.rx.recv().await.expect("couldn't receive on channel");
}
pub async fn execute(&mut self, script: String) -> Result<String, AnyError> {
let id = uuid::Uuid::new_v4().to_string();
let (response_tx, response_rx) = oneshot::channel();
self.tx
.send(JsCoreRequest {
script,
id: id.clone(),
response_tx
})
.expect("couldn't send on channel... it is likely that the main worker thread has crashed...");
let response = response_rx.await?;
info!("Got response: {:?}", response);
response
.result
.map_err(|err| anyhow!(err))
}
pub async fn load_module(&mut self, path: String) -> Result<String, AnyError> {
let id = uuid::Uuid::new_v4().to_string();
let (response_tx, response_rx) = oneshot::channel();
self.tx_module_load
.send(JsCoreRequest {
script: path,
id: id.clone(),
response_tx
})
.expect("couldn't send on channel... it is likely that the main worker thread has crashed...");
let response = response_rx.await?;
response
.result
.map_err(|err| anyhow!(err))
}
}
#[derive(Debug)]
struct JsCoreRequest {
script: String,
#[allow(dead_code)]
id: String,
response_tx: oneshot::Sender<JsCoreResponse>
}
#[derive(Debug, Clone)]
struct JsCoreResponse {
result: Result<String, String>,
}
#[derive(Clone)]
pub struct JsCore {
worker: Arc<TokioMutex<MainWorker>>,
}
pub struct ExternWrapper(ExternIO);
impl std::fmt::Display for ExternWrapper {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
//Write the bytes to string like: [0, 1, 3]
let bytes = self.0.as_bytes();
let mut bytes_str = String::from("[");
for (i, byte) in bytes.iter().enumerate() {
bytes_str.push_str(&format!("{}", byte));
if i < bytes.len() - 1 {
bytes_str.push_str(", ");
}
}
bytes_str.push_str("]");
write!(f, "{}", bytes_str).unwrap();
Ok(())
}
}
impl JsCore {
pub fn new() -> Self {
JsCore {
worker: Arc::new(TokioMutex::new(MainWorker::from_options(
main_module_url(),
PermissionsContainer::allow_all(),
main_worker_options(),
))),
}
}
async fn load_module(&self, file_path: String) -> Result<(), AnyError> {
let mut worker = self.worker.lock().await;
let url = resolve_url_or_path(&file_path, current_dir()?.as_path())?;
let module_id = worker.js_runtime.load_side_es_module(&url).await?;
let evaluate_fut = worker.js_runtime.mod_evaluate(module_id);
worker.js_runtime.with_event_loop_future(evaluate_fut, PollEventLoopOptions::default()).await?;
Ok(())
}
async fn init_engine(&self) {
let mut worker = self
.worker
.lock()
.await;
worker.bootstrap(BootstrapOptions::default());
worker
.execute_main_module(&main_module_url())
.await
.expect("init_engine(): could not execute main module");
}
fn event_loop(&self) -> EventLoopFuture {
let event_loop = EventLoopFuture::new(self.worker.clone());
event_loop
}
async fn execute_async_smart(
&self,
script: String
) -> Result<SmartGlobalVariableFuture<impl Future<Output = Result<v8::Global<v8::Value>, AnyError>>>, AnyError> {
let wrapped_script = format!(
r#"
(async () => {{
return ({});
}})();
"#, script
);
let resolve_fut = {
let mut worker = self.worker.lock().await;
let execute_async = worker.execute_script("js_core", wrapped_script.into());
worker.js_runtime.resolve(execute_async.unwrap().into())
};
Ok(SmartGlobalVariableFuture::new(self.worker.clone(), resolve_fut))
}
fn generate_execution_slot(
rx: Arc<TokioMutex<UnboundedReceiver<JsCoreRequest>>>,
js_core: JsCore,
) -> impl Future {
async move {
loop {
//info!("Execution slot loop running");
let mut maybe_request = rx.lock().await;
if let Some(request) = maybe_request.recv().await {
//info!("Got request: {:?}", request);
let script = request.script.clone();
let js_core_cloned = js_core.clone();
let response_tx = request.response_tx;
//global_req_id = Some(id.clone());
tokio::task::spawn_local(async move {
// info!("Spawn local driving: {}", id);
//let local_variable_name = uuid_to_valid_variable_name(&id);
let script_fut = js_core_cloned
.execute_async_smart(script)
.await
.expect("Couldn't create execute_async_smart future");
//info!("Script fut created: {}", id);
match script_fut.await {
Ok(res) => {
//info!("Script execution completed Succesfully: {}", id);
response_tx
.send(JsCoreResponse {
result: Ok(res),
})
.expect("couldn't send on channel");
}
Err(err) => {
error!("Error executing script: {:?}", err);
response_tx
.send(JsCoreResponse {
result: Err(err.to_string()),
})
.expect("couldn't send on channel");
}
}
});
}
//sleep(std::time::Duration::from_millis(10)).await;
tokio::task::yield_now().await;
}
}
}
pub async fn start(config: Ad4mConfig) -> JsCoreHandle {
let (tx_inside, rx_outside) = broadcast::channel::<JsCoreResponse>(50);
let (tx_outside, rx_inside) = mpsc::unbounded_channel::<JsCoreRequest>();
let rx_inside = Arc::new(TokioMutex::new(rx_inside));
let (tx_outside_loader, mut rx_inside_loader) = mpsc::unbounded_channel::<JsCoreRequest>();
let tx_inside_clone = tx_inside.clone();
std::thread::spawn(move || {
let rt = Builder::new_current_thread()
.thread_name(String::from("js_core"))
.enable_all()
.build()
.expect("Failed to create Tokio runtime");
let _guard = rt.enter();
let js_core = JsCore::new();
rt.block_on(async {
let result = js_core.init_engine().await;
info!("AD4M JS engine init completed, with result: {:?}", result);
let result = js_core
.execute_async_smart(format!("initCore({})", config.get_json()).into())
.await
.expect("to be able to create js execution future")
.await ;
match result {
Ok(res) => {
info!("AD4M coreInit() completed Succesfully: {:?}", res);
tx_inside
.send(JsCoreResponse {
result: Ok(String::from("initialized")),
})
.expect("couldn't send on channel");
}
Err(err) => {
error!("Error executing coreInit(): {:?}", err);
tx_inside
.send(JsCoreResponse {
result: Err(format!("Error executing coreInit(): {:?}", err)),
})
.expect("couldn't send on channel");
}
}
loop {
//info!("Main loop running");
//Listener future for loading JS modules into runtime
let module_load_fut = async {
loop {
//info!("Module load loop running");
if let Some(request) = rx_inside_loader.recv().await {
let script = request.script;
let js_core_cloned = js_core.clone();
let ts_response = request.response_tx;
tokio::task::spawn_local(async move {
match js_core_cloned.load_module(script).await {
Ok(()) => {
info!("Module loaded!");
ts_response
.send(JsCoreResponse {
result: Ok(String::from("")),
})
.expect("couldn't send on channel");
}
Err(err) => {
error!("Error loading module: {:?}", err);
ts_response
.send(JsCoreResponse {
result: Err(err.to_string()),
})
.expect("couldn't send on channel");
}
}
});
}
tokio::task::yield_now().await;
}
};
let local_set = tokio::task::LocalSet::new();
let holochain_local_set = tokio::task::LocalSet::new();
let module_load_local_set = tokio::task::LocalSet::new();
let holochain_signal_receiver_fut = async {
loop {
//info!("Holochain service loop");
if let Some(holochain_service) = maybe_get_holochain_service().await {
let mut stream_receiver = holochain_service.stream_receiver.lock().await;
if let Some(signal) = stream_receiver.recv().await {
match signal.clone() {
Signal::App {
cell_id,
zome_name,
signal: payload,
} => {
let js_core_cloned = js_core.clone();
tokio::task::spawn_local(async move {
// Handle the received signal here
let script = format!(
"await core.holochainService.handleCallback({{cell_id: [{:?}, {:?}], zome_name: '{}', signal: {}}})",
cell_id.dna_hash().get_raw_39().to_vec(), cell_id.agent_pubkey().get_raw_39().to_vec(), zome_name, ExternWrapper(payload.into_inner())
);
match js_core_cloned.execute_async_smart(script).await {
Ok(_res) => {
info!(
"Holochain Handle Callback Completed Succesfully",
);
}
Err(err) => {
error!("Error executing callback: {:?}", err);
}
}
});
},
Signal::System(_) => {
// Handle the received signal here
info!("Received system signal");
}
}
}
}
tokio::task::yield_now().await;
}
};
tokio::select! {
biased;
event_loop_result = js_core.event_loop() => {
match event_loop_result {
Ok(_) => {} //info!("AD4M event loop finished"),
Err(err) => {
error!("AD4M event loop closed with error: {}", err);
break;
}
}
}
_drive_local_set = local_set.run_until(Self::generate_execution_slot(rx_inside.clone(), js_core.clone())) => {
info!("AD4M drive local set completed");
}
_module_load = module_load_local_set.run_until(module_load_fut) => {
info!("AD4M module load completed");
//break;
}
_holochain_signal_receivers = holochain_local_set.run_until(holochain_signal_receiver_fut) => {
info!("AD4M holochain signal receiver completed");
}
}
}
})
});
let handle = JsCoreHandle {
rx: rx_outside,
tx: tx_outside,
tx_module_load: tx_outside_loader,
broadcast_tx: tx_inside_clone
};
//Set the JsCoreHandle to a global object so we can use it inside of deno op calls
let mut global_handle = JS_CORE_HANDLE.lock().await;
*global_handle = Some(handle.clone());
handle
}
}