All files / src/p2p client.ts

66.66% Statements 40/60
55.55% Branches 10/18
54.54% Functions 12/22
66.66% Lines 40/60

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200                                                            1x                             37x 37x         37x 1x   36x     37x 1x 1x     37x 18x     37x       37x       37x       19x 19x 19x                           18x 18x 18x             1x             1x   1x 1x 1x           1x 1x             1x           55x                                                                 55x 55x     55x 55x         55x             18x       18x   18x 18x     18x 18x        
import {Serializer} from '../serializer'
import {P2PErrorHandler, P2PHandler, P2PProvider} from './provider'
import {NetMessage, TimeMessage} from './types'
 
type SetTimeout = (handler: any, timeout: number, ...args: any[]) => number
type TimeoutID = ReturnType<SetTimeout>
 
export interface P2PClientOptions {
    /** P2P provider to use  */
    provider: P2PProvider
 
    /** heartbeat timout in milliseconds, or undefined if no heartbeat is desired */
    heartbeatTimoutMs?: number
 
    /** alternative implementation for setTimeout (mostly for testing) */
    setTimeoutImpl?: SetTimeout
}
 
/**
 * @argument message a decoded message from the lower transport layer
 */
export type P2PMessageHandler = (message: NetMessage) => void
 
type P2PClientEventMap = {
    message: P2PMessageHandler
    error: P2PErrorHandler
    close: P2PHandler
}
 
export class P2PClient {
    static __className = 'P2PClient'
 
    readonly provider: P2PProvider
 
    private setTimeoutImpl: SetTimeout
    private heartbeatTimoutMs?: number
    private heartbeatTimoutId?: TimeoutID
    private eventListeners: {
        [T in keyof P2PClientEventMap]?: Array<{
            once: boolean
            handler: P2PClientEventMap[T]
        }>
    }
 
    constructor(options: P2PClientOptions) {
        Eif (options.provider) {
            this.provider = options.provider
        } else {
            throw new Error('Missing provider')
        }
 
        if (options.setTimeoutImpl !== undefined) {
            this.setTimeoutImpl = options.setTimeoutImpl
        } else {
            this.setTimeoutImpl = setTimeout
        }
 
        if (options.heartbeatTimoutMs !== undefined) {
            this.heartbeatTimoutMs = options.heartbeatTimoutMs
            this.resetHeartbeat()
        }
 
        this.provider.on('data', (data: Uint8Array) => {
            this.handleData(data)
        })
 
        this.provider.on('error', (e: any) => {
            this.emit('error', [e])
        })
 
        this.provider.on('close', () => {
            this.emit('close', [])
        })
 
        this.eventListeners = {}
    }
 
    send(message: NetMessage['value'], done?: P2PHandler): void {
        const wrappedMessage = NetMessage.from(message)
        const messageBuffer = Serializer.encode({object: wrappedMessage})
        this.provider.write(messageBuffer.array, done)
    }
 
    end(cb?: P2PHandler): void {
        this.endHeartbeat()
        this.provider.end(cb)
    }
 
    destroy(err?: Error): void {
        this.endHeartbeat()
        this.provider.destroy(err)
    }
 
    private handleData(data: Uint8Array): void {
        try {
            const message = Serializer.decode({type: NetMessage, data})
            this.emit('message', [message])
        } catch (e: any) {
            this.emit('error', [e])
        }
    }
 
    private endHeartbeat() {
        Iif (this.heartbeatTimoutId !== undefined) {
            clearTimeout(this.heartbeatTimoutId)
            this.heartbeatTimoutId = undefined
        }
    }
 
    private resetHeartbeat() {
        this.endHeartbeat()
 
        Eif (this.heartbeatTimoutMs !== undefined) {
            this.setTimeoutImpl(() => {
                this.handleHeartbeat()
            }, this.heartbeatTimoutMs)
        }
    }
 
    private handleHeartbeat() {
        const now = Date.now()
        const timeMessage = TimeMessage.from({
            org: now,
            rec: 0,
            xmt: 0,
            dst: 0,
        })
 
        this.send(timeMessage, () => {
            this.resetHeartbeat()
        })
    }
 
    on<T extends keyof P2PClientEventMap>(event: T, handler: P2PClientEventMap[T]): this {
        return this.addListenerInternal(event, handler, false, false)
    }
    once<T extends keyof P2PClientEventMap>(event: T, handler: P2PClientEventMap[T]): this {
        return this.addListenerInternal(event, handler, true, false)
    }
    addListener<T extends keyof P2PClientEventMap>(event: T, handler: P2PClientEventMap[T]): this {
        return this.addListenerInternal(event, handler, false, false)
    }
    prependListener<T extends keyof P2PClientEventMap>(
        event: T,
        handler: P2PClientEventMap[T]
    ): this {
        return this.addListenerInternal(event, handler, false, true)
    }
    removeListener<T extends keyof P2PClientEventMap>(
        event: T,
        handler: P2PClientEventMap[T]
    ): this {
        if (this.eventListeners[event] !== undefined) {
            this.eventListeners[event] = this.eventListeners[event]!.filter((e) => {
                return e.handler !== handler
            }) as (typeof this.eventListeners)[T]
        }
 
        return this
    }
 
    private addListenerInternal<T extends keyof P2PClientEventMap>(
        event: T,
        handler: P2PClientEventMap[T],
        once: boolean,
        prepend: boolean
    ): this {
        Eif (this.eventListeners[event] === undefined) {
            this.eventListeners[event] = []
        }
 
        Eif (!prepend) {
            this.eventListeners[event]!.push({once, handler})
        } else {
            this.eventListeners[event]!.unshift({once, handler})
        }
 
        return this
    }
 
    private emit<T extends keyof P2PClientEventMap>(
        event: T,
        args: Parameters<P2PClientEventMap[T]>
    ) {
        Iif (this.eventListeners[event] === undefined) {
            return
        }
 
        for (const {handler} of this.eventListeners[event]!) {
            // typescript is loosing the specificity provided by T in the assignment above
            const erasedHandler = handler as any
            erasedHandler(...args)
        }
 
        this.eventListeners[event] = this.eventListeners[event]!.filter((e) => {
            return e.once !== true
        }) as (typeof this.eventListeners)[T]
    }
}