Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement backwards-compatible discovery API that uses mDNS #89

Merged
merged 2 commits into from
Jul 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion dist/lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ class Client extends _eventemitter.default {
}

this.api.notifications().then(result => {
this.notifications = _objectSpread({}, this.notifications, {}, flattenTree(result));
this.notifications = _objectSpread(_objectSpread({}, this.notifications), flattenTree(result));
Object.keys(this.notifications).forEach(path => {
const notification = _objectSpread({
path
Expand Down
2 changes: 1 addition & 1 deletion dist/lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ class Connection extends _eventemitter.default {
}

if (this._authenticated === true && !path.includes('auth/login')) {
opts.headers = _objectSpread({}, opts.headers, {
opts.headers = _objectSpread(_objectSpread({}, opts.headers), {}, {
Authorization: "".concat(this._token.kind, " ").concat(this._token.token)
});
opts.credentials = 'same-origin';
Expand Down
112 changes: 74 additions & 38 deletions dist/lib/discovery.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ require("core-js/modules/es.string.includes");

require("core-js/modules/es.string.split");

require("core-js/modules/es.string.starts-with");

require("core-js/modules/es.string.trim");

Object.defineProperty(exports, "__esModule", {
Expand Down Expand Up @@ -62,7 +64,7 @@ class SKServer {

createClient() {
let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return new _client.default(_objectSpread({}, opts, {
return new _client.default(_objectSpread(_objectSpread({}, opts), {}, {
hostname: this._hostname,
port: this._port
}));
Expand All @@ -73,62 +75,96 @@ class SKServer {
exports.SKServer = SKServer;

class Discovery extends _eventemitter.default {
constructor(bonjour) {
constructor(bonjourOrMdns) {
let timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 60000;
super();
const props = ['_server', '_registry'].join(',');
this.found = [];

if (!bonjour || typeof bonjour !== 'object' || Object.keys(bonjour).join(',') !== props) {
throw new Error('Invalid mDNS provider');
if (!bonjourOrMdns || typeof bonjourOrMdns !== 'object') {
throw new Error('No mDNS provider given');
}

this.found = [];
const browser = bonjour.find({
type: 'signalk-http'
});
browser.on('up', ad => {
const service = _objectSpread({}, ad.txt, {
name: ad.name || '',
hostname: ad.host || '',
port: parseInt(ad.port, 10)
});

if (service.hasOwnProperty('roles') && typeof service.roles === 'string' && service.roles.includes(',')) {
service.roles = service.roles.split(',').map(role => role.trim().toLowerCase());
}

if (service.hasOwnProperty('roles') && typeof service.roles === 'string' && !service.roles.includes(',')) {
service.roles = [service.roles].map(role => role.trim().toLowerCase());
}
const bonjourProps = ['_server', '_registry'].join(',');
const mdnsProps = ['dns_sd', 'Advertisement', 'createAdvertisement', 'Browser'].join(',');

let ipv4 = service.hostname;
if (Object.keys(bonjourOrMdns).join(',').startsWith(bonjourProps)) {
return this.discoverWithBonjour(bonjourOrMdns, timeout);
}

if (Array.isArray(ad.addresses)) {
ipv4 = ad.addresses.reduce((found, address) => {
if (address && typeof address === 'string' && address.includes('.')) {
found = address;
}
if (Object.keys(bonjourOrMdns).join(',').startsWith(mdnsProps)) {
return this.discoverWithMdns(bonjourOrMdns, timeout);
}

return found;
}, service.hostname);
}
throw new Error('Unrecognized mDNS provider given');
}

if (ipv4.trim() !== '') {
service.hostname = ipv4;
discoverWithBonjour(bonjour, timeout) {
const browser = bonjour.find({
type: 'signalk-http'
});
browser.on('up', ad => this.handleDiscoveredService(ad, _objectSpread(_objectSpread({}, ad.txt), {}, {
name: ad.name || '',
hostname: ad.host || '',
port: parseInt(ad.port, 10),
provider: 'bonjour'
})));
setTimeout(() => {
if (this.found.length === 0) {
this.emit('timeout');
}

const server = new SKServer(service);
this.found.push(server);
this.emit('found', server);
});
browser.stop();
}, timeout);
browser.start();
}

discoverWithMdns(mDNS, timeout) {
const browser = mDNS.createBrowser(mDNS.tcp('_signalk-http'));
browser.on('serviceUp', ad => this.handleDiscoveredService(ad, _objectSpread(_objectSpread({}, ad.txtRecord), {}, {
hostname: ad.host || '',
port: parseInt(ad.port, 10),
provider: 'mdns'
})));
browser.on('error', err => this.handleDiscoveryError(err));
setTimeout(() => {
if (this.found.length === 0) {
this.emit('timeout');
}

browser.stop();
}, timeout);
browser.start();
}

handleDiscoveryError(err) {
console.error("Error during discovery: ".concat(err.message));
}

handleDiscoveredService(ad, service) {
if (typeof service.roles === 'string') {
service.roles = service.roles.split(',').map(role => role.trim().toLowerCase());
}

service.roles = Array.isArray(service.roles) ? service.roles : [];
let ipv4 = service.hostname;

if (Array.isArray(ad.addresses)) {
ipv4 = ad.addresses.reduce((found, address) => {
if (address && typeof address === 'string' && address.includes('.')) {
found = address;
}

return found;
}, service.hostname);
}

if (ipv4.trim() !== '') {
service.hostname = ipv4;
}

const server = new SKServer(service);
this.found.push(server);
this.emit('found', server);
}

}
Expand Down
2 changes: 1 addition & 1 deletion dist/lib/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ class Request extends _eventemitter.default {
response,
receivedAt
});
this.emit('response', _objectSpread({}, response, {
this.emit('response', _objectSpread(_objectSpread({}, response), {}, {
request: {
receivedAt,
name: this.name,
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"casper-chai": "^0.3.0",
"chai": "^4.1.0",
"freeport-promise": "^1.1.0",
"mdns": "^2.5.1",
"mocha": "^6.0.2",
"signalk-server": "^1.28.0"
},
Expand Down
130 changes: 87 additions & 43 deletions src/lib/discovery.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,108 +11,152 @@ import EventEmitter from 'eventemitter3'
import Client from './client'

export class SKServer {
constructor (service) {
constructor(service) {
this._roles = service.roles || ['master', 'main']
this._self = service.self || ''
this._version = service.version || '0.0.0'
this._hostname = service.hostname
this._port = service.port
}

get roles () {
get roles() {
return this._roles
}

get self () {
get self() {
return this._self
}

get version () {
get version() {
return this._version
}

get hostname () {
get hostname() {
return this._hostname
}

get port () {
get port() {
return this._port
}

isMain () {
isMain() {
return this._roles.includes('main')
}

isMaster () {
isMaster() {
return this._roles.includes('master')
}

createClient (opts = {}) {
createClient(opts = {}) {
return new Client({
...opts,
hostname: this._hostname,
port: this._port
port: this._port,
})
}
}

export default class Discovery extends EventEmitter {
constructor (bonjour, timeout = 60000) {
constructor(bonjourOrMdns, timeout = 60000) {
super()

const props = [ '_server', '_registry' ].join(',')
this.found = []

if (!bonjour || typeof bonjour !== 'object' || Object.keys(bonjour).join(',') !== props) {
throw new Error('Invalid mDNS provider')
if (!bonjourOrMdns || typeof bonjourOrMdns !== 'object') {
throw new Error('No mDNS provider given')
}

this.found = []
const bonjourProps = ['_server', '_registry'].join(',')
const mdnsProps = ['dns_sd', 'Advertisement', 'createAdvertisement', 'Browser'].join(',')

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we testing that the order of the keys is exactly this and these are the first keys?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

First keys was just bcs I didn't want to compare every key, seemed uncessary. My thinking re the order was that, if the order didn't match, chances are that it's a different module with similar methods or a very different version of the module. That way we have a loose version check, which would catch any major changes to those modules (i.e. fingerprinting)

I would have preferred a way to check the modules identity, but I don't think that's possible besides fingerprinting. If you know of a better way that allows us to check that a module is mdns or bonjour, and that the version is within a supported range, I'm all ears :)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would just call hasOwnProperty on the prop names and be done with it. Relying on the order seems needlessly brittle.

if (Object.keys(bonjourOrMdns).join(',').startsWith(bonjourProps)) {
return this.discoverWithBonjour(bonjourOrMdns, timeout)
}

if (Object.keys(bonjourOrMdns).join(',').startsWith(mdnsProps)) {
return this.discoverWithMdns(bonjourOrMdns, timeout)
}

throw new Error('Unrecognized mDNS provider given')
}

discoverWithBonjour(bonjour, timeout) {
const browser = bonjour.find({ type: 'signalk-http' })

browser.on('up', ad => {
const service = {
browser.on('up', (ad) =>
this.handleDiscoveredService(ad, {
...ad.txt,
name: ad.name || '',
hostname: ad.host || '',
port: parseInt(ad.port, 10)
}
port: parseInt(ad.port, 10),
provider: 'bonjour',
})
)

if (service.hasOwnProperty('roles') && typeof service.roles === 'string' && service.roles.includes(',')) {
service.roles = service.roles.split(',').map(role => role.trim().toLowerCase())
setTimeout(() => {
if (this.found.length === 0) {
this.emit('timeout')
}

if (service.hasOwnProperty('roles') && typeof service.roles === 'string' && !service.roles.includes(',')) {
service.roles = [ service.roles ].map(role => role.trim().toLowerCase())
}
browser.stop()
}, timeout)

let ipv4 = service.hostname
browser.start()
}

if (Array.isArray(ad.addresses)) {
ipv4 = ad.addresses.reduce((found, address) => {
if (address && typeof address === 'string' && address.includes('.')) {
found = address
}
return found
}, service.hostname)
}
discoverWithMdns(mDNS, timeout) {
const browser = mDNS.createBrowser(mDNS.tcp('_signalk-http'))

if (ipv4.trim() !== '') {
service.hostname = ipv4
}
browser.on('serviceUp', (ad) =>
this.handleDiscoveredService(ad, {
...ad.txtRecord,
hostname: ad.host || '',
port: parseInt(ad.port, 10),
provider: 'mdns',
})
)

const server = new SKServer(service)
this.found.push(server)
this.emit('found', server)
})

browser.start()
browser.on('error', (err) => this.handleDiscoveryError(err))

setTimeout(() => {
if (this.found.length === 0) {
this.emit('timeout')
}

browser.stop()
}, timeout)

browser.start()
}

handleDiscoveryError(err) {
console.error(`Error during discovery: ${err.message}`)
}

handleDiscoveredService(ad, service) {
if (typeof service.roles === 'string') {
service.roles = service.roles.split(',').map((role) => role.trim().toLowerCase())
}

service.roles = Array.isArray(service.roles) ? service.roles : []

let ipv4 = service.hostname

if (Array.isArray(ad.addresses)) {
ipv4 = ad.addresses.reduce((found, address) => {
if (address && typeof address === 'string' && address.includes('.')) {
found = address
}
return found
}, service.hostname)
}

if (ipv4.trim() !== '') {
service.hostname = ipv4
}

const server = new SKServer(service)
this.found.push(server)
this.emit('found', server)
}
}
Loading