Skip to content

Commit

Permalink
FIX hasLeader() is mixing up states
Browse files Browse the repository at this point in the history
  • Loading branch information
pubkey committed Mar 23, 2023
1 parent 69c76a4 commit c5369e8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
10 changes: 7 additions & 3 deletions src/leader-election-web-lock.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,19 @@ export const LeaderElectionWebLock = function (broadcastChannel, options) {
this._dpLC = false; // true when onduplicate called

this._wKMC = {}; // stuff for cleanup

// lock name
this.lN = 'pubkey-bc||' + broadcastChannel.method.type + '||' + broadcastChannel.name;

};



LeaderElectionWebLock.prototype = {
hasLeader() {
return navigator.locks.query().then(locks => {
if (locks.held && locks.held.length > 0) {
const relevantLocks = locks.held ? locks.held.filter(lock => lock.name === this.lN) : [];
if (relevantLocks && relevantLocks.length > 0) {
return true;
} else {
return false;
Expand All @@ -46,9 +51,8 @@ LeaderElectionWebLock.prototype = {
this._wKMC.rej = rej;
});
this._wLMP = new Promise((res) => {
const lockId = 'pubkey-bc||' + this.broadcastChannel.method.type + '||' + this.broadcastChannel.name;
navigator.locks.request(
lockId,
this.lN,
{
signal: this._wKMC.c.signal
},
Expand Down
15 changes: 14 additions & 1 deletion test/integration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,7 @@ function runTest(channelOptions) {
console.log('Finished: ' + JSON.stringify(channelOptions));
});
});
describe('.hasLeader', () => {
describe('.hasLeader()', () => {
it('should have hasLeader=true after election has run', async () => {
const channelName = AsyncTestUtil.randomString(12);
const channel = new BroadcastChannel(channelName, channelOptions);
Expand All @@ -662,6 +662,19 @@ function runTest(channelOptions) {
await AsyncTestUtil.waitUntil(async () => (await elector.hasLeader()) === true);
await AsyncTestUtil.waitUntil(async () => (await elector2.hasLeader()) === true);

channel.close();
channel2.close();
});
it('should not mix up hasLeader() state from other channel', async () => {
const channel = new BroadcastChannel(AsyncTestUtil.randomString(12), channelOptions);
const channel2 = new BroadcastChannel(AsyncTestUtil.randomString(12), channelOptions);
const elector = createLeaderElection(channel);
const elector2 = createLeaderElection(channel2);

await elector.awaitLeadership();
const has = await elector2.hasLeader();
assert.strictEqual(has, false);

channel.close();
channel2.close();
});
Expand Down

0 comments on commit c5369e8

Please sign in to comment.