grid-apps-cmms/src/moto/worker.js

99 lines
2.5 KiB
JavaScript
Raw Normal View History

2021-12-26 19:43:48 -05:00
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
"use strict";
(function() {
2021-12-26 22:00:31 -05:00
let moto = self.moto = self.moto || {},
2021-12-26 19:43:48 -05:00
time = Date.now;
2021-12-26 22:00:31 -05:00
if (moto.worker) return;
2021-12-26 19:43:48 -05:00
// allow license to inject module
2021-12-26 22:00:31 -05:00
self.gapp = self.gapp || moto;
let isinit = false;
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 = {
register: (name, fn) => {
endpoints[name] = fn;
sync(name);
},
2021-12-26 19:43:48 -05:00
send: (msg) => {
self.postMessage(msg);
},
2021-12-26 22:00:31 -05:00
sync: (name) => {
if (name) {
if (isinit) dispatch.send({register: [name]});
} else {
dispatch.send({register: Object.keys(endpoints)});
}
},
2021-12-26 19:43:48 -05:00
onmessage: (e) => {
if (e.data === '--init--') {
2021-12-26 22:00:31 -05:00
isinit = true;
dispatch.sync();
2021-12-26 19:43:48 -05:00
return;
}
let time_recv = time(),
msg = e.data || {},
2021-12-26 22:00:31 -05:00
run = endpoints[msg.task],
2021-12-26 19:43:48 -05:00
send = {
data : function(data,direct) {
dispatch.send({
seq: msg.seq,
task: msg.task,
done: false,
data: data
}, direct);
},
done : function(data,direct) {
dispatch.send({
seq: msg.seq,
task: msg.task,
done: true,
data: data
}, direct);
}
};
if (run) {
try {
let time_xfer = (time_recv - msg.time),
output = run(msg.data, send),
time_send = time(),
time_proc = time_send - time_recv;
if (output) dispatch.send({
seq: msg.seq,
task: msg.task,
time_send: time_xfer,
time_proc: time_proc,
// replaced on reply side
time_recv: time(),
data: output
});
} catch (wrkerr) {
// console.log(wrkerr);
console.trace(wrkerr.stack);
send.done({error: wrkerr.toString()});
}
} else {
console.log({worker_unhandled: e, msg, fn: dispatch[msg.task]});
}
}
};
// attach onmessage hanler
self.onmessage = dispatch.onmessage;
})();