Skip to content

Commit 2509772

Browse files
authored
fix: ensure stream is closed when protocol is incorrect (#471)
Close the stream in a finally block so we always close it regardless of what happened.
1 parent c4fbc01 commit 2509772

File tree

1 file changed

+19
-19
lines changed

1 file changed

+19
-19
lines changed

src/network.js

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -239,23 +239,7 @@ export class Network {
239239
const connection = await this._libp2p.dial(peer)
240240
const stream = await connection.newStream([BITSWAP120, BITSWAP110, BITSWAP100])
241241

242-
/** @type {Uint8Array} */
243-
let serialized
244-
switch (stream.stat.protocol) {
245-
case BITSWAP100:
246-
serialized = msg.serializeToBitswap100()
247-
break
248-
case BITSWAP110:
249-
case BITSWAP120:
250-
serialized = msg.serializeToBitswap110()
251-
break
252-
default:
253-
throw new Error('Unknown protocol: ' + stream.stat.protocol)
254-
}
255-
256-
await writeMessage(stream, serialized, this._log)
257-
258-
stream.close()
242+
await writeMessage(stream, msg, this._log)
259243

260244
this._updateSentStats(peer, msg.blocks)
261245
}
@@ -297,17 +281,33 @@ export class Network {
297281
/**
298282
*
299283
* @param {Stream} stream
300-
* @param {Uint8Array} msg
284+
* @param {Message} msg
301285
* @param {*} log
302286
*/
303287
async function writeMessage (stream, msg, log) {
304288
try {
289+
/** @type {Uint8Array} */
290+
let serialized
291+
switch (stream.stat.protocol) {
292+
case BITSWAP100:
293+
serialized = msg.serializeToBitswap100()
294+
break
295+
case BITSWAP110:
296+
case BITSWAP120:
297+
serialized = msg.serializeToBitswap110()
298+
break
299+
default:
300+
throw new Error('Unknown protocol: ' + stream.stat.protocol)
301+
}
302+
305303
await pipe(
306-
[msg],
304+
[serialized],
307305
lp.encode(),
308306
stream
309307
)
310308
} catch (err) {
311309
log(err)
310+
} finally {
311+
stream.close()
312312
}
313313
}

0 commit comments

Comments
 (0)