2020-01-21 03:49:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
|
|
|
use super::dispatch_json::{JsonOp, Value};
|
|
|
|
use crate::ops::json_op;
|
2020-02-08 14:34:31 -05:00
|
|
|
use crate::state::State;
|
2020-02-11 04:04:59 -05:00
|
|
|
use crate::worker::WorkerEvent;
|
2020-01-21 03:49:47 -05:00
|
|
|
use deno_core::*;
|
|
|
|
use futures;
|
2020-02-11 04:04:59 -05:00
|
|
|
use futures::channel::mpsc;
|
|
|
|
use futures::sink::SinkExt;
|
2020-01-21 03:49:47 -05:00
|
|
|
use std;
|
|
|
|
use std::convert::From;
|
|
|
|
|
2020-02-11 04:04:59 -05:00
|
|
|
pub fn web_worker_op<D>(
|
|
|
|
sender: mpsc::Sender<WorkerEvent>,
|
|
|
|
dispatcher: D,
|
|
|
|
) -> impl Fn(Value, Option<ZeroCopyBuf>) -> Result<JsonOp, ErrBox>
|
|
|
|
where
|
|
|
|
D: Fn(
|
|
|
|
&mpsc::Sender<WorkerEvent>,
|
|
|
|
Value,
|
|
|
|
Option<ZeroCopyBuf>,
|
|
|
|
) -> Result<JsonOp, ErrBox>,
|
|
|
|
{
|
|
|
|
move |args: Value, zero_copy: Option<ZeroCopyBuf>| -> Result<JsonOp, ErrBox> {
|
|
|
|
dispatcher(&sender, args, zero_copy)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn init(i: &mut Isolate, s: &State, sender: &mpsc::Sender<WorkerEvent>) {
|
2020-01-21 03:49:47 -05:00
|
|
|
i.register_op(
|
|
|
|
"worker_post_message",
|
2020-02-11 04:04:59 -05:00
|
|
|
s.core_op(json_op(web_worker_op(
|
|
|
|
sender.clone(),
|
|
|
|
op_worker_post_message,
|
|
|
|
))),
|
2020-01-21 03:49:47 -05:00
|
|
|
);
|
|
|
|
i.register_op(
|
2020-02-11 04:04:59 -05:00
|
|
|
"worker_close",
|
|
|
|
s.core_op(json_op(web_worker_op(sender.clone(), op_worker_close))),
|
2020-01-21 03:49:47 -05:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Post message to host as guest worker
|
|
|
|
fn op_worker_post_message(
|
2020-02-11 04:04:59 -05:00
|
|
|
sender: &mpsc::Sender<WorkerEvent>,
|
2020-01-21 03:49:47 -05:00
|
|
|
_args: Value,
|
2020-01-24 15:10:49 -05:00
|
|
|
data: Option<ZeroCopyBuf>,
|
2020-01-21 03:49:47 -05:00
|
|
|
) -> Result<JsonOp, ErrBox> {
|
|
|
|
let d = Vec::from(data.unwrap().as_ref()).into_boxed_slice();
|
2020-02-11 04:04:59 -05:00
|
|
|
let mut sender = sender.clone();
|
|
|
|
let fut = sender.send(WorkerEvent::Message(d));
|
|
|
|
futures::executor::block_on(fut).expect("Failed to post message to host");
|
|
|
|
Ok(JsonOp::Sync(json!({})))
|
|
|
|
}
|
2020-01-21 03:49:47 -05:00
|
|
|
|
2020-02-11 04:04:59 -05:00
|
|
|
/// Notify host that guest worker closes
|
|
|
|
fn op_worker_close(
|
|
|
|
sender: &mpsc::Sender<WorkerEvent>,
|
|
|
|
_args: Value,
|
|
|
|
_data: Option<ZeroCopyBuf>,
|
|
|
|
) -> Result<JsonOp, ErrBox> {
|
|
|
|
let mut sender = sender.clone();
|
|
|
|
sender.close_channel();
|
2020-01-21 03:49:47 -05:00
|
|
|
Ok(JsonOp::Sync(json!({})))
|
|
|
|
}
|