split mesh ui/work, change client/worker contract

This commit is contained in:
Stewart Allen 2021-12-27 16:24:39 -05:00
commit 5153fb2ad9
5 changed files with 198 additions and 145 deletions

View file

@ -13,7 +13,6 @@ if (moto.worker) return;
// allow license to inject module
self.gapp = self.gapp || moto;
let isinit = false;
let endpoints = {};
// code is running in the worker / server context
@ -21,74 +20,52 @@ const dispatch = moto.worker = {
register: (name, fn) => {
endpoints[name] = fn;
sync(name);
},
send: (msg) => {
self.postMessage(msg);
},
sync: (name) => {
if (name) {
if (isinit) dispatch.send({register: [name]});
} else {
dispatch.send({register: Object.keys(endpoints)});
}
},
onmessage: (e) => {
if (e.data === '--init--') {
isinit = true;
dispatch.sync();
return;
}
let time_recv = time(),
msg = e.data || {},
let msg = e.data,
run = endpoints[msg.task],
done = false,
send = {
data : function(data,direct) {
dispatch.send({
seq: msg.seq,
task: msg.task,
done: false,
data: data
}, direct);
data: (data, direct) => {
if (canSend(data)) {
dispatch.send({ done: false, data: data }, direct);
}
},
done : function(data,direct) {
dispatch.send({
seq: msg.seq,
task: msg.task,
done: true,
data: data
}, direct);
done: (data, direct) => {
if (canSend(data)) {
dispatch.send({ done: true, data: data }, direct);
done = true;
}
},
error: (data) => {
dispatch.send({ error: data });
}
},
canSend = (data) => {
if (done) {
console.log("unexpected reply dropped", {data, msg});
}
return !done;
};
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()});
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 });
}
} else {
console.log({worker_unhandled: e, msg, fn: dispatch[msg.task]});
console.log({worker_unhandled: e});
send.error(`no registered endpoint: ${msg.task}`);
}
}