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
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use std::marker::PhantomData;
use std::rc::{Rc, Weak};
use gloo_utils::window;
use js_sys::Array;
use web_sys::{Blob, BlobPropertyBag, Url};
use crate::bridge::{CallbackMap, WorkerBridge};
use crate::codec::{Bincode, Codec};
use crate::handler_id::HandlerId;
use crate::messages::FromWorker;
use crate::native_worker::{DedicatedWorker, NativeWorkerExt};
use crate::traits::Worker;
use crate::{Callback, Shared};
fn create_worker(path: &str) -> DedicatedWorker {
let js_shim_url = Url::new_with_base(
path,
&window().location().href().expect("failed to read href."),
)
.expect("failed to create url for javascript entrypoint")
.to_string();
let wasm_url = js_shim_url.replace(".js", "_bg.wasm");
let array = Array::new();
array.push(
&format!(
r#"importScripts("{}");wasm_bindgen("{}");"#,
js_shim_url, wasm_url
)
.into(),
);
let blob = Blob::new_with_str_sequence_and_options(
&array,
BlobPropertyBag::new().type_("application/javascript"),
)
.unwrap();
let url = Url::create_object_url_with_blob(&blob).unwrap();
DedicatedWorker::new(&url).expect("failed to spawn worker")
}
#[derive(Clone)]
pub struct WorkerSpawner<W, CODEC = Bincode>
where
W: Worker,
CODEC: Codec,
{
_marker: PhantomData<(W, CODEC)>,
callback: Option<Callback<W::Output>>,
}
impl<W, CODEC> fmt::Debug for WorkerSpawner<W, CODEC>
where
W: Worker,
CODEC: Codec,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("WorkerScope<_>")
}
}
impl<W, CODEC> Default for WorkerSpawner<W, CODEC>
where
W: Worker,
CODEC: Codec,
{
fn default() -> Self {
Self::new()
}
}
impl<W, CODEC> WorkerSpawner<W, CODEC>
where
W: Worker,
CODEC: Codec,
{
pub fn new() -> Self {
Self {
_marker: PhantomData,
callback: None,
}
}
pub fn encoding<C>(&mut self) -> WorkerSpawner<W, C>
where
C: Codec,
{
WorkerSpawner {
_marker: PhantomData,
callback: self.callback.clone(),
}
}
pub fn callback<F>(&mut self, cb: F) -> &mut Self
where
F: 'static + Fn(W::Output),
{
self.callback = Some(Rc::new(cb));
self
}
pub fn spawn(&self, path: &str) -> WorkerBridge<W> {
let pending_queue = Rc::new(RefCell::new(Some(Vec::new())));
let handler_id = HandlerId::new();
let mut callbacks = HashMap::new();
if let Some(m) = self.callback.as_ref().map(Rc::downgrade) {
callbacks.insert(handler_id, m);
}
let callbacks: Shared<CallbackMap<W>> = Rc::new(RefCell::new(callbacks));
let worker = {
let pending_queue = pending_queue.clone();
let callbacks = callbacks.clone();
let worker = create_worker(path);
let handler = {
let worker = worker.clone();
move |msg: FromWorker<W>| match msg {
FromWorker::WorkerLoaded => {
if let Some(pending_queue) = pending_queue.borrow_mut().take() {
for to_worker in pending_queue.into_iter() {
worker.post_packed_message::<_, CODEC>(to_worker);
}
}
}
FromWorker::ProcessOutput(id, output) => {
let mut callbacks = callbacks.borrow_mut();
if let Some(m) = callbacks.get(&id) {
if let Some(m) = Weak::upgrade(m) {
m(output);
} else {
callbacks.remove(&id);
}
}
}
}
};
worker.set_on_packed_message::<_, CODEC, _>(handler);
worker
};
WorkerBridge::<W>::new::<CODEC>(
handler_id,
worker,
pending_queue,
callbacks,
self.callback.clone(),
)
}
}