Skip to content

Commit

Permalink
Remove useless event listener when outside of cluster mode
Browse files Browse the repository at this point in the history
  • Loading branch information
FabienChaynes authored and zbjornson committed Jul 31, 2021
1 parent c7b9a9d commit bfeabc2
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 21 deletions.
42 changes: 22 additions & 20 deletions lib/cluster.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,27 +180,29 @@ function addListeners() {
}
});
}
}

// Respond to master's requests for worker's local metrics.
process.on('message', message => {
if (cluster().isWorker && message.type === GET_METRICS_REQ) {
Promise.all(registries.map(r => r.getMetricsAsJSON()))
.then(metrics => {
process.send({
type: GET_METRICS_RES,
requestId: message.requestId,
metrics,
});
})
.catch(error => {
process.send({
type: GET_METRICS_RES,
requestId: message.requestId,
error: error.message,
});
});
if (cluster().isWorker) {
// Respond to master's requests for worker's local metrics.
process.on('message', message => {
if (message.type === GET_METRICS_REQ) {
Promise.all(registries.map(r => r.getMetricsAsJSON()))
.then(metrics => {
process.send({
type: GET_METRICS_RES,
requestId: message.requestId,
metrics,
});
})
.catch(error => {
process.send({
type: GET_METRICS_RES,
requestId: message.requestId,
error: error.message,
});
});
}
});
}
});
}

module.exports = AggregatorRegistry;
17 changes: 16 additions & 1 deletion test/clusterTest.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
'use strict';

const cluster = require('cluster');
const process = require('process');

describe('AggregatorRegistry', () => {
it('requiring the cluster should not add any listeners', () => {
it('requiring the cluster should not add any listeners on the cluster module', () => {
const originalListenerCount = cluster.listenerCount('message');

require('../lib/cluster');
Expand All @@ -17,6 +18,20 @@ describe('AggregatorRegistry', () => {
expect(cluster.listenerCount('message')).toBe(originalListenerCount);
});

it('requiring the cluster should not add any listeners on the process module', () => {
const originalListenerCount = process.listenerCount('message');

require('../lib/cluster');

expect(process.listenerCount('message')).toBe(originalListenerCount);

jest.resetModules();

require('../lib/cluster');

expect(process.listenerCount('message')).toBe(originalListenerCount);
});

describe('aggregatorRegistry.clusterMetrics()', () => {
it('works properly if there are no cluster workers', async () => {
const AggregatorRegistry = require('../lib/cluster');
Expand Down

0 comments on commit bfeabc2

Please sign in to comment.