Skip to content

Commit

Permalink
feat: make retransmit timer use setTimeout instead of setInterval #…
Browse files Browse the repository at this point in the history
…96

This is so that it only runs when packets are inflight, and lowers idle cpu usage
  • Loading branch information
Julusian committed Sep 20, 2023
1 parent 6ed8e4f commit e84cf95
Showing 1 changed file with 25 additions and 10 deletions.
35 changes: 25 additions & 10 deletions src/lib/atemSocketChild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export class AtemSocketChild {

private _connectionState = ConnectionState.Closed
private _reconnectTimer: NodeJS.Timer | undefined
private _retransmitTimer: NodeJS.Timer | undefined
private _retransmitTimer: NodeJS.Timeout | undefined

private _nextSendPacketId = 1
private _sessionId = 0
Expand Down Expand Up @@ -98,14 +98,6 @@ export class AtemSocketChild {
})
}, CONNECTION_RETRY_INTERVAL)
}
// Check for retransmits every 10 milliseconds
if (!this._retransmitTimer) {
this._retransmitTimer = setInterval(() => {
this._checkForRetransmit().catch((e) => {
this.log(`Failed to retransmit: ${e?.message ?? e}`)
})
}, RETRANSMIT_INTERVAL)
}
}

public async connect(address: string, port: number): Promise<void> {
Expand All @@ -126,7 +118,7 @@ export class AtemSocketChild {

private _clearTimers() {
if (this._retransmitTimer) {
clearInterval(this._retransmitTimer)
clearTimeout(this._retransmitTimer)
this._retransmitTimer = undefined
}
if (this._reconnectTimer) {
Expand Down Expand Up @@ -197,6 +189,7 @@ export class AtemSocketChild {
payload: buffer,
resent: 0,
})
this._triggerRetransmitTimer()
}

private _recreateSocket(): Socket {
Expand Down Expand Up @@ -305,6 +298,8 @@ export class AtemSocketChild {
return true
}
})
this._triggerRetransmitTimer()

ps.push(this.onCommandsAcknowledged(ackedCommands))
// this.log(`${Date.now()} Got ack ${ackPacketId} Remaining=${this._inFlight.length}`)
}
Expand Down Expand Up @@ -378,8 +373,28 @@ export class AtemSocketChild {
}
}

private _triggerRetransmitTimer(): void {
if (!this._inFlight.length && this._retransmitTimer) {
clearTimeout(this._retransmitTimer)
delete this._retransmitTimer
return
}

if (!this._retransmitTimer) {
this._retransmitTimer = setTimeout(() => {
delete this._retransmitTimer
this._checkForRetransmit().catch((e) => {
this.log(`Failed to retransmit: ${e?.message ?? e}`)
})
}, RETRANSMIT_INTERVAL)
}
}

private async _checkForRetransmit(): Promise<void> {
if (!this._inFlight.length) return

this._triggerRetransmitTimer()

const now = performance.now()
for (const sentPacket of this._inFlight) {
if (sentPacket.lastSent + IN_FLIGHT_TIMEOUT < now) {
Expand Down

0 comments on commit e84cf95

Please sign in to comment.