955 BJavaScriptView Raw
1// Manage how quickly messages are delivered to the channel. In theory, we
2// should be able to call `send()` until it returns `false` but this leads to
3// crashes with advanced serialization, see
4// <https://github.com/nodejs/node/issues/34797>.
5//
6// Even if that's fixed (and the Node.js versions with the fixes are the
7// minimally supported versions) we need flow control based on `send()`'s return
8// value.
9
10const nowAndTimers = require('./now-and-timers');
11
12function controlFlow(channel) {
13 let sending = false;
14
15 const buffer = [];
16 const deliverNext = () => {
17 if (!channel.connected) {
18 buffer.length = 0;
19 }
20
21 if (buffer.length === 0) {
22 sending = false;
23 return;
24 }
25
26 channel.send(buffer.shift(), deliverNext);
27 };
28
29 return message => {
30 if (!channel.connected) {
31 return;
32 }
33
34 buffer.push(message);
35 if (!sending) {
36 sending = true;
37 nowAndTimers.setImmediate(deliverNext);
38 }
39 };
40}
41
42exports.controlFlow = controlFlow;