Moved peer connection to fully use write for backpressure

This commit is contained in:
Mitchell McCaffrey 2021-01-20 18:07:23 +11:00
parent 5a0567019a
commit 435752e7a9
2 changed files with 20 additions and 10 deletions

View File

@ -55,26 +55,26 @@ class Connection extends SimplePeer {
}
}
// Override the send function with encoding, chunking and data channel support
send(data, channel) {
// Custom send function with encoding, chunking and data channel support
// Uses `write` to send the data to allow for buffer / backpressure handling
sendObject(object, channel) {
try {
const packedData = encode(data);
const packedData = encode(object);
if (packedData.byteLength > MAX_BUFFER_SIZE) {
const chunks = this.chunk(packedData);
for (let chunk of chunks) {
if (this.dataChannels[channel]) {
// Write to the stream to allow for buffer / backpressure handling
this.dataChannels[channel].write(encode(chunk));
} else {
super.send(encode(chunk));
this.write(encode(chunk));
}
}
return;
} else {
if (this.dataChannels[channel]) {
this.dataChannels[channel].send(packedData);
this.dataChannels[channel].write(packedData);
} else {
super.send(packedData);
this.write(packedData);
}
}
} catch (error) {

View File

@ -124,10 +124,16 @@ class Session extends EventEmitter {
if (!this.peers[sessionId].ready) {
this.peers[sessionId].connection.once("connect", () => {
this.peers[sessionId].connection.send({ id: eventId, data }, channel);
this.peers[sessionId].connection.sendObject(
{ id: eventId, data },
channel
);
});
} else {
this.peers[sessionId].connection.send({ id: eventId, data }, channel);
this.peers[sessionId].connection.sendObject(
{ id: eventId, data },
channel
);
}
}
@ -193,10 +199,14 @@ class Session extends EventEmitter {
trickle: true,
config: { iceServers: this._iceServers },
});
// Up max listeners to 100 to account for up to 100 tokens on load
connection.setMaxListeners && connection.setMaxListeners(100);
const peer = { id, connection, initiator, ready: false };
function sendPeer(id, data, channel) {
peer.connection.send({ id, data }, channel);
peer.connection.sendObject({ id, data }, channel);
}
function handleSignal(signal) {