Move comms from runtime to api component

This commit is contained in:
Nick O'Leary
2015-11-12 09:03:03 +00:00
parent 9f5e6a4b37
commit 8fb955e182
11 changed files with 145 additions and 109 deletions

View File

@@ -1,484 +0,0 @@
/**
* Copyright 2014, 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var should = require("should");
var sinon = require("sinon");
var when = require("when");
var http = require('http');
var express = require('express');
var app = express();
var WebSocket = require('ws');
var comms = require("../../../red/runtime/comms");
var Users = require("../../../red/api/auth/users");
var Tokens = require("../../../red/api/auth/tokens");
var address = '127.0.0.1';
var listenPort = 0; // use ephemeral port
describe("runtime/comms", function() {
describe("with default keepalive", function() {
var server;
var url;
var port;
before(function(done) {
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/comms';
comms.start();
done();
});
});
after(function() {
comms.stop();
});
it('accepts connection', function(done) {
var ws = new WebSocket(url);
ws.on('open', function() {
ws.close();
done();
});
});
it('publishes message after subscription', function(done) {
var ws = new WebSocket(url);
ws.on('open', function() {
ws.send('{"subscribe":"topic1"}');
comms.publish('topic1', 'foo');
});
ws.on('message', function(msg) {
msg.should.equal('{"topic":"topic1","data":"foo"}');
ws.close();
done();
});
});
it('publishes retained message for subscription', function(done) {
comms.publish('topic2', 'bar', true);
var ws = new WebSocket(url);
ws.on('open', function() {
ws.send('{"subscribe":"topic2"}');
});
ws.on('message', function(msg) {
msg.should.equal('{"topic":"topic2","data":"bar"}');
ws.close();
done();
});
});
it('retained message is deleted by non-retained message', function(done) {
comms.publish('topic3', 'retained', true);
comms.publish('topic3', 'non-retained');
var ws = new WebSocket(url);
ws.on('open', function() {
ws.send('{"subscribe":"topic3"}');
comms.publish('topic3', 'new');
});
ws.on('message', function(msg) {
msg.should.equal('{"topic":"topic3","data":"new"}');
ws.close();
done();
});
});
it('malformed messages are ignored',function(done) {
var ws = new WebSocket(url);
ws.on('open', function() {
ws.send('not json');
ws.send('[]');
ws.send('{"subscribe":"topic3"}');
comms.publish('topic3', 'correct');
});
ws.on('message', function(msg) {
msg.should.equal('{"topic":"topic3","data":"correct"}');
ws.close();
done();
});
});
// The following test currently fails due to minimum viable
// implementation. More test should be written to test topic
// matching once this one is passing
if (0) {
it('receives message on correct topic', function(done) {
var ws = new WebSocket(url);
ws.on('open', function() {
ws.send('{"subscribe":"topic4"}');
comms.publish('topic5', 'foo');
comms.publish('topic4', 'bar');
});
ws.on('message', function(msg) {
msg.should.equal('{"topic":"topic4","data":"bar"}');
ws.close();
done();
});
});
}
});
describe("disabled editor", function() {
var server;
var url;
var port;
before(function(done) {
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {disableEditor:true});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/comms';
comms.start();
done();
});
});
after(function() {
comms.stop();
});
it('rejects websocket connections',function(done) {
var ws = new WebSocket(url);
ws.on('open', function() {
done(new Error("Socket connection unexpectedly accepted"));
ws.close();
});
ws.on('error', function() {
done();
});
});
});
describe("non-default httpAdminRoot set: /adminPath", function() {
var server;
var url;
var port;
before(function(done) {
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {httpAdminRoot:"/adminPath"});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/adminPath/comms';
comms.start();
done();
});
});
after(function() {
comms.stop();
});
it('accepts connections',function(done) {
var ws = new WebSocket(url);
ws.on('open', function() {
ws.close();
done();
});
ws.on('error', function() {
done(new Error("Socket connection failed"));
});
});
});
describe("non-default httpAdminRoot set: /adminPath/", function() {
var server;
var url;
var port;
before(function(done) {
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {httpAdminRoot:"/adminPath/"});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/adminPath/comms';
comms.start();
done();
});
});
after(function() {
comms.stop();
});
it('accepts connections',function(done) {
var ws = new WebSocket(url);
ws.on('open', function() {
ws.close();
done();
});
ws.on('error', function() {
done(new Error("Socket connection failed"));
});
});
});
describe("non-default httpAdminRoot set: adminPath", function() {
var server;
var url;
var port;
before(function(done) {
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {httpAdminRoot:"adminPath"});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/adminPath/comms';
comms.start();
done();
});
});
after(function() {
comms.stop();
});
it('accepts connections',function(done) {
var ws = new WebSocket(url);
ws.on('open', function() {
ws.close();
done();
});
ws.on('error', function() {
done(new Error("Socket connection failed"));
});
});
});
describe("keep alives", function() {
var server;
var url;
var port;
before(function(done) {
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {webSocketKeepAliveTime: 100});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/comms';
comms.start();
done();
});
});
after(function() {
comms.stop();
});
it('are sent', function(done) {
var ws = new WebSocket(url);
var count = 0;
ws.on('message', function(data) {
var msg = JSON.parse(data);
msg.should.have.property('topic','hb');
msg.should.have.property('data').be.a.Number;
count++;
if (count == 3) {
ws.close();
done();
}
});
});
it('are not sent if other messages are sent', function(done) {
var ws = new WebSocket(url);
var count = 0;
var interval;
ws.on('open', function() {
ws.send('{"subscribe":"foo"}');
interval = setInterval(function() {
comms.publish('foo', 'bar');
}, 50);
});
ws.on('message', function(data) {
var msg = JSON.parse(data);
// It is possible a heartbeat message may arrive - so ignore them
if (msg.topic != "hb") {
msg.should.have.property('topic', 'foo');
msg.should.have.property('data', 'bar');
count++;
if (count == 5) {
clearInterval(interval);
ws.close();
done();
}
}
});
});
});
describe('authentication required, no anonymous',function() {
var server;
var url;
var port;
var getDefaultUser;
var getUser;
var getToken;
before(function(done) {
getDefaultUser = sinon.stub(Users,"default",function() { return when.resolve(null);});
getUser = sinon.stub(Users,"get", function(username) {
if (username == "fred") {
return when.resolve({permissions:"read"});
} else {
return when.resolve(null);
}
});
getToken = sinon.stub(Tokens,"get",function(token) {
if (token == "1234") {
return when.resolve({user:"fred",scope:["*"]});
} else if (token == "5678") {
return when.resolve({user:"barney",scope:["*"]});
} else {
return when.resolve(null);
}
});
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {adminAuth:{}});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/comms';
comms.start();
done();
});
});
after(function() {
getDefaultUser.restore();
getUser.restore();
getToken.restore();
comms.stop();
});
it('prevents connections that do not authenticate',function(done) {
var ws = new WebSocket(url);
var count = 0;
var interval;
ws.on('open', function() {
ws.send('{"subscribe":"foo"}');
});
ws.on('close', function() {
done();
});
});
it('allows connections that do authenticate',function(done) {
var ws = new WebSocket(url);
var received = 0;
ws.on('open', function() {
ws.send('{"auth":"1234"}');
});
ws.on('message', function(msg) {
received++;
if (received == 1) {
msg.should.equal('{"auth":"ok"}');
ws.send('{"subscribe":"foo"}');
comms.publish('foo', 'correct');
} else {
msg.should.equal('{"topic":"foo","data":"correct"}');
ws.close();
}
});
ws.on('close', function() {
try {
received.should.equal(2);
done();
} catch(err) {
done(err);
}
});
});
it('rejects connections for non-existant token',function(done) {
var ws = new WebSocket(url);
var received = 0;
ws.on('open', function() {
ws.send('{"auth":"2345"}');
});
ws.on('close', function() {
done();
});
});
it('rejects connections for invalid token',function(done) {
var ws = new WebSocket(url);
var received = 0;
ws.on('open', function() {
ws.send('{"auth":"5678"}');
});
ws.on('close', function() {
done();
});
});
});
describe('authentication required, anonymous enabled',function() {
var server;
var url;
var port;
var getDefaultUser;
before(function(done) {
getDefaultUser = sinon.stub(Users,"default",function() { return when.resolve({permissions:"read"});});
server = http.createServer(function(req,res){app(req,res)});
comms.init(server, {adminAuth:{}});
server.listen(listenPort, address);
server.on('listening', function() {
port = server.address().port;
url = 'http://' + address + ':' + port + '/comms';
comms.start();
done();
});
});
after(function() {
getDefaultUser.restore();
comms.stop();
});
it('allows anonymous connections that do not authenticate',function(done) {
var ws = new WebSocket(url);
var count = 0;
var interval;
ws.on('open', function() {
ws.send('{"subscribe":"foo"}');
setTimeout(function() {
comms.publish('foo', 'correct');
},200);
});
ws.on('message', function(msg) {
msg.should.equal('{"topic":"foo","data":"correct"}');
count++;
ws.close();
});
ws.on('close', function() {
try {
count.should.equal(1);
done();
} catch(err) {
done(err);
}
});
});
});
});

View File

@@ -21,19 +21,12 @@ var path = require("path");
var api = require("../../../red/api");
var runtime = require("../../../red/runtime");
var comms = require("../../../red/runtime/comms");
var redNodes = require("../../../red/runtime/nodes");
var storage = require("../../../red/runtime/storage");
var settings = require("../../../red/runtime/settings");
var log = require("../../../red/runtime/log");
describe("runtime", function() {
var commsMessages = [];
var commsPublish;
beforeEach(function() {
commsMessages = [];
});
afterEach(function() {
if (console.log.restore) {
console.log.restore();
@@ -41,13 +34,9 @@ describe("runtime", function() {
})
before(function() {
commsPublish = sinon.stub(comms,"publish", function(topic,msg,retained) {
commsMessages.push({topic:topic,msg:msg,retained:retained});
});
process.env.NODE_RED_HOME = path.resolve(path.join(__dirname,"..","..",".."))
});
after(function() {
commsPublish.restore();
delete process.env.NODE_RED_HOME;
});
@@ -55,32 +44,26 @@ describe("runtime", function() {
beforeEach(function() {
sinon.stub(log,"init",function() {});
sinon.stub(settings,"init",function() {});
sinon.stub(comms,"init",function() {});
});
afterEach(function() {
log.init.restore();
settings.init.restore();
comms.init.restore();
})
it("initialises components", function() {
var dummyServer = {};
runtime.init(dummyServer,{testSettings: true, httpAdminRoot:"/"});
runtime.init({testSettings: true, httpAdminRoot:"/"});
log.init.called.should.be.true;
settings.init.called.should.be.true;
comms.init.called.should.be.true;
});
it("returns version", function() {
var dummyServer = {};
runtime.init(dummyServer,{testSettings: true, httpAdminRoot:"/"});
runtime.init({testSettings: true, httpAdminRoot:"/"});
/^\d+\.\d+\.\d+(-git)?$/.test(runtime.version()).should.be.true;
})
});
describe("start",function() {
var commsInit;
var storageInit;
var settingsLoad;
var logMetric;
@@ -93,10 +76,8 @@ describe("runtime", function() {
var redNodesGetNodeList;
var redNodesLoadFlows;
var redNodesStartFlows;
var commsStart;
beforeEach(function() {
commsInit = sinon.stub(comms,"init",function() {});
storageInit = sinon.stub(storage,"init",function(settings) {return when.resolve();});
logMetric = sinon.stub(log,"metric",function() { return false; });
logWarn = sinon.stub(log,"warn",function() { });
@@ -107,10 +88,8 @@ describe("runtime", function() {
redNodesCleanModuleList = sinon.stub(redNodes,"cleanModuleList",function(){});
redNodesLoadFlows = sinon.stub(redNodes,"loadFlows",function() {return when.resolve()});
redNodesStartFlows = sinon.stub(redNodes,"startFlows",function() {});
commsStart = sinon.stub(comms,"start",function(){});
});
afterEach(function() {
commsInit.restore();
storageInit.restore();
logMetric.restore();
logWarn.restore();
@@ -122,7 +101,6 @@ describe("runtime", function() {
redNodesCleanModuleList.restore();
redNodesLoadFlows.restore();
redNodesStartFlows.restore();
commsStart.restore();
});
it("reports errored/missing modules",function(done) {
redNodesGetNodeList = sinon.stub(redNodes,"getNodeList", function(cb) {
@@ -131,7 +109,7 @@ describe("runtime", function() {
{ module:"module",enabled:true,loaded:false,types:["typeA","typeB"]} // missing
].filter(cb);
});
runtime.init({},{testSettings: true, httpAdminRoot:"/", load:function() { return when.resolve();}});
runtime.init({testSettings: true, httpAdminRoot:"/", load:function() { return when.resolve();}});
sinon.stub(console,"log");
runtime.start().then(function() {
console.log.restore();
@@ -139,7 +117,6 @@ describe("runtime", function() {
storageInit.calledOnce.should.be.true;
redNodesInit.calledOnce.should.be.true;
redNodesLoad.calledOnce.should.be.true;
commsStart.calledOnce.should.be.true;
redNodesLoadFlows.calledOnce.should.be.true;
logWarn.calledWithMatch("Failed to register 1 node type");
@@ -162,7 +139,7 @@ describe("runtime", function() {
].filter(cb);
});
var serverInstallModule = sinon.stub(redNodes,"installModule",function(name) { return when.resolve();});
runtime.init({},{testSettings: true, autoInstallModules:true, httpAdminRoot:"/", load:function() { return when.resolve();}});
runtime.init({testSettings: true, autoInstallModules:true, httpAdminRoot:"/", load:function() { return when.resolve();}});
sinon.stub(console,"log");
runtime.start().then(function() {
console.log.restore();
@@ -188,7 +165,7 @@ describe("runtime", function() {
{ err:"errored",name:"errName" } // error
].filter(cb);
});
runtime.init({},{testSettings: true, verbose:true, httpAdminRoot:"/", load:function() { return when.resolve();}});
runtime.init({testSettings: true, verbose:true, httpAdminRoot:"/", load:function() { return when.resolve();}});
sinon.stub(console,"log");
runtime.start().then(function() {
console.log.restore();
@@ -203,12 +180,11 @@ describe("runtime", function() {
});
it("reports runtime metrics",function(done) {
var commsStop = sinon.stub(comms,"stop",function() {} );
var stopFlows = sinon.stub(redNodes,"stopFlows",function() {} );
redNodesGetNodeList = sinon.stub(redNodes,"getNodeList", function() {return []});
logMetric.restore();
logMetric = sinon.stub(log,"metric",function() { return true; });
runtime.init({},{testSettings: true, runtimeMetricInterval:200, httpAdminRoot:"/", load:function() { return when.resolve();}});
runtime.init({testSettings: true, runtimeMetricInterval:200, httpAdminRoot:"/", load:function() { return when.resolve();}});
sinon.stub(console,"log");
runtime.start().then(function() {
console.log.restore();
@@ -226,7 +202,6 @@ describe("runtime", function() {
done(err);
} finally {
runtime.stop();
commsStop.restore();
stopFlows.restore();
}
},300);
@@ -237,15 +212,9 @@ describe("runtime", function() {
});
it("stops components", function() {
var commsStop = sinon.stub(comms,"stop",function() {} );
var stopFlows = sinon.stub(redNodes,"stopFlows",function() {} );
runtime.stop();
commsStop.called.should.be.true;
stopFlows.called.should.be.true;
commsStop.restore();
stopFlows.restore();
});
});

View File

@@ -19,7 +19,6 @@ var sinon = require('sinon');
var RedNode = require("../../../../red/runtime/nodes/Node");
var Log = require("../../../../red/runtime/log");
var flows = require("../../../../red/runtime/nodes/flows");
var comms = require("../../../../red/runtime/comms");
describe('Node', function() {
describe('#constructor',function() {
@@ -512,9 +511,6 @@ describe('Node', function() {
});
describe('#status', function() {
after(function() {
comms.publish.restore();
});
it('publishes status', function(done) {
sinon.stub(flows,"handleStatus", function(node,message,msg) {});
var n = new RedNode({id:'123',type:'abc'});
@@ -522,18 +518,9 @@ describe('Node', function() {
var topic;
var message;
var retain;
sinon.stub(comms, 'publish', function(_topic, _message, _retain) {
topic = _topic;
message = _message;
retain = _retain;
});
n.status(status);
topic.should.equal('status/123');
message.should.equal(status);
retain.should.be.true;
flows.handleStatus.called.should.be.true;
flows.handleStatus.args[0][0].should.eql(n);
flows.handleStatus.args[0][1].should.eql(status);