2021-12-26 19:43:48 -05:00
|
|
|
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
|
|
|
|
|
|
|
|
|
|
"use strict";
|
|
|
|
|
|
|
|
|
|
(function() {
|
|
|
|
|
|
2021-12-29 00:19:22 -05:00
|
|
|
let moto = self.moto = self.moto || {};
|
2021-12-26 19:43:48 -05:00
|
|
|
|
2021-12-26 22:00:31 -05:00
|
|
|
if (moto.worker) return;
|
|
|
|
|
|
2021-12-29 00:19:22 -05:00
|
|
|
gapp.register('moto.worker');
|
2021-12-26 22:00:31 -05:00
|
|
|
|
|
|
|
|
let endpoints = {};
|
2021-12-26 19:43:48 -05:00
|
|
|
|
|
|
|
|
// code is running in the worker / server context
|
2021-12-26 22:00:31 -05:00
|
|
|
const dispatch = moto.worker = {
|
|
|
|
|
|
2021-12-27 18:13:11 -05:00
|
|
|
bind: (name, fn) => {
|
2021-12-26 22:00:31 -05:00
|
|
|
endpoints[name] = fn;
|
2021-12-27 18:13:11 -05:00
|
|
|
dispatch.send({bind: name});
|
2021-12-26 22:00:31 -05:00
|
|
|
},
|
2021-12-26 19:43:48 -05:00
|
|
|
|
|
|
|
|
send: (msg) => {
|
|
|
|
|
self.postMessage(msg);
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
onmessage: (e) => {
|
2021-12-27 16:24:39 -05:00
|
|
|
let msg = e.data,
|
2021-12-26 22:00:31 -05:00
|
|
|
run = endpoints[msg.task],
|
2021-12-27 16:24:39 -05:00
|
|
|
done = false,
|
2021-12-26 19:43:48 -05:00
|
|
|
send = {
|
2021-12-27 16:24:39 -05:00
|
|
|
data: (data, direct) => {
|
|
|
|
|
if (canSend(data)) {
|
|
|
|
|
dispatch.send({ done: false, data: data }, direct);
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
done: (data, direct) => {
|
|
|
|
|
if (canSend(data)) {
|
|
|
|
|
dispatch.send({ done: true, data: data }, direct);
|
|
|
|
|
done = true;
|
|
|
|
|
}
|
2021-12-26 19:43:48 -05:00
|
|
|
},
|
2021-12-27 16:24:39 -05:00
|
|
|
error: (data) => {
|
2021-12-27 20:39:07 -05:00
|
|
|
if (canSend(data)) {
|
|
|
|
|
done = true;
|
|
|
|
|
dispatch.send({ error: data });
|
|
|
|
|
}
|
2021-12-27 16:24:39 -05:00
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
canSend = (data) => {
|
|
|
|
|
if (done) {
|
|
|
|
|
console.log("unexpected reply dropped", {data, msg});
|
2021-12-26 19:43:48 -05:00
|
|
|
}
|
2021-12-27 16:24:39 -05:00
|
|
|
return !done;
|
2021-12-26 19:43:48 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if (run) {
|
|
|
|
|
try {
|
2021-12-27 16:24:39 -05:00
|
|
|
let data = run(msg.data, send);
|
|
|
|
|
if (data) {
|
|
|
|
|
send.done(data);
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.trace(error.stack);
|
|
|
|
|
dispatch.send({ data: {error: error.toString()}, done: true });
|
2021-12-26 19:43:48 -05:00
|
|
|
}
|
|
|
|
|
} else {
|
2021-12-27 16:24:39 -05:00
|
|
|
console.log({worker_unhandled: e});
|
|
|
|
|
send.error(`no registered endpoint: ${msg.task}`);
|
2021-12-26 19:43:48 -05:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// attach onmessage hanler
|
|
|
|
|
self.onmessage = dispatch.onmessage;
|
|
|
|
|
|
|
|
|
|
})();
|