Initial commit

master
Avril 4 years ago
commit 86cff91d9d
Signed by: flanchan
GPG Key ID: 284488987C31F630

2
.gitignore vendored

@ -0,0 +1,2 @@
*~
node_modules/

@ -0,0 +1,116 @@
const Stage = require('stage-js');
function Dispatcher() {
this.hooks = [];
}
Dispatcher.prototype.hook = function(cb) {
this.hooks.push(cb);
return this.hooks.length-1;
};
Dispatcher.prototype.unhook = function(index) {
this.hooks[index] = null;
};
Dispatcher.prototype.signal = function(value) {
for(const cb of this.hooks) {
if(cb) cb.apply(this, [value]);
}
};
Dispatcher.prototype.clear = function() {
this.hooks = [];
};
const addEventListenerHack = (to, ev, lam) => {
to.addEventListener(ev, lam);
return lam;
};
const socket_dispatcher = (ws) => {
const disp = new Dispatcher();
const pusher = new Stage();
let closed=false;
disp.socket = ws;
const h0 = ws.addEventListener('message', (ev) => pusher.give(ev.data));
const h1 = ws.addEventListener('close', () => pusher.commit());
(async () => {
while ( (msg = await pusher.take()) !== undefined)
disp.signal({op: 'message', value: msg});
disp.signal({op: 'close'});
})();
disp.close = () => {
if(!closed) {
ws.removeEventListener('message', h0);
ws.removeEventListener('close', h1);
pusher.commit();
closed=true;
}
};
disp.send = (msg) => {
if(!closed) {
ws.send(msg);
}
};
return disp;
};
function MessageQueue(ws, filter, apply) {
this.socket = socket_dispatcher(ws);
this.filter = filter || (()=>true);
this.apply = apply || ((o) => o);
const stage = this.stage = new Stage();
const base = this;
this.hook = this.socket.hook((msg) => {
if (msg)
{
switch(msg.op)
{
case 'close':
base.close();
break;
case 'message':
stage.give(msg.value);
break;
default:
//uhh
break;
}
}
});
}
const MQ = MessageQueue.prototype;
MQ.close = () => {
this.socket.unhook(this.hook);
this.stage.commit();
this.socket.close();
};
MQ.send = async (value) => {
const awaiter = this.stage.take();
this.socket.send(this.apply(value));
const ret = await awaiter;
};
MQ.read = () => this.stage.take();
MQ.oneshot = async (value) => {
const ret = await this.send(value);
this.close();
return ret;
};
if(module)
module.exports = MessageQueue;

13
package-lock.json generated

@ -0,0 +1,13 @@
{
"name": "@username/message-queue",
"version": "0.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@notflan/stage-js": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/@notflan/stage-js/-/stage-js-0.1.0.tgz",
"integrity": "sha512-oEkEgLBPB4ghtV1XE6j6gWoX6C3x8BcBjLCpdXTADTKU8q7qAJeM3tP7/fFgrVst5CXR9RtOcXri/kAltuek5g=="
}
}
}

@ -0,0 +1,18 @@
{
"name": "@username/message-queue",
"version": "0.0.0",
"description": "Await on websocket messages",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"async"
],
"author": "Avril",
"license": "GPL-3.0-or-later",
"dependencies": {
"@notflan/stage-js": "^0.1.0"
},
"devDependencies": {}
}
Loading…
Cancel
Save