Skip to content

Commit

Permalink
chore: lint the circuit relay files (libp2p#1566)
Browse files Browse the repository at this point in the history
  • Loading branch information
maschad committed Mar 3, 2023
1 parent fc14934 commit bb9772c
Show file tree
Hide file tree
Showing 10 changed files with 47 additions and 47 deletions.
28 changes: 14 additions & 14 deletions src/circuit/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { PeerSet, PeerMap, PeerList } from '@libp2p/peer-collections'

const log = logger('libp2p:circuit:client')

const noop = () => {}
const noop = (): void => {}

/**
* CircuitServiceInit initializes the circuit service using values
Expand Down Expand Up @@ -81,17 +81,17 @@ export class RelayReservationManager extends EventEmitter<RelayReservationManage
this.components.connectionManager.addEventListener('peer:connect', this._onPeerConnect)
}

isStarted () {
isStarted (): boolean {
return this.started
}

start () {
start (): void {
void this._listenOnAvailableHopRelays().catch(err => { log.error('error listening on relays', err) })
this.started = true
}

async stop () {
this.reservationMap.forEach((timer) => clearTimeout(timer))
async stop (): Promise<void> {
this.reservationMap.forEach((timer) => { clearTimeout(timer) })
this.reservationMap.clear()
this.relays.clear()
}
Expand All @@ -102,7 +102,7 @@ export class RelayReservationManager extends EventEmitter<RelayReservationManage
* If the protocol is supported, check if the peer supports **HOP** and add it as a listener if
* inside the threshold.
*/
async _onProtocolChange ({ peerId, protocols }: {peerId: PeerId, protocols: string[]}) {
async _onProtocolChange ({ peerId, protocols }: { peerId: PeerId, protocols: string[] }): Promise<void> {
if (peerId.equals(this.components.peerId)) {
return
}
Expand Down Expand Up @@ -151,11 +151,11 @@ export class RelayReservationManager extends EventEmitter<RelayReservationManage
* Handle case when peer connects. If we already have the peer in the protobook,
* we treat this event as an `onProtocolChange`.
*/
_onPeerConnect ({ detail: connection }: CustomEvent<Connection>) {
_onPeerConnect ({ detail: connection }: CustomEvent<Connection>): void {
void this.components.peerStore.protoBook.get(connection.remotePeer)
.then((protocols) => {
void this._onProtocolChange({ peerId: connection.remotePeer, protocols })
.catch((err) => log.error('handling reconnect failed', err))
.catch((err) => { log.error('handling reconnect failed', err) })
},
(err) => {
// this is not necessarily an error as we will only have the protocols stored
Expand All @@ -167,7 +167,7 @@ export class RelayReservationManager extends EventEmitter<RelayReservationManage
/**
* Peer disconnects
*/
_onPeerDisconnected (evt: CustomEvent<Connection>) {
_onPeerDisconnected (evt: CustomEvent<Connection>): void {
const connection = evt.detail
const peerId = connection.remotePeer
clearTimeout(this.reservationMap.get(peerId))
Expand Down Expand Up @@ -238,11 +238,11 @@ export class RelayReservationManager extends EventEmitter<RelayReservationManage
/**
* Remove listen relay
*/
async _removeListenRelay (PeerId: PeerId) {
async _removeListenRelay (PeerId: PeerId): Promise<void> {
const recheck = this.relays.has(PeerId)
this.relays.delete(PeerId)
if (recheck) {
// TODO: this should be responsibility of the connMgr
// TODO: this should be responsibility of the connMgr https://github.com/libp2p/js-libp2p/issues/1610
await this._listenOnAvailableHopRelays(new PeerList([PeerId]))
}
}
Expand All @@ -254,7 +254,7 @@ export class RelayReservationManager extends EventEmitter<RelayReservationManage
* 2. Dial and try to listen on the peers we know that support hop but are not connected.
* 3. Search the network.
*/
async _listenOnAvailableHopRelays (peersToIgnore: PeerList = new PeerList([])) {
async _listenOnAvailableHopRelays (peersToIgnore: PeerList = new PeerList([])): Promise<void> {
// Check if already listening on enough relays
if (this.relays.size >= this.maxReservations) {
return
Expand Down Expand Up @@ -321,7 +321,7 @@ export class RelayReservationManager extends EventEmitter<RelayReservationManage
}
}

async _tryToListenOnRelay (peerId: PeerId) {
async _tryToListenOnRelay (peerId: PeerId): Promise<void> {
try {
if (peerId.equals(this.components.peerId)) {
log.trace('Skipping dialling self %p', peerId.toString())
Expand All @@ -335,7 +335,7 @@ export class RelayReservationManager extends EventEmitter<RelayReservationManage
}
}

private readonly createOrRefreshReservation = async (peerId: PeerId) => {
private readonly createOrRefreshReservation = async (peerId: PeerId): Promise<void> => {
try {
const connections = this.components.connectionManager.getConnections(peerId)

Expand Down
14 changes: 7 additions & 7 deletions src/circuit/hop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ async function handleReserve ({ connection, stream: pbstr, relayPeer, relayAddrs
return
}

const result = await reservationStore.reserve(connection.remotePeer, connection.remoteAddr)
const result = reservationStore.reserve(connection.remotePeer, connection.remoteAddr)

if (result.status !== Status.OK) {
hopstr.write({ type: HopMessage.Type.STATUS, status: result.status })
Expand All @@ -105,12 +105,12 @@ async function handleReserve ({ connection, stream: pbstr, relayPeer, relayAddrs
type: HopMessage.Type.STATUS,
status: Status.OK,
reservation: await makeReservation(relayAddrs, relayPeer, connection.remotePeer, BigInt(result.expire ?? 0)),
limit: (await reservationStore.get(relayPeer))?.limit
limit: reservationStore.get(relayPeer)?.limit
})
log('sent confirmation response to %s', connection.remotePeer)
} catch (err) {
log.error('failed to send confirmation response to %s', connection.remotePeer)
await reservationStore.removeReservation(connection.remotePeer)
reservationStore.removeReservation(connection.remotePeer)
}
}

Expand Down Expand Up @@ -138,12 +138,12 @@ async function handleConnect (options: HopProtocolOptions): Promise<void> {
const status = await acl.allowConnect(connection.remotePeer, connection.remoteAddr, dstPeer)
if (status !== Status.OK) {
log.error('hop connect denied for %s with status %s', connection.remotePeer, status)
hopstr.write({ type: HopMessage.Type.STATUS, status: status })
hopstr.write({ type: HopMessage.Type.STATUS, status })
return
}
}

if (!await reservationStore.hasReservation(dstPeer)) {
if (!reservationStore.hasReservation(dstPeer)) {
log.error('hop connect denied for %s with status %s', connection.remotePeer, Status.NO_RESERVATION)
hopstr.write({ type: HopMessage.Type.STATUS, status: Status.NO_RESERVATION })
return
Expand Down Expand Up @@ -179,9 +179,9 @@ async function handleConnect (options: HopProtocolOptions): Promise<void> {
const sourceStream = stream.unwrap()

log('connection to destination established, short circuiting streams...')
const limit = (await reservationStore.get(dstPeer))?.limit
const limit = reservationStore.get(dstPeer)?.limit
// Short circuit the two streams to create the relayed connection
return createLimitedRelay(sourceStream, destinationStream, limit)
createLimitedRelay(sourceStream, destinationStream, limit)
}

async function makeReservation (
Expand Down
2 changes: 1 addition & 1 deletion src/circuit/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export interface Reservation {
}

export interface ReservationStore {
reserve: (peer: PeerId, addr: Multiaddr, limit?: Limit) => {status: ReservationStatus, expire?: number}
reserve: (peer: PeerId, addr: Multiaddr, limit?: Limit) => { status: ReservationStatus, expire?: number }
removeReservation: (peer: PeerId) => void
hasReservation: (dst: PeerId) => boolean
get: (peer: PeerId) => Reservation | undefined
Expand Down
4 changes: 2 additions & 2 deletions src/circuit/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export function createListener (options: ListenerOptions): Listener {
*
* @returns {Multiaddr[]}
*/
function getAddrs () {
function getAddrs (): Multiaddr[] {
const addrs = []
for (const addr of listeningAddrs.values()) {
addrs.push(addr)
Expand All @@ -63,7 +63,7 @@ export function createListener (options: ListenerOptions): Listener {
}

const listener: Listener = Object.assign(new EventEmitter(), {
close: async () => await Promise.resolve(),
close: async () => { await Promise.resolve() },
listen,
getAddrs
})
Expand Down
8 changes: 4 additions & 4 deletions src/circuit/relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ export class Relay implements Startable {
this._advertiseService = this._advertiseService.bind(this)
}

isStarted () {
isStarted (): boolean {
return this.started
}

/**
* Start Relay service
*/
async start () {
async start (): Promise<void> {
// Advertise service if HOP enabled and advertising enabled
if (this.init.hop.enabled === true && this.init.advertise.enabled === true) {
this.timeout = setDelayedInterval(
Expand All @@ -60,7 +60,7 @@ export class Relay implements Startable {
/**
* Stop Relay service
*/
async stop () {
async stop (): Promise<void> {
try {
clearDelayedInterval(this.timeout)
} catch (err) { }
Expand All @@ -71,7 +71,7 @@ export class Relay implements Startable {
/**
* Advertise hop relay service in the network.
*/
async _advertiseService () {
async _advertiseService (): Promise<void> {
try {
const cid = await namespaceToCid(RELAY_RENDEZVOUS_NS)
await this.components.contentRouting.provide(cid)
Expand Down
8 changes: 4 additions & 4 deletions src/circuit/reservation-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export type ReservationStoreOptions = RecursivePartial<ReservationStoreInit>

export class ReservationStore implements IReservationStore, Startable {
private readonly reservations = new PeerMap<Reservation>()
private _started = false;
private _started = false
private interval: any
private readonly init: ReservationStoreInit

Expand All @@ -53,11 +53,11 @@ export class ReservationStore implements IReservationStore, Startable {
}
}

isStarted () {
isStarted (): boolean {
return this._started
}

start () {
start (): void {
if (this._started) {
return
}
Expand All @@ -75,7 +75,7 @@ export class ReservationStore implements IReservationStore, Startable {
)
}

stop () {
stop (): void {
clearInterval(this.interval)
}

Expand Down
4 changes: 2 additions & 2 deletions src/circuit/reservation-voucher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ export class ReservationVoucherRecord implements Record {
this.expiration = expiration
}

marshal () {
marshal (): Uint8Array {
return ReservationVoucher.encode({
relay: this.relay.toBytes(),
peer: this.peer.toBytes(),
expiration: BigInt(this.expiration)
})
}

equals (other: Record) {
equals (other: Record): boolean {
if (!(other instanceof ReservationVoucherRecord)) {
return false
}
Expand Down
4 changes: 2 additions & 2 deletions src/circuit/stop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export async function handleStop ({
connection,
request,
pbstr
}: HandleStopOptions) {
}: HandleStopOptions): Promise<Stream | undefined> {
const stopstr = pbstr.pb(StopMessage)
log('new circuit relay v2 stop stream from %s', connection.remotePeer)
// Validate the STOP request has the required input
Expand All @@ -45,7 +45,7 @@ export async function handleStop ({
return
}

// TODO: go-libp2p marks connection transient if there is limit field present in request.
// TODO: go-libp2p marks connection transient if there is limit field present in request. Depends on https://github.com/libp2p/js-libp2p/issues/1611
// Cannot find any reference to transient connections in js-libp2p

stopstr.write({ type: StopMessage.Type.STATUS, status: Status.OK })
Expand Down
14 changes: 7 additions & 7 deletions src/circuit/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export class Circuit implements Transport, Startable {
this._started = false
}

isStarted () {
isStarted (): boolean {
return this._started
}

Expand Down Expand Up @@ -102,11 +102,11 @@ export class Circuit implements Transport, Startable {
})

if (this._init.hop.enabled === true) {
void this.reservationStore.start()
this.reservationStore.start()
}
}

async stop () {
async stop (): Promise<void> {
if (this._init.hop.enabled === true) {
this.reservationStore.stop()
await this.components.registrar.unhandle(RELAY_V2_HOP_CODEC)
Expand All @@ -118,11 +118,11 @@ export class Circuit implements Transport, Startable {
return true
}

get [Symbol.toStringTag] () {
get [Symbol.toStringTag] (): 'libp2p/circuit-relay-v2' {
return 'libp2p/circuit-relay-v2'
}

async onHop ({ connection, stream }: IncomingStreamData) {
async onHop ({ connection, stream }: IncomingStreamData): Promise<void> {
log('received circuit v2 hop protocol stream from %s', connection.remotePeer)

const hopTimeoutPromise = pDefer()
Expand Down Expand Up @@ -165,7 +165,7 @@ export class Circuit implements Transport, Startable {
}
}

async onStop ({ connection, stream }: IncomingStreamData) {
async onStop ({ connection, stream }: IncomingStreamData): Promise<void> {
const pbstr = pbStream(stream)
const request = await pbstr.readPB(CircuitV2.StopMessage)
log('received circuit v2 stop protocol request from %s', connection.remotePeer)
Expand Down Expand Up @@ -248,7 +248,7 @@ export class Circuit implements Transport, Startable {
destinationAddr, relayAddr, ma,
disconnectOnFailure
}: ConnectOptions
) {
): Promise<Connection> {
try {
const pbstr = pbStream(stream)
const hopstr = pbstr.pb(CircuitV2.HopMessage)
Expand Down
8 changes: 4 additions & 4 deletions src/circuit/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,17 @@ import type { Stream } from '@libp2p/interface-connection'

const log = logger('libp2p:circuit:v2:util')

const doRelay = (src: Stream, dst: Stream) => {
const doRelay = (src: Stream, dst: Stream): void => {
queueMicrotask(() => {
void dst.sink(src.source).catch(err => log.error('error while relating streams:', err))
void dst.sink(src.source).catch(err => { log.error('error while relating streams:', err) })
})

queueMicrotask(() => {
void src.sink(dst.source).catch(err => log.error('error while relaying streams:', err))
void src.sink(dst.source).catch(err => { log.error('error while relaying streams:', err) })
})
}

export function createLimitedRelay (source: Stream, destination: Stream, limit?: Limit) {
export function createLimitedRelay (source: Stream, destination: Stream, limit?: Limit): void {
// trivial case
if (limit == null) {
doRelay(source, destination)
Expand Down

0 comments on commit bb9772c

Please sign in to comment.