tus-js-client-stall-detection
Version:
A pure JavaScript client for the tus resumable upload protocol (fork with stall detection)
80 lines • 2.73 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StallDetector = void 0;
const logger_js_1 = require("./logger.js");
class StallDetector {
constructor(options, onStallDetected) {
this.intervalId = null;
this.lastProgressTime = 0;
this.lastProgressValue = 0;
this.isActive = false;
this.options = options;
this.onStallDetected = onStallDetected;
}
/**
* Start monitoring for stalls
* @param initialProgress Optional initial progress value to start with
*/
start(initialProgress) {
if (this.intervalId) {
return; // Already started
}
this.lastProgressTime = Date.now();
this.lastProgressValue = initialProgress !== null && initialProgress !== void 0 ? initialProgress : 0;
this.isActive = true;
(0, logger_js_1.log)(`tus: starting stall detection with checkInterval: ${this.options.checkInterval}ms, stallTimeout: ${this.options.stallTimeout}ms`);
// Setup periodic check
this.intervalId = setInterval(() => {
if (!this.isActive) {
return;
}
const now = Date.now();
if (this._isProgressStalled(now)) {
this._handleStall('no progress');
}
}, this.options.checkInterval);
}
/**
* Stop monitoring for stalls
*/
stop() {
this.isActive = false;
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
/**
* Update progress information
* @param progressValue The current progress value (bytes uploaded)
*/
updateProgress(progressValue) {
// Only update progress time if the value has actually changed
if (progressValue !== this.lastProgressValue) {
this.lastProgressTime = Date.now();
this.lastProgressValue = progressValue;
}
}
/**
* Check if upload has stalled based on progress events
*/
_isProgressStalled(now) {
const timeSinceProgress = now - this.lastProgressTime;
const stallTimeout = this.options.stallTimeout;
const isStalled = timeSinceProgress > stallTimeout;
if (isStalled) {
(0, logger_js_1.log)(`tus: no progress for ${timeSinceProgress}ms (limit: ${stallTimeout}ms)`);
}
return isStalled;
}
/**
* Handle a detected stall
*/
_handleStall(reason) {
(0, logger_js_1.log)(`tus: upload stalled: ${reason}`);
this.stop();
this.onStallDetected(reason);
}
}
exports.StallDetector = StallDetector;
//# sourceMappingURL=StallDetector.js.map