Skip to content

Commit 1838a64

Browse files
committed
fix: token release logic
1 parent 3cadeb3 commit 1838a64

File tree

2 files changed

+13
-14
lines changed

2 files changed

+13
-14
lines changed

src/dialer/dial-request.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -47,21 +47,21 @@ class DialRequest {
4747
const tokenHolder = new FIFO()
4848
tokens.forEach(token => tokenHolder.push(token))
4949
const dialAbortControllers = this.addrs.map(() => new AbortController())
50-
let startedDials = 0
50+
let completedDials = 0
5151

5252
try {
5353
return await pAny(this.addrs.map(async (addr, i) => {
5454
const token = await tokenHolder.shift() // get token
55-
startedDials++
5655
let conn
5756
try {
5857
const signal = dialAbortControllers[i].signal
5958
conn = await this.dialAction(addr, { ...options, signal: anySignal([signal, options.signal]) })
6059
// Remove the successful AbortController so it is not aborted
6160
dialAbortControllers.splice(i, 1)
6261
} finally {
63-
// If we have more dials to make, recycle the token, otherwise release it
64-
if (startedDials < this.addrs.length) {
62+
completedDials++
63+
// If we have more or equal dials remaining than tokens, recycle the token, otherwise release it
64+
if (this.addrs.length - completedDials >= tokens.length) {
6565
tokenHolder.push(token)
6666
} else {
6767
this.dialer.releaseToken(tokens.splice(tokens.indexOf(token), 1)[0])

test/dialing/dial-request.spec.js

+9-10
Original file line numberDiff line numberDiff line change
@@ -53,16 +53,11 @@ describe('Dial Request', () => {
5353

5454
it('should release tokens when all addr dials have started', async () => {
5555
const mockConnection = await createMockConnection()
56+
const firstDials = pDefer()
5657
const deferred = pDefer()
5758
const actions = {
58-
1: async () => {
59-
await delay(0)
60-
return Promise.reject(error)
61-
},
62-
2: async () => {
63-
await delay(0)
64-
return Promise.reject(error)
65-
},
59+
1: () => firstDials.promise,
60+
2: () => firstDials.promise,
6661
3: () => deferred.promise
6762
}
6863
const dialAction = (num) => actions[num]()
@@ -85,15 +80,19 @@ describe('Dial Request', () => {
8580
sinon.spy(dialer, 'releaseToken')
8681
dialRequest.run({ signal: controller.signal })
8782
// Let the first dials run
88-
await delay(100)
83+
await delay(0)
84+
85+
// Finish the first 2 dials
86+
firstDials.reject(error)
87+
await delay(0)
8988

9089
// Only 1 dial should remain, so 1 token should have been released
9190
expect(actions[1]).to.have.property('callCount', 1)
9291
expect(actions[2]).to.have.property('callCount', 1)
9392
expect(actions[3]).to.have.property('callCount', 1)
9493
expect(dialer.releaseToken).to.have.property('callCount', 1)
9594

96-
// Finish the dial
95+
// Finish the dial and release the 2nd token
9796
deferred.resolve(mockConnection)
9897
await delay(0)
9998
expect(dialer.releaseToken).to.have.property('callCount', 2)

0 commit comments

Comments
 (0)