Skip to content

Commit

Permalink
Merge pull request #789 from bucko13/indexer-listeners
Browse files Browse the repository at this point in the history
add ability to track listeners and remove them on close for indexer
  • Loading branch information
braydonf committed Jul 3, 2019
2 parents 4f7e79b + f4b7400 commit fed7f29
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
19 changes: 13 additions & 6 deletions lib/indexer/indexer.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ class Indexer extends EventEmitter {

this.db = null;
this.batch = null;
this.bound = [];
this.syncing = false;
this.height = 0;
}
Expand Down Expand Up @@ -122,12 +123,17 @@ class Indexer extends EventEmitter {
}

/**
* Close the indexer, wait for the database to close.
* Close the indexer, wait for the database to close,
* unbind all events.
* @returns {Promise}
*/

async close() {
return this.db.close();
await this.db.close();
for (const [event, listener] of this.bound)
this.chain.removeListener(event, listener);

this.bound.length = 0;
}

/**
Expand Down Expand Up @@ -187,7 +193,7 @@ class Indexer extends EventEmitter {
}

/**
* Bind to chain events.
* Bind to chain events and save listeners for removal on close
* @private
*/

Expand All @@ -202,9 +208,10 @@ class Indexer extends EventEmitter {
}
};

this.chain.on('connect', listener);
this.chain.on('disconnect', listener);
this.chain.on('reset', listener);
for (const event of ['connect', 'disconnect', 'reset']) {
this.bound.push([event, listener]);
this.chain.on(event, listener);
}
}

/**
Expand Down
20 changes: 20 additions & 0 deletions test/indexer-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
'use strict';

const assert = require('bsert');
const EventEmitter = require('events');
const reorg = require('./util/reorg');
const Script = require('../lib/script/script');
const Opcode = require('../lib/script/opcode');
Expand Down Expand Up @@ -320,6 +321,25 @@ describe('Indexer', function() {
message: 'Limit above max of 10.'
});
});

it('should track bound chain events and remove on close', async () => {
const indexer = new AddrIndexer({
blocks: {},
chain: new EventEmitter()
});

const events = ['connect', 'disconnect', 'reset'];

await indexer.open();

for (const event of events)
assert.equal(indexer.chain.listeners(event).length, 1);

await indexer.close();

for (const event of events)
assert.equal(indexer.chain.listeners(event).length, 0);
});
});

describe('Index 10 blocks', function() {
Expand Down

0 comments on commit fed7f29

Please sign in to comment.