@libp2p/tcp 8.0.13-c960eb659 → 8.0.13-d8f5bc211

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/listener.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import net from 'net'
2
2
  import { CodeError } from '@libp2p/interface/errors'
3
3
  import { TypedEventEmitter, CustomEvent } from '@libp2p/interface/events'
4
- import { logger } from '@libp2p/logger'
5
4
  import { CODE_P2P } from './constants.js'
6
5
  import { toMultiaddrConnection } from './socket-to-conn.js'
7
6
  import {
@@ -10,21 +9,20 @@ import {
10
9
  type NetConfig
11
10
  } from './utils.js'
12
11
  import type { TCPCreateListenerOptions } from './index.js'
12
+ import type { ComponentLogger, Logger, LoggerOptions } from '@libp2p/interface'
13
13
  import type { MultiaddrConnection, Connection } from '@libp2p/interface/connection'
14
14
  import type { CounterGroup, MetricGroup, Metrics } from '@libp2p/interface/metrics'
15
15
  import type { Listener, ListenerEvents, Upgrader } from '@libp2p/interface/transport'
16
16
  import type { Multiaddr } from '@multiformats/multiaddr'
17
17
 
18
- const log = logger('libp2p:tcp:listener')
19
-
20
18
  /**
21
19
  * Attempts to close the given maConn. If a failure occurs, it will be logged
22
20
  */
23
- async function attemptClose (maConn: MultiaddrConnection): Promise<void> {
21
+ async function attemptClose (maConn: MultiaddrConnection, options: LoggerOptions): Promise<void> {
24
22
  try {
25
23
  await maConn.close()
26
24
  } catch (err) {
27
- log.error('an error occurred closing the connection', err)
25
+ options.log.error('an error occurred closing the connection', err)
28
26
  }
29
27
  }
30
28
 
@@ -45,6 +43,7 @@ interface Context extends TCPCreateListenerOptions {
45
43
  backlog?: number
46
44
  metrics?: Metrics
47
45
  closeServerOnMaxConnections?: CloseServerOnMaxConnectionsOpts
46
+ logger: ComponentLogger
48
47
  }
49
48
 
50
49
  export interface TCPListenerMetrics {
@@ -78,12 +77,15 @@ export class TCPListener extends TypedEventEmitter<ListenerEvents> implements Li
78
77
  private status: Status = { code: TCPListenerStatusCode.INACTIVE }
79
78
  private metrics?: TCPListenerMetrics
80
79
  private addr: string
80
+ private readonly log: Logger
81
81
 
82
82
  constructor (private readonly context: Context) {
83
83
  super()
84
84
 
85
85
  context.keepAlive = context.keepAlive ?? true
86
+ context.noDelay = context.noDelay ?? true
86
87
 
88
+ this.log = context.logger.forComponent('libp2p:tcp:listener')
87
89
  this.addr = 'unknown'
88
90
  this.server = net.createServer(context, this.onSocket.bind(this))
89
91
 
@@ -172,7 +174,7 @@ export class TCPListener extends TypedEventEmitter<ListenerEvents> implements Li
172
174
  }
173
175
  // Avoid uncaught errors caused by unstable connections
174
176
  socket.on('error', err => {
175
- log('socket error', err)
177
+ this.log('socket error', err)
176
178
  this.metrics?.events.increment({ [`${this.addr} error`]: true })
177
179
  })
178
180
 
@@ -183,19 +185,20 @@ export class TCPListener extends TypedEventEmitter<ListenerEvents> implements Li
183
185
  socketInactivityTimeout: this.context.socketInactivityTimeout,
184
186
  socketCloseTimeout: this.context.socketCloseTimeout,
185
187
  metrics: this.metrics?.events,
186
- metricPrefix: `${this.addr} `
188
+ metricPrefix: `${this.addr} `,
189
+ logger: this.context.logger
187
190
  })
188
191
  } catch (err) {
189
- log.error('inbound connection failed', err)
192
+ this.log.error('inbound connection failed', err)
190
193
  this.metrics?.errors.increment({ [`${this.addr} inbound_to_connection`]: true })
191
194
  return
192
195
  }
193
196
 
194
- log('new inbound connection %s', maConn.remoteAddr)
197
+ this.log('new inbound connection %s', maConn.remoteAddr)
195
198
  try {
196
199
  this.context.upgrader.upgradeInbound(maConn)
197
200
  .then((conn) => {
198
- log('inbound connection upgraded %s', maConn.remoteAddr)
201
+ this.log('inbound connection upgraded %s', maConn.remoteAddr)
199
202
  this.connections.add(maConn)
200
203
 
201
204
  socket.once('close', () => {
@@ -210,7 +213,7 @@ export class TCPListener extends TypedEventEmitter<ListenerEvents> implements Li
210
213
  // we can do. resume() will be called again every time a connection is dropped, which
211
214
  // acts as an eventual retry mechanism. onListenError allows the consumer act on this.
212
215
  this.resume().catch(e => {
213
- log.error('error attempting to listen server once connection count under limit', e)
216
+ this.log.error('error attempting to listen server once connection count under limit', e)
214
217
  this.context.closeServerOnMaxConnections?.onListenError?.(e as Error)
215
218
  })
216
219
  }
@@ -225,27 +228,31 @@ export class TCPListener extends TypedEventEmitter<ListenerEvents> implements Li
225
228
  this.connections.size >= this.context.closeServerOnMaxConnections.closeAbove
226
229
  ) {
227
230
  this.pause(false).catch(e => {
228
- log.error('error attempting to close server once connection count over limit', e)
231
+ this.log.error('error attempting to close server once connection count over limit', e)
229
232
  })
230
233
  }
231
234
 
232
235
  this.dispatchEvent(new CustomEvent<Connection>('connection', { detail: conn }))
233
236
  })
234
237
  .catch(async err => {
235
- log.error('inbound connection failed', err)
238
+ this.log.error('inbound connection failed', err)
236
239
  this.metrics?.errors.increment({ [`${this.addr} inbound_upgrade`]: true })
237
240
 
238
- await attemptClose(maConn)
241
+ await attemptClose(maConn, {
242
+ log: this.log
243
+ })
239
244
  })
240
245
  .catch(err => {
241
- log.error('closing inbound connection failed', err)
246
+ this.log.error('closing inbound connection failed', err)
242
247
  })
243
248
  } catch (err) {
244
- log.error('inbound connection failed', err)
249
+ this.log.error('inbound connection failed', err)
245
250
 
246
- attemptClose(maConn)
251
+ attemptClose(maConn, {
252
+ log: this.log
253
+ })
247
254
  .catch(err => {
248
- log.error('closing inbound connection failed', err)
255
+ this.log.error('closing inbound connection failed', err)
249
256
  this.metrics?.errors.increment({ [`${this.addr} inbound_closing_failed`]: true })
250
257
  })
251
258
  }
@@ -276,7 +283,7 @@ export class TCPListener extends TypedEventEmitter<ListenerEvents> implements Li
276
283
  addrs = addrs.concat(getMultiaddrs('ip6', address.address, address.port))
277
284
  }
278
285
  } catch (err) {
279
- log.error('could not turn %s:%s into multiaddr', address.address, address.port, err)
286
+ this.log.error('could not turn %s:%s into multiaddr', address.address, address.port, err)
280
287
  }
281
288
  }
282
289
 
@@ -310,9 +317,11 @@ export class TCPListener extends TypedEventEmitter<ListenerEvents> implements Li
310
317
  async close (): Promise<void> {
311
318
  // Close connections and server the same time to avoid any race condition
312
319
  await Promise.all([
313
- Promise.all(Array.from(this.connections.values()).map(async maConn => attemptClose(maConn))),
320
+ Promise.all(Array.from(this.connections.values()).map(async maConn => attemptClose(maConn, {
321
+ log: this.log
322
+ }))),
314
323
  this.pause(true).catch(e => {
315
- log.error('error attempting to close server once connection count over limit', e)
324
+ this.log.error('error attempting to close server once connection count over limit', e)
316
325
  })
317
326
  ])
318
327
  }
@@ -334,7 +343,7 @@ export class TCPListener extends TypedEventEmitter<ListenerEvents> implements Li
334
343
  })
335
344
 
336
345
  this.status = { ...this.status, code: TCPListenerStatusCode.ACTIVE }
337
- log('Listening on %s', this.server.address())
346
+ this.log('Listening on %s', this.server.address())
338
347
  }
339
348
 
340
349
  private async pause (permanent: boolean): Promise<void> {
@@ -347,7 +356,7 @@ export class TCPListener extends TypedEventEmitter<ListenerEvents> implements Li
347
356
  return
348
357
  }
349
358
 
350
- log('Closing server on %s', this.server.address())
359
+ this.log('Closing server on %s', this.server.address())
351
360
 
352
361
  // NodeJS implementation tracks listening status with `this._handle` property.
353
362
  // - Server.close() sets this._handle to null immediately. If this._handle is null, ERR_SERVER_NOT_RUNNING is thrown
@@ -1,17 +1,15 @@
1
1
  import { CodeError } from '@libp2p/interface/errors'
2
- import { logger } from '@libp2p/logger'
3
2
  import { ipPortToMultiaddr as toMultiaddr } from '@libp2p/utils/ip-port-to-multiaddr'
4
3
  // @ts-expect-error no types
5
4
  import toIterable from 'stream-to-it'
6
5
  import { CLOSE_TIMEOUT, SOCKET_TIMEOUT } from './constants.js'
7
6
  import { multiaddrToNetConfig } from './utils.js'
7
+ import type { ComponentLogger } from '@libp2p/interface'
8
8
  import type { MultiaddrConnection } from '@libp2p/interface/connection'
9
9
  import type { CounterGroup } from '@libp2p/interface/metrics'
10
10
  import type { AbortOptions, Multiaddr } from '@multiformats/multiaddr'
11
11
  import type { Socket } from 'net'
12
12
 
13
- const log = logger('libp2p:tcp:socket')
14
-
15
13
  interface ToConnectionOptions {
16
14
  listeningAddr?: Multiaddr
17
15
  remoteAddr?: Multiaddr
@@ -20,6 +18,7 @@ interface ToConnectionOptions {
20
18
  socketCloseTimeout?: number
21
19
  metrics?: CounterGroup
22
20
  metricPrefix?: string
21
+ logger: ComponentLogger
23
22
  }
24
23
 
25
24
  /**
@@ -27,6 +26,7 @@ interface ToConnectionOptions {
27
26
  * https://github.com/libp2p/interface-transport#multiaddrconnection
28
27
  */
29
28
  export const toMultiaddrConnection = (socket: Socket, options: ToConnectionOptions): MultiaddrConnection => {
29
+ const log = options.logger.forComponent('libp2p:tcp:socket')
30
30
  const metrics = options.metrics
31
31
  const metricPrefix = options.metricPrefix ?? ''
32
32
  const inactivityTimeout = options.socketInactivityTimeout ?? SOCKET_TIMEOUT
@@ -182,7 +182,9 @@ export const toMultiaddrConnection = (socket: Socket, options: ToConnectionOptio
182
182
  log('%s socket abort due to error', lOptsStr, err)
183
183
 
184
184
  socket.destroy(err)
185
- }
185
+ },
186
+
187
+ log
186
188
  }
187
189
 
188
190
  return maConn
package/src/utils.ts CHANGED
@@ -22,7 +22,7 @@ export function multiaddrToNetConfig (addr: Multiaddr, config: NetConfig = {}):
22
22
  }
23
23
 
24
24
  // tcp listening
25
- return { ...addr.toOptions(), ...config }
25
+ return { ...config, ...addr.toOptions() }
26
26
  }
27
27
 
28
28
  export function getMultiaddrs (proto: 'ip4' | 'ip6', ip: string, port: number): Multiaddr[] {