@@ -11,6 +11,7 @@ const { AbortError } = require('libp2p-interfaces/src/transport/errors')
11
11
const AbortController = require ( 'abort-controller' )
12
12
const AggregateError = require ( 'aggregate-error' )
13
13
const pDefer = require ( 'p-defer' )
14
+ const delay = require ( 'delay' )
14
15
15
16
const { DialRequest } = require ( '../../src/dialer/dial-request' )
16
17
const createMockConnection = require ( '../utils/mockConnection' )
@@ -50,6 +51,54 @@ describe('Dial Request', () => {
50
51
expect ( dialer . releaseToken ) . to . have . property ( 'callCount' , tokens . length )
51
52
} )
52
53
54
+ it ( 'should release tokens when all addr dials have started' , async ( ) => {
55
+ const mockConnection = await createMockConnection ( )
56
+ const deferred = pDefer ( )
57
+ 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
+ } ,
66
+ 3 : ( ) => deferred . promise
67
+ }
68
+ const dialAction = ( num ) => actions [ num ] ( )
69
+ const tokens = [ 'a' , 'b' ]
70
+ const controller = new AbortController ( )
71
+ const dialer = {
72
+ getTokens : ( ) => [ ...tokens ] ,
73
+ releaseToken : ( ) => { }
74
+ }
75
+
76
+ const dialRequest = new DialRequest ( {
77
+ addrs : Object . keys ( actions ) ,
78
+ dialer,
79
+ dialAction
80
+ } )
81
+
82
+ sinon . spy ( actions , 1 )
83
+ sinon . spy ( actions , 2 )
84
+ sinon . spy ( actions , 3 )
85
+ sinon . spy ( dialer , 'releaseToken' )
86
+ dialRequest . run ( { signal : controller . signal } )
87
+ // Let the first dials run
88
+ await delay ( 10 )
89
+
90
+ // Only 1 dial should remain, so 1 token should have been released
91
+ expect ( actions [ 1 ] ) . to . have . property ( 'callCount' , 1 )
92
+ expect ( actions [ 2 ] ) . to . have . property ( 'callCount' , 1 )
93
+ expect ( actions [ 3 ] ) . to . have . property ( 'callCount' , 1 )
94
+ expect ( dialer . releaseToken ) . to . have . property ( 'callCount' , 1 )
95
+
96
+ // Finish the dial
97
+ deferred . resolve ( mockConnection )
98
+ await delay ( 0 )
99
+ expect ( dialer . releaseToken ) . to . have . property ( 'callCount' , 2 )
100
+ } )
101
+
53
102
it ( 'should throw an AggregateError if all dials fail' , async ( ) => {
54
103
const actions = {
55
104
1 : ( ) => Promise . reject ( error ) ,
0 commit comments