From 296d4e38ad45317bdc5fb5839f4e2d09b13a869f Mon Sep 17 00:00:00 2001 From: Julian Waller Date: Mon, 11 Dec 2023 10:48:35 +0000 Subject: [PATCH] fix: send oversize commands without erroring --- src/lib/__tests__/packetBuilder.spec.ts | 9 ++++++++- src/lib/packetBuilder.ts | 19 +++++++++++-------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/lib/__tests__/packetBuilder.spec.ts b/src/lib/__tests__/packetBuilder.spec.ts index c4a69a76..658c3f65 100644 --- a/src/lib/__tests__/packetBuilder.spec.ts +++ b/src/lib/__tests__/packetBuilder.spec.ts @@ -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', () => { diff --git a/src/lib/packetBuilder.ts b/src/lib/packetBuilder.ts index 7958f29e..aa23f1ad 100644 --- a/src/lib/packetBuilder.ts +++ b/src/lib/packetBuilder.ts @@ -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() } @@ -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 } }