Skip to content

Commit a89818a

Browse files
committed
refactor: Refactored config to be done inside services (libp2p#1573)
1 parent 0d4c8e4 commit a89818a

File tree

9 files changed

+157
-148
lines changed

9 files changed

+157
-148
lines changed

packages/libp2p/src/autonat/index.ts

+16-16
Original file line numberDiff line numberDiff line change
@@ -109,14 +109,23 @@ class DefaultAutoNATService implements Startable {
109109
private started: boolean
110110

111111
constructor (components: AutoNATComponents, init: AutoNATServiceInit) {
112+
const validatedConfig = object({
113+
protocolPrefix: string().default(PROTOCOL_PREFIX),
114+
timeout: number().integer().default(TIMEOUT),
115+
startupDelay: number().integer().default(STARTUP_DELAY),
116+
refreshInterval: number().integer().default(REFRESH_INTERVAL),
117+
maxInboundStreams: number().integer().default(MAX_INBOUND_STREAMS),
118+
maxOutboundStreams: number().integer().default(MAX_OUTBOUND_STREAMS)
119+
}).validateSync(init)
120+
112121
this.components = components
113122
this.started = false
114-
this.protocol = `/${init.protocolPrefix}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`
115-
this.timeout = init.timeout ?? TIMEOUT
116-
this.maxInboundStreams = init.maxInboundStreams ?? MAX_INBOUND_STREAMS
117-
this.maxOutboundStreams = init.maxOutboundStreams ?? MAX_OUTBOUND_STREAMS
118-
this.startupDelay = init.startupDelay ?? STARTUP_DELAY
119-
this.refreshInterval = init.refreshInterval ?? REFRESH_INTERVAL
123+
this.protocol = `/${validatedConfig.protocolPrefix}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`
124+
this.timeout = validatedConfig.timeout
125+
this.maxInboundStreams = validatedConfig.maxInboundStreams
126+
this.maxOutboundStreams = validatedConfig.maxOutboundStreams
127+
this.startupDelay = validatedConfig.startupDelay
128+
this.refreshInterval = validatedConfig.refreshInterval
120129
this._verifyExternalAddresses = this._verifyExternalAddresses.bind(this)
121130
}
122131

@@ -588,16 +597,7 @@ class DefaultAutoNATService implements Startable {
588597
}
589598

590599
export function autoNATService (init: AutoNATServiceInit = {}): (components: AutoNATComponents) => unknown {
591-
const validatedConfig = object({
592-
protocolPrefix: string().default(PROTOCOL_PREFIX),
593-
timeout: number().integer().default(TIMEOUT),
594-
startupDelay: number().integer().default(STARTUP_DELAY),
595-
refreshInterval: number().integer().default(REFRESH_INTERVAL),
596-
maxInboundStreams: number().integer().default(MAX_INBOUND_STREAMS),
597-
maxOutboundStreams: number().integer().default(MAX_OUTBOUND_STREAMS)
598-
}).validateSync(init)
599-
600600
return (components) => {
601-
return new DefaultAutoNATService(components, validatedConfig)
601+
return new DefaultAutoNATService(components, init)
602602
}
603603
}

packages/libp2p/src/circuit-relay/server/index.ts

+19-22
Original file line numberDiff line numberDiff line change
@@ -100,10 +100,6 @@ export interface RelayServerEvents {
100100
'relay:advert:error': CustomEvent<Error>
101101
}
102102

103-
const defaults = {
104-
maxOutboundStopStreams: MAX_CONNECTIONS
105-
}
106-
107103
class CircuitRelayServer extends EventEmitter<RelayServerEvents> implements Startable, CircuitRelayService {
108104
private readonly registrar: Registrar
109105
private readonly peerStore: PeerStore
@@ -126,18 +122,32 @@ class CircuitRelayServer extends EventEmitter<RelayServerEvents> implements Star
126122
constructor (components: CircuitRelayServerComponents, init: CircuitRelayServerInit = {}) {
127123
super()
128124

125+
const validatedConfig = object({
126+
hopTimeout: number().min(0).integer().default(DEFAULT_HOP_TIMEOUT),
127+
reservations: object({
128+
maxReservations: number().integer().min(0).default(DEFAULT_MAX_RESERVATION_STORE_SIZE),
129+
reservationClearInterval: number().integer().min(0).default(DEFAULT_MAX_RESERVATION_CLEAR_INTERVAL),
130+
applyDefaultLimit: boolean().default(true),
131+
reservationTtl: number().integer().min(0).default(DEFAULT_MAX_RESERVATION_TTL),
132+
defaultDurationLimit: number().integer().min(0).default(DEFAULT_DURATION_LIMIT).max(init?.reservations?.reservationTtl ?? DEFAULT_MAX_RESERVATION_TTL, `default duration limit must be less than reservation TTL: ${init?.reservations?.reservationTtl}`)
133+
}),
134+
maxInboundHopStreams: number().integer().min(0).default(DEFAULT_MAX_INBOUND_STREAMS),
135+
maxOutboundHopStreams: number().integer().min(0).default(DEFAULT_MAX_OUTBOUND_STREAMS),
136+
maxOutboundStopStreams: number().integer().min(0).default(MAX_CONNECTIONS)
137+
}).validateSync(init)
138+
129139
this.registrar = components.registrar
130140
this.peerStore = components.peerStore
131141
this.addressManager = components.addressManager
132142
this.peerId = components.peerId
133143
this.connectionManager = components.connectionManager
134144
this.connectionGater = components.connectionGater
135145
this.started = false
136-
this.hopTimeout = init?.hopTimeout ?? DEFAULT_HOP_TIMEOUT
146+
this.hopTimeout = validatedConfig.hopTimeout
137147
this.shutdownController = new AbortController()
138-
this.maxInboundHopStreams = init.maxInboundHopStreams
139-
this.maxOutboundHopStreams = init.maxOutboundHopStreams
140-
this.maxOutboundStopStreams = init.maxOutboundStopStreams ?? defaults.maxOutboundStopStreams
148+
this.maxInboundHopStreams = validatedConfig.maxInboundHopStreams
149+
this.maxOutboundHopStreams = validatedConfig.maxOutboundHopStreams
150+
this.maxOutboundStopStreams = validatedConfig.maxOutboundStopStreams
141151

142152
try {
143153
// fails on node < 15.4
@@ -446,20 +456,7 @@ class CircuitRelayServer extends EventEmitter<RelayServerEvents> implements Star
446456
}
447457

448458
export function circuitRelayServer (init: CircuitRelayServerInit = {}): (components: CircuitRelayServerComponents) => CircuitRelayService {
449-
const validatedConfig = object({
450-
hopTimeout: number().min(0).integer().default(DEFAULT_HOP_TIMEOUT),
451-
reservations: object({
452-
maxReservations: number().integer().min(0).default(DEFAULT_MAX_RESERVATION_STORE_SIZE),
453-
reservationClearInterval: number().integer().min(0).default(DEFAULT_MAX_RESERVATION_CLEAR_INTERVAL),
454-
applyDefaultLimit: boolean().default(true),
455-
reservationTtl: number().integer().min(0).default(DEFAULT_MAX_RESERVATION_TTL),
456-
defaultDurationLimit: number().integer().min(0).default(DEFAULT_DURATION_LIMIT).max(init?.reservations?.reservationTtl ?? DEFAULT_MAX_RESERVATION_TTL, `default duration limit must be less than reservation TTL: ${init?.reservations?.reservationTtl}`)
457-
}),
458-
maxInboundHopStreams: number().integer().min(0).default(DEFAULT_MAX_INBOUND_STREAMS),
459-
maxOutboundHopStreams: number().integer().min(0).default(DEFAULT_MAX_OUTBOUND_STREAMS)
460-
}).validateSync(init)
461-
462459
return (components) => {
463-
return new CircuitRelayServer(components, validatedConfig)
460+
return new CircuitRelayServer(components, init)
464461
}
465462
}

packages/libp2p/src/circuit-relay/server/reservation-store.ts

+16-6
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { PeerMap } from '@libp2p/peer-collections'
2+
import { object, mixed, number, boolean } from 'yup'
23
import { DEFAULT_DATA_LIMIT, DEFAULT_DURATION_LIMIT, DEFAULT_MAX_RESERVATION_CLEAR_INTERVAL, DEFAULT_MAX_RESERVATION_STORE_SIZE, DEFAULT_MAX_RESERVATION_TTL } from '../constants.js'
34
import { type Limit, Status } from '../pb/index.js'
45
import type { RelayReservation } from '../index.js'
@@ -50,12 +51,21 @@ export class ReservationStore implements Startable {
5051
private readonly defaultDataLimit: bigint
5152

5253
constructor (options: ReservationStoreOptions = {}) {
53-
this.maxReservations = options.maxReservations ?? DEFAULT_MAX_RESERVATION_STORE_SIZE
54-
this.reservationClearInterval = options.reservationClearInterval ?? DEFAULT_MAX_RESERVATION_CLEAR_INTERVAL
55-
this.applyDefaultLimit = options.applyDefaultLimit !== false
56-
this.reservationTtl = options.reservationTtl ?? DEFAULT_MAX_RESERVATION_TTL
57-
this.defaultDurationLimit = options.defaultDurationLimit ?? DEFAULT_DURATION_LIMIT
58-
this.defaultDataLimit = options.defaultDataLimit ?? DEFAULT_DATA_LIMIT
54+
const validatedConfig = object({
55+
maxReservations: number().min(0).integer().default(DEFAULT_MAX_RESERVATION_STORE_SIZE),
56+
reservationClearInterval: number().integer().min(0).default(DEFAULT_MAX_RESERVATION_CLEAR_INTERVAL),
57+
applyDefaultLimit: boolean().default(true),
58+
reservationTtl: number().integer().min(0).default(DEFAULT_MAX_RESERVATION_TTL),
59+
defaultDurationLimit: number().integer().min(0).default(DEFAULT_DURATION_LIMIT),
60+
defaultDataLimit: mixed().test('is-bigint', 'Invalid bigint', value => typeof value === 'bigint').default(DEFAULT_DATA_LIMIT)
61+
}).validateSync(options)
62+
63+
this.maxReservations = validatedConfig.maxReservations
64+
this.reservationClearInterval = validatedConfig.reservationClearInterval
65+
this.applyDefaultLimit = validatedConfig.applyDefaultLimit
66+
this.reservationTtl = validatedConfig.reservationTtl
67+
this.defaultDurationLimit = validatedConfig.defaultDurationLimit
68+
this.defaultDataLimit = validatedConfig.defaultDataLimit as bigint
5969
}
6070

6171
isStarted (): boolean {

packages/libp2p/src/circuit-relay/transport/index.ts

+13-13
Original file line numberDiff line numberDiff line change
@@ -117,18 +117,25 @@ class CircuitRelayTransport implements Transport {
117117
private started: boolean
118118

119119
constructor (components: CircuitRelayTransportComponents, init: CircuitRelayTransportInit) {
120+
const validatedConfig = object({
121+
discoverRelays: number().min(0).integer().default(0),
122+
maxInboundStopStreams: number().min(0).integer().default(MAX_CONNECTIONS),
123+
maxOutboundStopStreams: number().min(0).integer().default(MAX_CONNECTIONS),
124+
stopTimeout: number().min(0).integer().default(DEFAULT_STOP_TIMEOUT)
125+
}).validateSync(init)
126+
120127
this.registrar = components.registrar
121128
this.peerStore = components.peerStore
122129
this.connectionManager = components.connectionManager
123130
this.peerId = components.peerId
124131
this.upgrader = components.upgrader
125132
this.addressManager = components.addressManager
126133
this.connectionGater = components.connectionGater
127-
this.maxInboundStopStreams = init.maxInboundStopStreams
128-
this.maxOutboundStopStreams = init.maxOutboundStopStreams
129-
this.stopTimeout = init.stopTimeout
134+
this.maxInboundStopStreams = validatedConfig.maxInboundStopStreams
135+
this.maxOutboundStopStreams = validatedConfig.maxOutboundStopStreams
136+
this.stopTimeout = validatedConfig.stopTimeout
130137

131-
if (init.discoverRelays != null && init.discoverRelays > 0) {
138+
if (validatedConfig.discoverRelays > 0) {
132139
this.discovery = new RelayDiscovery(components)
133140
this.discovery.addEventListener('relay:discover', (evt) => {
134141
this.reservationStore.addRelay(evt.detail, 'discovered')
@@ -384,15 +391,8 @@ class CircuitRelayTransport implements Transport {
384391
}
385392
}
386393

387-
export function circuitRelayTransport (init?: CircuitRelayTransportInit): (components: CircuitRelayTransportComponents) => Transport {
388-
const validatedConfig = object({
389-
discoverRelays: number().min(0).integer().default(0),
390-
maxInboundStopStreams: number().min(0).integer().default(MAX_CONNECTIONS),
391-
maxOutboundStopStreams: number().min(0).integer().default(MAX_CONNECTIONS),
392-
stopTimeout: number().min(0).integer().default(DEFAULT_STOP_TIMEOUT)
393-
}).validateSync(init)
394-
394+
export function circuitRelayTransport (init: CircuitRelayTransportInit = {}): (components: CircuitRelayTransportComponents) => Transport {
395395
return (components) => {
396-
return new CircuitRelayTransport(components, validatedConfig)
396+
return new CircuitRelayTransport(components, init)
397397
}
398398
}

packages/libp2p/src/fetch/index.ts

+20-17
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,6 @@ import type { IncomingStreamData, Registrar } from '@libp2p/interface-internal/r
2020

2121
const log = logger('libp2p:fetch')
2222

23-
const DEFAULT_TIMEOUT = 10000
24-
2523
export interface FetchServiceInit {
2624
protocolPrefix?: string
2725
maxInboundStreams?: number
@@ -96,15 +94,27 @@ class DefaultFetchService implements Startable, FetchService {
9694
private readonly components: FetchServiceComponents
9795
private readonly lookupFunctions: Map<string, LookupFunction>
9896
private started: boolean
99-
private readonly init: FetchServiceInit
97+
private readonly timeout: number
98+
private readonly maxInboundStreams: number
99+
private readonly maxOutboundStreams: number
100100

101101
constructor (components: FetchServiceComponents, init: FetchServiceInit) {
102+
const validatedConfig = object({
103+
protocolPrefix: string().default('libp2p'),
104+
timeout: number().integer().default(TIMEOUT),
105+
maxInboundStreams: number().integer().min(0).default(MAX_INBOUND_STREAMS),
106+
maxOutboundStreams: number().integer().min(0).default(MAX_OUTBOUND_STREAMS)
107+
}).validateSync(init)
108+
102109
this.started = false
103110
this.components = components
104-
this.protocol = `/${init.protocolPrefix}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`
111+
this.protocol = `/${validatedConfig.protocolPrefix}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`
112+
this.timeout = validatedConfig.timeout
113+
this.maxInboundStreams = validatedConfig.maxInboundStreams
114+
this.maxOutboundStreams = validatedConfig.maxOutboundStreams
115+
105116
this.lookupFunctions = new Map() // Maps key prefix to value lookup function
106117
this.handleMessage = this.handleMessage.bind(this)
107-
this.init = init
108118
}
109119

110120
async start (): Promise<void> {
@@ -117,8 +127,8 @@ class DefaultFetchService implements Startable, FetchService {
117127
log.error(err)
118128
})
119129
}, {
120-
maxInboundStreams: this.init.maxInboundStreams,
121-
maxOutboundStreams: this.init.maxOutboundStreams
130+
maxInboundStreams: this.maxInboundStreams,
131+
maxOutboundStreams: this.maxOutboundStreams
122132
})
123133
this.started = true
124134
}
@@ -144,8 +154,8 @@ class DefaultFetchService implements Startable, FetchService {
144154

145155
// create a timeout if no abort signal passed
146156
if (signal == null) {
147-
log('using default timeout of %d ms', this.init.timeout)
148-
signal = AbortSignal.timeout(this.init.timeout ?? DEFAULT_TIMEOUT)
157+
log('using default timeout of %d ms', this.timeout)
158+
signal = AbortSignal.timeout(this.timeout)
149159

150160
try {
151161
// fails on node < 15.4
@@ -310,12 +320,5 @@ class DefaultFetchService implements Startable, FetchService {
310320
}
311321

312322
export function fetchService (init: FetchServiceInit = {}): (components: FetchServiceComponents) => FetchService {
313-
const validatedConfig = object({
314-
protocolPrefix: string().default('libp2p'),
315-
timeout: number().integer().default(TIMEOUT),
316-
maxInboundStreams: number().integer().min(0).default(MAX_INBOUND_STREAMS),
317-
maxOutboundStreams: number().integer().min(0).default(MAX_OUTBOUND_STREAMS)
318-
}).validateSync(init)
319-
320-
return (components) => new DefaultFetchService(components, validatedConfig)
323+
return (components) => new DefaultFetchService(components, init)
321324
}

packages/libp2p/src/identify/identify.ts

+35-15
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { pbStream } from 'it-protobuf-stream'
88
import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
99
import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
1010
import { isNode, isBrowser, isWebWorker, isElectronMain, isElectronRenderer, isReactNative } from 'wherearewe'
11+
import { boolean, number, object, string } from 'yup'
1112
import { codes } from '../errors.js'
1213
import {
1314
AGENT_VERSION,
@@ -18,9 +19,12 @@ import {
1819
MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION,
1920
MAX_INBOUND_STREAMS,
2021
MAX_OUTBOUND_STREAMS,
21-
MAX_PUSH_INCOMING_STREAMS,
2222
MAX_IDENTIFY_MESSAGE_SIZE,
2323
TIMEOUT,
24+
RUN_ON_CONNECTION_OPEN,
25+
PROTOCOL_PREFIX,
26+
RUN_ON_TRANSIENT_CONNECTION,
27+
MAX_PUSH_INCOMING_STREAMS,
2428
MAX_PUSH_OUTGOING_STREAMS,
2529
MAX_OBSERVED_ADDRESSES
2630
} from './consts.js'
@@ -60,9 +64,24 @@ export class DefaultIdentifyService implements Startable, IdentifyService {
6064
private readonly maxIdentifyMessageSize: number
6165
private readonly maxObservedAddresses: number
6266
private readonly events: EventEmitter<Libp2pEvents>
63-
private readonly runOnTransientConnection?: boolean
67+
private readonly runOnTransientConnection: boolean
68+
private readonly runOnConnectionOpen: boolean
6469

6570
constructor (components: IdentifyServiceComponents, init: IdentifyServiceInit) {
71+
const validatedConfig = object({
72+
protocolPrefix: string().default(PROTOCOL_PREFIX),
73+
agentVersion: string().default(AGENT_VERSION),
74+
timeout: number().integer().default(TIMEOUT),
75+
maxIdentifyMessageSize: number().integer().min(0).default(MAX_IDENTIFY_MESSAGE_SIZE),
76+
maxInboundStreams: number().integer().min(0).default(MAX_INBOUND_STREAMS),
77+
maxPushIncomingStreams: number().integer().min(0).default(MAX_PUSH_INCOMING_STREAMS),
78+
maxPushOutgoingStreams: number().integer().min(0).default(MAX_PUSH_OUTGOING_STREAMS),
79+
maxOutboundStreams: number().integer().min(0).default(MAX_OUTBOUND_STREAMS),
80+
maxObservedAddresses: number().integer().min(0).default(MAX_OBSERVED_ADDRESSES),
81+
runOnConnectionOpen: boolean().default(RUN_ON_CONNECTION_OPEN),
82+
runOnTransientConnection: boolean().default(RUN_ON_TRANSIENT_CONNECTION)
83+
}).validateSync(init)
84+
6685
this.started = false
6786
this.peerId = components.peerId
6887
this.peerStore = components.peerStore
@@ -71,24 +90,25 @@ export class DefaultIdentifyService implements Startable, IdentifyService {
7190
this.connectionManager = components.connectionManager
7291
this.events = components.events
7392

74-
this.identifyProtocolStr = `/${init.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`
75-
this.identifyPushProtocolStr = `/${init.protocolPrefix}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION}`
76-
this.timeout = init.timeout ?? TIMEOUT
77-
this.maxInboundStreams = init.maxInboundStreams ?? MAX_INBOUND_STREAMS
78-
this.maxOutboundStreams = init.maxOutboundStreams ?? MAX_OUTBOUND_STREAMS
79-
this.maxPushIncomingStreams = init.maxPushIncomingStreams ?? MAX_PUSH_INCOMING_STREAMS
80-
this.maxPushOutgoingStreams = init.maxPushOutgoingStreams ?? MAX_PUSH_OUTGOING_STREAMS
81-
this.maxIdentifyMessageSize = init.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE
82-
this.maxObservedAddresses = init.maxObservedAddresses ?? MAX_OBSERVED_ADDRESSES
83-
this.runOnTransientConnection = init.runOnTransientConnection
93+
this.identifyProtocolStr = `/${validatedConfig.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`
94+
this.identifyPushProtocolStr = `/${validatedConfig.protocolPrefix}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION}`
95+
this.timeout = validatedConfig.timeout
96+
this.maxInboundStreams = validatedConfig.maxInboundStreams
97+
this.maxOutboundStreams = validatedConfig.maxOutboundStreams
98+
this.maxPushIncomingStreams = validatedConfig.maxPushIncomingStreams
99+
this.maxPushOutgoingStreams = validatedConfig.maxPushOutgoingStreams
100+
this.maxIdentifyMessageSize = validatedConfig.maxIdentifyMessageSize
101+
this.maxObservedAddresses = validatedConfig.maxObservedAddresses
102+
this.runOnTransientConnection = validatedConfig.runOnTransientConnection
103+
this.runOnConnectionOpen = validatedConfig.runOnConnectionOpen
84104

85105
// Store self host metadata
86106
this.host = {
87-
protocolVersion: `${init.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,
88-
agentVersion: init.agentVersion ?? AGENT_VERSION
107+
protocolVersion: `${validatedConfig.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,
108+
agentVersion: validatedConfig.agentVersion
89109
}
90110

91-
if (init.runOnConnectionOpen === true) {
111+
if (this.runOnConnectionOpen) {
92112
// When a new connection happens, trigger identify
93113
components.events.addEventListener('connection:open', (evt) => {
94114
const connection = evt.detail

0 commit comments

Comments
 (0)