CartoDB-SQL-API/lib/services/throttler-stream.js

36 lines
1.0 KiB
JavaScript
Raw Normal View History

2019-05-29 17:20:18 +08:00
'use strict';
const { Transform } = require('stream');
module.exports = class Throttler extends Transform {
constructor (pgstream, ...args) {
super(...args);
this.pgstream = pgstream;
2019-11-20 19:57:18 +08:00
this.sampleSeconds = global.settings.copy_from_maximum_slow_input_speed_interval || 15;
this.minimunBytesPerSampleThreshold = global.settings.copy_from_minimum_input_speed || 0;
2019-05-29 17:20:18 +08:00
this.byteCount = 0;
2019-11-20 19:57:18 +08:00
this._interval = setInterval(this._updateMetrics.bind(this), this.sampleSeconds*1000);
2019-05-29 17:20:18 +08:00
}
_updateMetrics () {
2019-11-20 19:57:18 +08:00
if (this.byteCount < this.minimunBytesPerSampleThreshold) {
2019-05-29 17:20:18 +08:00
clearInterval(this._interval);
this.pgstream.emit('error', new Error('Connection closed by server: input data too slow'));
}
this.byteCount = 0;
2019-05-29 17:20:18 +08:00
}
_transform (chunk, encoding, callback) {
this.byteCount += chunk.length;
callback(null, chunk);
}
_flush (callback) {
clearInterval(this._interval);
callback();
}
2019-05-29 17:38:25 +08:00
};