Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: replace err-code with CodeError #1532

Merged
merged 5 commits into from
Mar 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@
"@libp2p/interface-registrar": "^2.0.3",
"@libp2p/interface-stream-muxer": "^3.0.0",
"@libp2p/interface-transport": "^2.1.0",
"@libp2p/interfaces": "^3.0.3",
"@libp2p/interfaces": "^3.2.0",
"@libp2p/keychain": "^2.0.0",
"@libp2p/logger": "^2.0.1",
"@libp2p/multistream-select": "^3.0.0",
Expand All @@ -138,7 +138,6 @@
"abortable-iterator": "^4.0.2",
"any-signal": "^3.0.0",
"datastore-core": "^9.0.0",
"err-code": "^3.0.1",
"interface-datastore": "^8.0.0",
"it-all": "^2.0.0",
"it-drain": "^2.0.0",
Expand Down
8 changes: 4 additions & 4 deletions src/circuit/transport/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { StopMessage, HopMessage, Status } from '../pb/index.js'
import { logger } from '@libp2p/logger'
import createError from 'err-code'
import * as mafmt from '@multiformats/mafmt'
import { multiaddr } from '@multiformats/multiaddr'
import { codes } from '../../errors.js'
Expand All @@ -23,6 +22,7 @@ import type { ContentRouting } from '@libp2p/interface-content-routing'
import { CIRCUIT_PROTO_CODE, RELAY_V2_HOP_CODEC, RELAY_V2_STOP_CODEC } from '../constants.js'
import { RelayStoreInit, ReservationStore } from './reservation-store.js'
import { RelayDiscovery, RelayDiscoveryComponents } from './discovery.js'
import { CodeError } from '@libp2p/interfaces/errors'

const log = logger('libp2p:circuit-relay:transport')

Expand Down Expand Up @@ -154,7 +154,7 @@ class CircuitRelayTransport implements Transport {
if (ma.protoCodes().filter(code => code === CIRCUIT_PROTO_CODE).length !== 1) {
const errMsg = 'Invalid circuit relay address'
log.error(errMsg, ma)
throw createError(new Error(errMsg), codes.ERR_RELAYED_DIAL)
throw new CodeError(errMsg, codes.ERR_RELAYED_DIAL)
}

// Check the multiaddr to see if it contains a relay and a destination peer
Expand All @@ -167,7 +167,7 @@ class CircuitRelayTransport implements Transport {
if (relayId == null || destinationId == null) {
const errMsg = 'Circuit relay dial failed as addresses did not have peer id'
log.error(errMsg)
throw createError(new Error(errMsg), codes.ERR_RELAYED_DIAL)
throw new CodeError(errMsg, codes.ERR_RELAYED_DIAL)
}

const relayPeer = peerIdFromString(relayId)
Expand Down Expand Up @@ -223,7 +223,7 @@ class CircuitRelayTransport implements Transport {
const status = await hopstr.read()

if (status.status !== Status.OK) {
throw createError(new Error(`failed to connect via relay with status ${status?.status?.toString() ?? 'undefined'}`), codes.ERR_HOP_REQUEST_FAILED)
throw new CodeError(`failed to connect via relay with status ${status?.status?.toString() ?? 'undefined'}`, codes.ERR_HOP_REQUEST_FAILED)
}

// TODO: do something with limit and transient connection
Expand Down
26 changes: 13 additions & 13 deletions src/components.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import errCode from 'err-code'
import { CodeError } from '@libp2p/interfaces/errors'
import type { ConnectionProtector } from '@libp2p/interface-connection'
import type { ContentRouting } from '@libp2p/interface-content-routing'
import type { AddressManager } from '@libp2p/interface-address-manager'
Expand Down Expand Up @@ -157,7 +157,7 @@ export class DefaultComponents implements Components, Startable {

get peerId (): PeerId {
if (this._peerId == null) {
throw errCode(new Error('peerId not set'), 'ERR_SERVICE_MISSING')
throw new CodeError('peerId not set', 'ERR_SERVICE_MISSING')
}

return this._peerId
Expand All @@ -169,7 +169,7 @@ export class DefaultComponents implements Components, Startable {

get addressManager (): AddressManager {
if (this._addressManager == null) {
throw errCode(new Error('addressManager not set'), 'ERR_SERVICE_MISSING')
throw new CodeError('addressManager not set', 'ERR_SERVICE_MISSING')
}

return this._addressManager
Expand All @@ -181,7 +181,7 @@ export class DefaultComponents implements Components, Startable {

get peerStore (): PeerStore {
if (this._peerStore == null) {
throw errCode(new Error('peerStore not set'), 'ERR_SERVICE_MISSING')
throw new CodeError('peerStore not set', 'ERR_SERVICE_MISSING')
}

return this._peerStore
Expand All @@ -193,7 +193,7 @@ export class DefaultComponents implements Components, Startable {

get upgrader (): Upgrader {
if (this._upgrader == null) {
throw errCode(new Error('upgrader not set'), 'ERR_SERVICE_MISSING')
throw new CodeError('upgrader not set', 'ERR_SERVICE_MISSING')
}

return this._upgrader
Expand All @@ -205,7 +205,7 @@ export class DefaultComponents implements Components, Startable {

get registrar (): Registrar {
if (this._registrar == null) {
throw errCode(new Error('registrar not set'), 'ERR_SERVICE_MISSING')
throw new CodeError('registrar not set', 'ERR_SERVICE_MISSING')
}

return this._registrar
Expand All @@ -217,7 +217,7 @@ export class DefaultComponents implements Components, Startable {

get connectionManager (): ConnectionManager {
if (this._connectionManager == null) {
throw errCode(new Error('connectionManager not set'), 'ERR_SERVICE_MISSING')
throw new CodeError('connectionManager not set', 'ERR_SERVICE_MISSING')
}

return this._connectionManager
Expand All @@ -229,7 +229,7 @@ export class DefaultComponents implements Components, Startable {

get transportManager (): TransportManager {
if (this._transportManager == null) {
throw errCode(new Error('transportManager not set'), 'ERR_SERVICE_MISSING')
throw new CodeError('transportManager not set', 'ERR_SERVICE_MISSING')
}

return this._transportManager
Expand All @@ -241,7 +241,7 @@ export class DefaultComponents implements Components, Startable {

get connectionGater (): ConnectionGater {
if (this._connectionGater == null) {
throw errCode(new Error('connectionGater not set'), 'ERR_SERVICE_MISSING')
throw new CodeError('connectionGater not set', 'ERR_SERVICE_MISSING')
}

return this._connectionGater
Expand All @@ -253,7 +253,7 @@ export class DefaultComponents implements Components, Startable {

get contentRouting (): ContentRouting {
if (this._contentRouting == null) {
throw errCode(new Error('contentRouting not set'), 'ERR_SERVICE_MISSING')
throw new CodeError('contentRouting not set', 'ERR_SERVICE_MISSING')
}

return this._contentRouting
Expand All @@ -265,7 +265,7 @@ export class DefaultComponents implements Components, Startable {

get peerRouting (): PeerRouting {
if (this._peerRouting == null) {
throw errCode(new Error('peerRouting not set'), 'ERR_SERVICE_MISSING')
throw new CodeError('peerRouting not set', 'ERR_SERVICE_MISSING')
}

return this._peerRouting
Expand All @@ -277,7 +277,7 @@ export class DefaultComponents implements Components, Startable {

get datastore (): Datastore {
if (this._datastore == null) {
throw errCode(new Error('datastore not set'), 'ERR_SERVICE_MISSING')
throw new CodeError('datastore not set', 'ERR_SERVICE_MISSING')
}

return this._datastore
Expand All @@ -297,7 +297,7 @@ export class DefaultComponents implements Components, Startable {

get dialer (): Dialer {
if (this._dialer == null) {
throw errCode(new Error('dialer not set'), 'ERR_SERVICE_MISSING')
throw new CodeError('dialer not set', 'ERR_SERVICE_MISSING')
}

return this._dialer
Expand Down
8 changes: 4 additions & 4 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { FaultTolerance } from '@libp2p/interface-transport'
import type { Multiaddr } from '@multiformats/multiaddr'
import type { Libp2pInit } from './index.js'
import { codes, messages } from './errors.js'
import errCode from 'err-code'
import { CodeError } from '@libp2p/interfaces/errors'
import type { RecursivePartial } from '@libp2p/interfaces'
import { isNode, isBrowser, isWebWorker, isElectronMain, isElectronRenderer, isReactNative } from 'wherearewe'

Expand Down Expand Up @@ -92,15 +92,15 @@ export function validateConfig (opts: RecursivePartial<Libp2pInit>): Libp2pInit
const resultingOptions: Libp2pInit = mergeOptions(DefaultConfig, opts)

if (resultingOptions.transports == null || resultingOptions.transports.length < 1) {
throw errCode(new Error(messages.ERR_TRANSPORTS_REQUIRED), codes.ERR_TRANSPORTS_REQUIRED)
throw new CodeError(messages.ERR_TRANSPORTS_REQUIRED, codes.ERR_TRANSPORTS_REQUIRED)
}

if (resultingOptions.connectionEncryption == null || resultingOptions.connectionEncryption.length === 0) {
throw errCode(new Error(messages.CONN_ENCRYPTION_REQUIRED), codes.CONN_ENCRYPTION_REQUIRED)
throw new CodeError(messages.CONN_ENCRYPTION_REQUIRED, codes.CONN_ENCRYPTION_REQUIRED)
}

if (resultingOptions.connectionProtector === null && globalThis.process?.env?.LIBP2P_FORCE_PNET != null) { // eslint-disable-line no-undef
throw errCode(new Error(messages.ERR_PROTECTOR_REQUIRED), codes.ERR_PROTECTOR_REQUIRED)
throw new CodeError(messages.ERR_PROTECTOR_REQUIRED, codes.ERR_PROTECTOR_REQUIRED)
}

// Append user agent version to default AGENT_VERSION depending on the environment
Expand Down
10 changes: 5 additions & 5 deletions src/connection-manager/dialer/dial-request.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import errCode from 'err-code'
import { CodeError } from '@libp2p/interfaces/errors'
import { anySignal } from 'any-signal'
import FIFO from 'p-fifo'
import { setMaxListeners } from 'events'
Expand Down Expand Up @@ -50,7 +50,7 @@ export class DialRequest {

// If no tokens are available, throw
if (tokens.length < 1) {
throw errCode(new Error('No dial tokens available'), codes.ERR_NO_DIAL_TOKENS)
throw new CodeError('No dial tokens available', codes.ERR_NO_DIAL_TOKENS)
}

const tokenHolder = new FIFO<number>()
Expand Down Expand Up @@ -87,12 +87,12 @@ export class DialRequest {
// End attempt once another attempt succeeded
if (done) {
this.dialer.releaseToken(tokens.splice(tokens.indexOf(token), 1)[0])
throw errCode(new Error('dialAction already succeeded'), codes.ERR_ALREADY_SUCCEEDED)
throw new CodeError('dialAction already succeeded', codes.ERR_ALREADY_SUCCEEDED)
}

const controller = dialAbortControllers[i]
if (controller == null) {
throw errCode(new Error('dialAction did not come with an AbortController'), codes.ERR_INVALID_PARAMETERS)
throw new CodeError('dialAction did not come with an AbortController', codes.ERR_INVALID_PARAMETERS)
}
let conn
try {
Expand All @@ -116,7 +116,7 @@ export class DialRequest {
// Notify Promise.any that attempt was not successful
// to prevent from returning undefined despite there
// were successful dial attempts
throw errCode(new Error('dialAction led to empty object'), codes.ERR_TRANSPORT_DIAL_FAILED)
throw new CodeError('dialAction led to empty object', codes.ERR_TRANSPORT_DIAL_FAILED)
} else {
// This dial succeeded, don't attempt anything else
done = true
Expand Down
12 changes: 6 additions & 6 deletions src/connection-manager/dialer/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { logger } from '@libp2p/logger'
import errCode from 'err-code'
import { CodeError } from '@libp2p/interfaces/errors'
import { isMultiaddr, Multiaddr, Resolver, multiaddr, resolvers } from '@multiformats/multiaddr'
import { TimeoutController } from 'timeout-abort-controller'
import { anySignal } from 'any-signal'
Expand Down Expand Up @@ -156,7 +156,7 @@ export class DefaultDialer implements Startable, Dialer {

if (peerId != null) {
if (this.components.peerId.equals(peerId)) {
throw errCode(new Error('Tried to dial self'), codes.ERR_DIALED_SELF)
throw new CodeError('Tried to dial self', codes.ERR_DIALED_SELF)
}

if (multiaddr != null) {
Expand All @@ -165,7 +165,7 @@ export class DefaultDialer implements Startable, Dialer {
}

if ((await this.components.connectionGater.denyDialPeer?.(peerId)) === true) {
throw errCode(new Error('The dial request is blocked by gater.allowDialPeer'), codes.ERR_PEER_DIAL_INTERCEPTED)
throw new CodeError('The dial request is blocked by gater.allowDialPeer', codes.ERR_PEER_DIAL_INTERCEPTED)
}
}

Expand Down Expand Up @@ -195,7 +195,7 @@ export class DefaultDialer implements Startable, Dialer {
}

if (dialTarget.addrs.length === 0) {
throw errCode(new Error('The dial request has no valid addresses'), codes.ERR_NO_VALID_ADDRESSES)
throw new CodeError('The dial request has no valid addresses', codes.ERR_NO_VALID_ADDRESSES)
}

// try to join an in-flight dial for this peer if one is available
Expand Down Expand Up @@ -267,7 +267,7 @@ export class DefaultDialer implements Startable, Dialer {
addrs = [...new Set(addrs.map(ma => ma.toString()))].map(ma => multiaddr(ma))

if (addrs.length > this.maxAddrsToDial) {
throw errCode(new Error('dial with more addresses than allowed'), codes.ERR_TOO_MANY_ADDRESSES)
throw new CodeError('dial with more addresses than allowed', codes.ERR_TOO_MANY_ADDRESSES)
}

const peerId = isPeerId(peerIdOrMultiaddr.peerId) ? peerIdOrMultiaddr.peerId : undefined
Expand Down Expand Up @@ -324,7 +324,7 @@ export class DefaultDialer implements Startable, Dialer {
*/
const dialAction: DialAction = async (addr, options = {}) => {
if (options.signal?.aborted === true) {
throw errCode(new Error('already aborted'), codes.ERR_ALREADY_ABORTED)
throw new CodeError('already aborted', codes.ERR_ALREADY_ABORTED)
}

return await this.components.transportManager.dial(addr, options).catch(err => {
Expand Down
8 changes: 4 additions & 4 deletions src/connection-manager/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { logger } from '@libp2p/logger'
import errCode from 'err-code'
import { CodeError } from '@libp2p/interfaces/errors'
import mergeOptions from 'merge-options'
import { LatencyMonitor, SummaryObject } from './latency-monitor.js'
import type { AbortOptions } from '@libp2p/interfaces'
Expand Down Expand Up @@ -163,7 +163,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
this.opts = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, init)

if (this.opts.maxConnections < this.opts.minConnections) {
throw errCode(new Error('Connection Manager maxConnections must be greater than minConnections'), codes.ERR_INVALID_PARAMETERS)
throw new CodeError('Connection Manager maxConnections must be greater than minConnections', codes.ERR_INVALID_PARAMETERS)
}

log('options: %o', this.opts)
Expand Down Expand Up @@ -473,7 +473,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
const { peerId, multiaddr } = getPeerAddress(peerIdOrMultiaddr)

if (peerId == null && multiaddr == null) {
throw errCode(new TypeError('Can only open connections to PeerIds or Multiaddrs'), codes.ERR_INVALID_PARAMETERS)
throw new CodeError('Can only open connections to PeerIds or Multiaddrs', codes.ERR_INVALID_PARAMETERS)
}

if (peerId != null) {
Expand Down Expand Up @@ -547,7 +547,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
*/
getAll (peerId: PeerId): Connection[] {
if (!isPeerId(peerId)) {
throw errCode(new Error('peerId must be an instance of peer-id'), codes.ERR_INVALID_PARAMETERS)
throw new CodeError('peerId must be an instance of peer-id', codes.ERR_INVALID_PARAMETERS)
}

const id = peerId.toString()
Expand Down
6 changes: 3 additions & 3 deletions src/connection/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Multiaddr } from '@multiformats/multiaddr'
import errCode from 'err-code'
import { CodeError } from '@libp2p/interfaces/errors'
import { OPEN, CLOSING, CLOSED } from '@libp2p/interface-connection/status'
import { symbol } from '@libp2p/interface-connection'
import type { Connection, ConnectionStat, Stream } from '@libp2p/interface-connection'
Expand Down Expand Up @@ -107,11 +107,11 @@ export class ConnectionImpl implements Connection {
*/
async newStream (protocols: string | string[], options?: AbortOptions): Promise<Stream> {
if (this.stat.status === CLOSING) {
throw errCode(new Error('the connection is being closed'), 'ERR_CONNECTION_BEING_CLOSED')
throw new CodeError('the connection is being closed', 'ERR_CONNECTION_BEING_CLOSED')
}

if (this.stat.status === CLOSED) {
throw errCode(new Error('the connection is closed'), 'ERR_CONNECTION_CLOSED')
throw new CodeError('the connection is closed', 'ERR_CONNECTION_CLOSED')
}

if (!Array.isArray(protocols)) {
Expand Down
Loading