()
| 228 | } |
| 229 | |
| 230 | process() { |
| 231 | if (this.error) { |
| 232 | return; |
| 233 | } |
| 234 | |
| 235 | const buffers = []; |
| 236 | const callbacks = []; |
| 237 | let totalLength = 0; |
| 238 | |
| 239 | while (this.queue.length > 0 && totalLength < this.coalescingThreshold) { |
| 240 | const writeItem = this.queue.shift(); |
| 241 | if (!writeItem.operation.canBeWritten()) { |
| 242 | // Invoke the write callback with an error that is not going to be yielded to user |
| 243 | // as the operation has timed out or was cancelled. |
| 244 | writeItem.callback(new Error('The operation was already cancelled or timeout elapsed')); |
| 245 | continue; |
| 246 | } |
| 247 | let data; |
| 248 | try { |
| 249 | data = writeItem.operation.request.write(this.encoder, writeItem.operation.streamId); |
| 250 | } |
| 251 | catch (err) { |
| 252 | writeItem.callback(err); |
| 253 | continue; |
| 254 | } |
| 255 | totalLength += data.length; |
| 256 | buffers.push(data); |
| 257 | callbacks.push(writeItem.callback); |
| 258 | } |
| 259 | |
| 260 | if (totalLength === 0) { |
| 261 | this.isRunning = false; |
| 262 | return; |
| 263 | } |
| 264 | |
| 265 | // We have to invoke the callbacks to avoid race conditions. |
| 266 | // There is a performance benefit from executing all of them in a loop |
| 267 | for (let i = 0; i < callbacks.length; i++) { |
| 268 | callbacks[i](); |
| 269 | } |
| 270 | |
| 271 | // Concatenate buffers and write it to the socket |
| 272 | // Further writes will be throttled until flushed |
| 273 | this.canWrite = this.netClient.write(Buffer.concat(buffers, totalLength), err => { |
| 274 | if (err) { |
| 275 | this.setWriteError(err); |
| 276 | return; |
| 277 | } |
| 278 | |
| 279 | if (this.queue.length === 0 || !this.canWrite) { |
| 280 | // It will start running once we get the next message or has drained |
| 281 | this.isRunning = false; |
| 282 | return; |
| 283 | } |
| 284 | |
| 285 | // Allow IO between writes |
| 286 | setImmediate(() => this.process()); |
| 287 | }); |
no test coverage detected