|
| 1 | +import { log } from './logger.js' |
| 2 | +import type { StallDetectionOptions } from './options.js' |
| 3 | +import type { HttpStack } from './options.js' |
| 4 | + |
| 5 | +export class StallDetector { |
| 6 | + private options: StallDetectionOptions |
| 7 | + private httpStack: HttpStack |
| 8 | + private onStallDetected: (reason: string) => void |
| 9 | + |
| 10 | + private intervalId: ReturnType<typeof setInterval> | null = null |
| 11 | + private lastProgressTime = 0 |
| 12 | + private isActive = false |
| 13 | + |
| 14 | + constructor( |
| 15 | + options: StallDetectionOptions, |
| 16 | + httpStack: HttpStack, |
| 17 | + onStallDetected: (reason: string) => void, |
| 18 | + ) { |
| 19 | + this.options = options |
| 20 | + this.httpStack = httpStack |
| 21 | + this.onStallDetected = onStallDetected |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * Start monitoring for stalls |
| 26 | + */ |
| 27 | + start() { |
| 28 | + if (this.intervalId) { |
| 29 | + return // Already started |
| 30 | + } |
| 31 | + |
| 32 | + this.lastProgressTime = Date.now() |
| 33 | + this.isActive = true |
| 34 | + |
| 35 | + log( |
| 36 | + `tus: starting stall detection with checkInterval: ${this.options.checkInterval}ms, stallTimeout: ${this.options.stallTimeout}ms`, |
| 37 | + ) |
| 38 | + |
| 39 | + // Setup periodic check |
| 40 | + this.intervalId = setInterval(() => { |
| 41 | + if (!this.isActive) { |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + const now = Date.now() |
| 46 | + if (this._isProgressStalled(now)) { |
| 47 | + this._handleStall('no progress events received') |
| 48 | + } |
| 49 | + }, this.options.checkInterval) |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Stop monitoring for stalls |
| 54 | + */ |
| 55 | + stop(): void { |
| 56 | + this.isActive = false |
| 57 | + if (this.intervalId) { |
| 58 | + clearInterval(this.intervalId) |
| 59 | + this.intervalId = null |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * Update progress information |
| 65 | + */ |
| 66 | + updateProgress(): void { |
| 67 | + this.lastProgressTime = Date.now() |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * Check if upload has stalled based on progress events |
| 72 | + */ |
| 73 | + private _isProgressStalled(now: number): boolean { |
| 74 | + const timeSinceProgress = now - this.lastProgressTime |
| 75 | + const stallTimeout = this.options.stallTimeout |
| 76 | + const isStalled = timeSinceProgress > stallTimeout |
| 77 | + |
| 78 | + if (isStalled) { |
| 79 | + log(`tus: no progress for ${timeSinceProgress}ms (limit: ${stallTimeout}ms)`) |
| 80 | + } |
| 81 | + |
| 82 | + return isStalled |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * Handle a detected stall |
| 87 | + */ |
| 88 | + private _handleStall(reason: string): void { |
| 89 | + log(`tus: upload stalled: ${reason}`) |
| 90 | + this.stop() |
| 91 | + this.onStallDetected(reason) |
| 92 | + } |
| 93 | +} |
0 commit comments