systemquery/src/lib/transport/FramedTransport.mjs

96 lines
2.8 KiB
JavaScript

"use strict";
import { EventEmitter, once } from 'events';
import { write_safe, end_safe } from '../io/StreamHelpers.mjs';
/**
* Manages a TCP socket using a simple binary frame system.
* Frames look like this:
*
* <LENGTH: Uint32 big-endian> <DATA: Uint8Array>
*/
class FramedTransport {
constructor(socket) {
this.socket = socket;
this.socket.on("data", this.handle_chunk);
this.buffer = null;
/** The length of a uint in bytes @type {number} */
this.uint_length = 4;
this.writing = false;
}
/**
* Handles a single chunk of incoming data.
* May or may not emit a frame event.
* @param {Buffer|TypedArray} chunk The incoming chunk of data.
* @return {void}
*/
handle_chunk(chunk) {
if(this.buffer instanceof Buffer)
this.buffer = Buffer.concat(this.buffer, chunk);
let next_frame_length = this.buffer2uint(this.buffer, 0);
// We have enough data! Emit a frame and then start again.
if(this.buffer.length - this.uint_length >= next_frame_length) {
this.emit("frame", Buffer.slice(this.uint_length, next_frame_length));
if(this.buffer.length - (this.uint_length + next_frame_length) > 0)
this.buffer = Buffer.slice(this,uint_length + next_frame_length);
else
this.buffer = null;
}
}
/**
* Converts the number at a given position in a buffer from Uint32 with
* big-endian encoding to a normal number.
* @param {Buffer|TypedArray} buffer The source buffer.
* @param {number} pos32 The position in the buffer to read from.
* @return {number} The parsed number from the buffer.
*/
buffer2uint(buffer, pos32) {
return new DataView(buffer).getUint32(pos32, false);
}
/**
* Converts a positive integer into a Buffer using big-endian encoding.
* @param {number} uint The positive integer to convert.
* @return {Buffer} A new buffer representing the given number.
*/
uint2buffer(uint) {
let array = new ArrayBuffer(this.uint_length);
new DataView(array).setUint32(0, uint, false);
return Buffer.from(array);
}
/**
* Writes a given Buffer or TypedArray to the underlying socket inn a new frame.
* @param {Buffer|TypedArray} frame The data to send in a new frame.
* @return {Promise} A promise that resolves when writing is complete.
*/
async write(frame) {
if(this.writing) await once(this, "write-end");
this.emit("write-start");
this.writing = true;
await write_safe(this.socket, this.uint2buffer(frame.length));
await write_safe(this.socket, frame);
this.writing = false;
this.emit("write-end")
}
/**
* Gracefulls closes this socket.
* @return {Promise} A Promise that resolves when the socket is properly closed.
*/
async destroy() {
// Calling socket.end() is important as it closes the stream properly
await end_safe(this.socket);
await this.socket.destroy();
}
}
export default FramedTransport;