Skip to content

Commit

Permalink
fix: send oversize commands without erroring
Browse files Browse the repository at this point in the history
  • Loading branch information
Julusian committed Dec 11, 2023
1 parent fc1256e commit 296d4e3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
9 changes: 8 additions & 1 deletion src/lib/__tests__/packetBuilder.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,14 @@ describe('PacketBuilder', () => {
const builder = new PacketBuilder(500, ProtocolVersion.V8_1_1)

const cmd = new FakeCommand(501)
expect(() => builder.addCommand(cmd)).toThrow('too large')
expect(cmd.lengthWithHeader).toBe(501 + 8)
const smallCmd = new FakeCommand(10)

builder.addCommand(cmd)
builder.addCommand(smallCmd)
expect(builder.getPackets()).toHaveLength(2)
expect(builder.getPackets()[0]).toHaveLength(cmd.lengthWithHeader)
expect(builder.getPackets()[1]).toHaveLength(smallCmd.lengthWithHeader)
})

it('Command same size as packet', () => {
Expand Down
19 changes: 11 additions & 8 deletions src/lib/packetBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,12 @@ export class PacketBuilder {

const totalLength = payload.length + 8
if (totalLength > this.#maxPacketSize) {
throw new Error(`Comamnd ${cmd.constructor.name} is too large for a single packet`)
// Command is too large for a normal packet, try sending it on its own anyway
this.#finishBuffer(totalLength)
}

// Ensure the packet will fit into the current buffer
if (totalLength + this.#currentPacketFilled > this.#maxPacketSize) {
if (totalLength + this.#currentPacketFilled > this.#currentPacketBuffer.length) {
this.#finishBuffer()
}

Expand All @@ -48,20 +49,22 @@ export class PacketBuilder {
}

public getPackets(): Buffer[] {
this.#finishBuffer(false)
this.#finishBuffer(0)

this.#finished = true

return this.#completedBuffers
}

#finishBuffer(allocNewBuffer = true) {
if (this.#currentPacketFilled === 0 || this.#finished) return
#finishBuffer(newBufferLength = this.#maxPacketSize) {
if (this.#finished) return

this.#completedBuffers.push(this.#currentPacketBuffer.subarray(0, this.#currentPacketFilled))
if (this.#currentPacketFilled > 0) {
this.#completedBuffers.push(this.#currentPacketBuffer.subarray(0, this.#currentPacketFilled))
}

if (allocNewBuffer) {
this.#currentPacketBuffer = Buffer.alloc(this.#maxPacketSize)
if (newBufferLength > 0) {
this.#currentPacketBuffer = Buffer.alloc(newBufferLength)
this.#currentPacketFilled = 0
}
}
Expand Down

0 comments on commit 296d4e3

Please sign in to comment.