import { DNSPacket } from "../coder/DNSPacket" ; import { InterfaceName } from "../NetworkManager" ; import { QueryResponse } from "./QueryResponse" ; import Timeout = NodeJS . Timeout ; /**
 * Represents a delay response packet which is going to be sent over multicast.
 */ export class QueuedResponse { public static readonly MAX_DELAY = 500 ; private readonly packet : DNSPacket ; private readonly interfaceName : InterfaceName ; private timeOfCreation = new Date ( ) . getTime ( ) ; estimatedTimeToBeSent = 0 ; private delay = - 1 ; private timer ? : Timeout ; delayed ? : boolean ; constructor ( packet , interfaceName ) { this . packet = packet ; this . interfaceName = interfaceName ; } public getPacket ( ) { return this . packet ; } returns public getTimeSinceCreation ( ) { return new Date ( ) . getTime ( ) - this . timeOfCreation ; } public getTimeTillSent ( ) { return Math . max ( 0 , this . estimatedTimeToBeSent - new Date ( ) . getTime ( ) ) ; } public calculateRandomDelay ( ) { this . delay = Math . random ( ) * 100 + 20 ; this . estimatedTimeToBeSent = new Date ( ) . getTime ( ) + this . delay ; } public scheduleResponse ( callback ) { this . timer = setTimeout ( callback , this . delay ) ; this . timer . unref ( ) ; } public delayWouldBeInTimelyManner ( next ) { const delay = next . estimatedTimeToBeSent - this . timeOfCreation ; return delay <= QueuedResponse . MAX_DELAY ; } param next returns { code public combineWithNextPacketIfPossible ( next ) { if ( this . interfaceName !== next . interfaceName ) { return false ; } if ( ! next . packet . canBeCombinedWith ( this . packet ) ) { return false ; } next . packet . combineWith ( this . packet ) ; next . timeOfCreation = Math . min ( this . timeOfCreation , next . timeOfCreation ) ; if ( this . timer ) { clearTimeout ( this . timer ) ; this . timer = undefined ; } this . delayed = true ; return true ; } public combineWithUniqueResponseIfPossible ( response , interfaceName ) { if ( this . interfaceName !== interfaceName ) { return false ; } if ( ! this . packet . canBeCombinedWith ( response . asPacket ( ) ) ) { return false ; } this . packet . combineWith ( response . asPacket ( ) ) ; return true ; } }