All files client.ts

92.64% Statements 214/231
82.85% Branches 87/105
90.47% Functions 38/42
93.39% Lines 212/227

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 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 46586x                           1x   1x 1x 1x 1x 1x   1x   1x                     33x   33x 33x 33x 33x 33x 33x   33x 33x 33x 33x     33x 33x 33x 33x                     33x 33x 33x 33x       33x       33x       33x   33x       33x 33x       33x 33x       2x       2x               2x       1x       32x 1x   31x       33x     33x 33x       33x 33x 31x 31x 31x   33x 33x 5x   33x 3x 3x 3x         38x 1x   37x 37x 21x   16x 16x 16x         3x     3x 3x     3x 3x 1x 1x 1x   3x 1x 1x   3x 1x 1x           40x 19x   21x 21x 21x       3x 9x 9x 8x   1x             50x 50x       50x 50x 50x   50x 50x     50x 103x     50x       50x 19x 19x 19x 12x   19x 19x 1x   19x           50x       50x       50x 50x   50x     50x       50x 12x 38x 2x     50x   50x 50x 50x 33x         103x         103x 103x         103x   50x 50x   40x 40x   7x 7x   6x 6x         50x 35x 15x 15x 5x 5x   10x   45x 1x 1x         1x   44x                 44x 1x   44x 1x     44x 15x 15x 15x 15x 15x 15x 29x 25x 25x   4x         4x 4x 1x             4x       5x 5x 2x   5x       9x     9x 9x   9x 9x       40x 40x 40x 17x         7x 7x 7x 7x 7x 1x         6x 6x         40x 1x   39x       36x     36x 1x   35x 35x 9x 9x 9x         9x     9x       9x       19x 13x   6x       19x 19x 19x 19x 19x     19x     1x  
import {Checksum256, Name, UInt64} from '@wharfkit/antelope'
 
import {
    ActionStreamFilter,
    ActionStreamOptions,
    ErrorCode,
    StreamAction,
    StreamGap,
    StreamOverflow,
    StreamState,
    WsAckMessage,
    WsActionMessage,
    WsServerMessage,
    WsSubscribeMessage,
} from './types'
 
const DEFAULT_RECONNECT_DELAY = 1000
const DEFAULT_RECONNECT_MAX_DELAY = 30000
const DEFAULT_ACK_INTERVAL = 1000
const DEFAULT_QUEUE_SIZE = 1000
const DEFAULT_HEALTHY_THRESHOLD = 10000
 
const START_AT_HEAD_SENTINEL = UInt64.from(UInt64.max)
 
export class ActionStreamClient {
    private url: string
    private filter: ActionStreamFilter
    private decode: boolean
    private reconnectDelay: number
    private reconnectMaxDelay: number
    private ackInterval: number
    private queueSize: number
    private healthyThreshold: number
    private startAtHead: boolean
 
    private ws: WebSocket | null = null
    private currentSeq: UInt64
    private lastAcked: UInt64 = UInt64.from(0)
    private closed = false
    private _connected = false
    private _catchupComplete = false
    private _headSeq: UInt64 = UInt64.from(0)
    private _libSeq: UInt64 = UInt64.from(0)
 
    private queue: StreamAction[] = []
    private waitingResolve: ((action: StreamAction) => void) | null = null
    private waitingReject: ((err: Error) => void) | null = null
    private reconnectTimer: ReturnType<typeof setTimeout> | null = null
    private currentBackoff: number
    private readonly ackIntervalU64: UInt64
    private hasAcked = false
    private catchupCompleteAt: number | null = null
    private _overflowCount = 0
    private expectedSubSeq: number | null = 1
 
    onHeartbeat?: (state: StreamState) => void
    onCatchupComplete?: (state: StreamState) => void
    onError?: (code: number, message: string) => void
    onConnect?: () => void
    onDisconnect?: () => void
    onOverflow?: (overflow: StreamOverflow) => void
    onGap?: (gap: StreamGap) => void
 
    constructor(url: string, filter: ActionStreamFilter, options?: ActionStreamOptions) {
        this.url = url
        this.filter = filter
        this.decode = options && options.decode !== undefined ? options.decode : true
        this.reconnectDelay =
            options && options.reconnectDelay !== undefined
                ? options.reconnectDelay
                : DEFAULT_RECONNECT_DELAY
        this.reconnectMaxDelay =
            options && options.reconnectMaxDelay !== undefined
                ? options.reconnectMaxDelay
                : DEFAULT_RECONNECT_MAX_DELAY
        this.ackInterval =
            options && options.ackInterval !== undefined
                ? options.ackInterval
                : DEFAULT_ACK_INTERVAL
        this.queueSize =
            options && options.queueSize !== undefined ? options.queueSize : DEFAULT_QUEUE_SIZE
        this.healthyThreshold =
            options && options.healthyThreshold !== undefined
                ? options.healthyThreshold
                : DEFAULT_HEALTHY_THRESHOLD
        this.startAtHead = options !== undefined && options.startSeq === 'head'
        this.currentSeq =
            options && options.startSeq !== undefined && !this.startAtHead
                ? UInt64.from(options.startSeq)
                : UInt64.from(0)
        this.currentBackoff = this.reconnectDelay
        this.ackIntervalU64 = UInt64.from(this.ackInterval)
    }
 
    get headSeq(): UInt64 {
        return this._headSeq
    }
 
    get libSeq(): UInt64 {
        return this._libSeq
    }
 
    get connected(): boolean {
        return this._connected
    }
 
    get catchupComplete(): boolean {
        return this._catchupComplete
    }
 
    get overflowCount(): number {
        return this._overflowCount
    }
 
    connect(): void {
        if (this.closed) {
            throw new Error('Client is closed')
        }
        this.dial()
    }
 
    close(): void {
        Iif (this.closed) {
            return
        }
        this.closed = true
        Iif (this.reconnectTimer) {
            clearTimeout(this.reconnectTimer)
            this.reconnectTimer = null
        }
        const wasConnected = this._connected
        if (this.ws) {
            this.ws.onclose = null
            this.ws.close()
            this.ws = null
        }
        this._connected = false
        if (wasConnected && this.onDisconnect) {
            this.onDisconnect()
        }
        if (this.waitingReject) {
            this.waitingReject(new Error('Client closed'))
            this.waitingResolve = null
            this.waitingReject = null
        }
    }
 
    next(): Promise<StreamAction> {
        if (this.closed) {
            return Promise.reject(new Error('Client closed'))
        }
        const queued = this.takeQueued()
        if (queued) {
            return Promise.resolve(queued)
        }
        return new Promise<StreamAction>((resolve, reject) => {
            this.waitingResolve = resolve
            this.waitingReject = reject
        })
    }
 
    nextWithTimeout(timeoutMs: number): Promise<StreamAction | null> {
        Iif (this.closed) {
            return Promise.reject(new Error('Client closed'))
        }
        const queued = this.takeQueued()
        Iif (queued) {
            return Promise.resolve(queued)
        }
        return new Promise<StreamAction | null>((resolve, reject) => {
            const timer = setTimeout(() => {
                this.waitingResolve = null
                this.waitingReject = null
                resolve(null)
            }, timeoutMs)
            this.waitingResolve = (action: StreamAction) => {
                clearTimeout(timer)
                resolve(action)
            }
            this.waitingReject = (err: Error) => {
                clearTimeout(timer)
                reject(err)
            }
        })
    }
 
    private takeQueued(): StreamAction | null {
        if (this.queue.length === 0) {
            return null
        }
        const action = this.queue.shift()!
        this.ackSeq(action)
        return action
    }
 
    async *[Symbol.asyncIterator](): AsyncIterableIterator<StreamAction> {
        while (!this.closed) {
            try {
                const action = await this.next()
                yield action
            } catch {
                return
            }
        }
    }
 
    // resetConnectionState clears every field whose lifetime is one socket.
    private resetConnectionState(): void {
        this.catchupCompleteAt = null
        this.expectedSubSeq = 1
    }
 
    private dial(): void {
        const ws = new WebSocket(this.url)
        this.ws = ws
        this.resetConnectionState()
 
        ws.onopen = () => {
            this.sendSubscribe()
        }
 
        ws.onmessage = (event: MessageEvent) => {
            this.handleMessage(event.data)
        }
 
        ws.onerror = () => {
            // onclose will fire after onerror
        }
 
        ws.onclose = () => {
            const wasConnected = this._connected
            this._connected = false
            if (wasConnected && this.onDisconnect) {
                this.onDisconnect()
            }
            if (!this.closed) {
                if (this.wasHealthy()) {
                    this.currentBackoff = this.reconnectDelay
                }
                this.scheduleReconnect()
            }
        }
    }
 
    private sendSubscribe(): void {
        Iif (!this.ws) {
            return
        }
 
        const msg: WsSubscribeMessage = {
            type: 'subscribe',
        }
 
        if (this.filter.contracts && this.filter.contracts.length > 0) {
            msg.contracts = this.filter.contracts.map((c) => String(Name.from(c)))
        }
        Iif (this.filter.receivers && this.filter.receivers.length > 0) {
            msg.receivers = this.filter.receivers.map((r) => String(Name.from(r)))
        }
        Iif (this.filter.actions && this.filter.actions.length > 0) {
            msg.actions = this.filter.actions.map((a) => String(Name.from(a)))
        }
 
        if (this.currentSeq.gt(UInt64.from(0))) {
            msg.start_seq = this.currentSeq.toString()
        } else if (this.startAtHead) {
            msg.start_seq = START_AT_HEAD_SENTINEL.toString()
        }
 
        msg.decode = this.decode
 
        this.ws.send(JSON.stringify(msg))
        this._connected = true
        if (this.onConnect) {
            this.onConnect()
        }
    }
 
    private handleMessage(data: string | ArrayBuffer | Blob): void {
        Iif (typeof data !== 'string') {
            return
        }
 
        let msg: WsServerMessage
        try {
            msg = JSON.parse(data) as WsServerMessage
        } catch {
            return
        }
 
        switch (msg.type) {
            case 'action':
                this.handleAction(msg)
                break
            case 'heartbeat':
                this.handleHeartbeat(msg)
                break
            case 'catchup_complete':
                this.handleCatchupComplete(msg)
                break
            case 'error':
                this.handleError(msg)
                break
        }
    }
 
    private handleAction(msg: WsActionMessage): void {
        if (msg.sub_seq === undefined) {
            this.expectedSubSeq = null
        } else if (this.expectedSubSeq !== null) {
            if (msg.sub_seq !== this.expectedSubSeq) {
                this.handleGap(msg.sub_seq)
                return
            }
            this.expectedSubSeq = msg.sub_seq + 1
        }
        if (!msg.trx_id) {
            if (this.onError) {
                this.onError(
                    ErrorCode.DataInconsistent,
                    `Action ${msg.global_seq} arrived without a trx_id`
                )
            }
            return
        }
        const action: StreamAction = {
            globalSeq: UInt64.from(msg.global_seq),
            blockNum: msg.block_num,
            blockTime: msg.block_time,
            contract: Name.from(msg.contract),
            action: Name.from(msg.action),
            receiver: Name.from(msg.receiver),
            trxId: Checksum256.from(msg.trx_id),
        }
        if (msg.hex_data) {
            action.hexData = msg.hex_data
        }
        if (msg.data) {
            action.data = msg.data
        }
 
        if (this.waitingResolve) {
            const resolve = this.waitingResolve
            this.waitingResolve = null
            this.waitingReject = null
            this.acceptSeq(action)
            this.ackSeq(action)
            resolve(action)
        } else if (this.queue.length < this.queueSize) {
            this.queue.push(action)
            this.acceptSeq(action)
        } else {
            this.handleOverflow(action)
        }
    }
 
    private handleOverflow(action: StreamAction): void {
        this._overflowCount++
        if (this.onOverflow) {
            this.onOverflow({
                droppedFrom: action.globalSeq,
                resumeSeq: this.currentSeq,
                queueSize: this.queue.length,
                overflowCount: this._overflowCount,
            })
        }
        this.resubscribe()
    }
 
    private handleGap(received: number): void {
        const expected = this.expectedSubSeq!
        if (this.onGap) {
            this.onGap({expected, received, resumeSeq: this.currentSeq})
        }
        this.resubscribe()
    }
 
    private resubscribe(): void {
        Iif (!this.ws) {
            return
        }
        const ws = this.ws
        this.ws = null
        // Leave onclose wired: it owns the disconnect notice and the reconnect schedule.
        ws.onmessage = null
        ws.close()
    }
 
    private handleHeartbeat(msg: {head_seq: string; lib_seq: string}): void {
        this._headSeq = UInt64.from(msg.head_seq)
        this._libSeq = UInt64.from(msg.lib_seq)
        if (this.onHeartbeat) {
            this.onHeartbeat({headSeq: this._headSeq, libSeq: this._libSeq})
        }
    }
 
    private handleCatchupComplete(msg: {head_seq: string; lib_seq: string}): void {
        this._headSeq = UInt64.from(msg.head_seq)
        this._libSeq = UInt64.from(msg.lib_seq)
        this._catchupComplete = true
        this.catchupCompleteAt = Date.now()
        if (this.onCatchupComplete) {
            this.onCatchupComplete({headSeq: this._headSeq, libSeq: this._libSeq})
        }
    }
 
    private handleError(msg: {code: number; message: string}): void {
        if (this.onError) {
            this.onError(msg.code, msg.message)
        }
    }
 
    private acceptSeq(action: StreamAction): void {
        if (action.globalSeq.lt(this.currentSeq)) {
            return
        }
        this.currentSeq = action.globalSeq.adding(1).cast(UInt64)
    }
 
    private ackSeq(action: StreamAction): void {
        Iif (this.ackInterval <= 0) {
            return
        }
        if (this.hasAcked && action.globalSeq.lte(this.lastAcked)) {
            return
        }
        const diff = action.globalSeq.subtracting(this.lastAcked)
        if (diff.gte(this.ackIntervalU64)) {
            this.lastAcked = action.globalSeq
            this.hasAcked = true
            this.sendAck(action.globalSeq)
        }
    }
 
    private sendAck(seq: UInt64): void {
        Iif (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            return
        }
        const msg: WsAckMessage = {
            type: 'ack',
            seq: seq.toString(),
        }
        this.ws.send(JSON.stringify(msg))
    }
 
    private wasHealthy(): boolean {
        if (this.catchupCompleteAt === null) {
            return false
        }
        return Date.now() - this.catchupCompleteAt >= this.healthyThreshold
    }
 
    private scheduleReconnect(): void {
        const delay = this.currentBackoff
        this.currentBackoff = Math.min(this.currentBackoff * 2, this.reconnectMaxDelay)
        this.reconnectTimer = setTimeout(() => {
            this.reconnectTimer = null
            Iif (this.closed) {
                return
            }
            this.dial()
        }, delay)
    }
}