Skip to content

Commit 6b052d8

Browse files
authored
fix: adds more info on stream monitoring (#575)
1 parent f0c6953 commit 6b052d8

File tree

2 files changed

+24
-18
lines changed

2 files changed

+24
-18
lines changed

src/internal/streams/monitor.ts

+14-5
Original file line numberDiff line numberDiff line change
@@ -10,19 +10,28 @@ import { Readable } from 'node:stream'
1010
export function monitorStream(dataStream: Readable) {
1111
const speedMonitor = monitorStreamSpeed(dataStream)
1212
const byteCounter = createByteCounterStream()
13+
const span = trace.getActiveSpan()
1314

14-
let measures: number[] = []
15+
let measures: any[] = []
1516

1617
// Handle the 'speed' event to collect speed measurements
1718
speedMonitor.on('speed', (bps) => {
18-
measures.push(bps)
19-
const span = trace.getActiveSpan()
20-
span?.setAttributes({ 'stream.speed': measures, bytesRead: byteCounter.bytes })
19+
measures.push({
20+
'stream.speed': bps,
21+
'stream.bytesRead': byteCounter.bytes,
22+
'stream.status': {
23+
paused: dataStream.isPaused(),
24+
closed: dataStream.closed,
25+
},
26+
})
27+
28+
span?.setAttributes({
29+
stream: JSON.stringify(measures),
30+
})
2131
})
2232

2333
speedMonitor.on('close', () => {
2434
measures = []
25-
const span = trace.getActiveSpan()
2635
span?.setAttributes({ uploadRead: byteCounter.bytes })
2736
})
2837

src/internal/streams/stream-speed.ts

+10-13
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,32 @@
11
import { Readable } from 'stream'
22
import { PassThrough } from 'node:stream'
33

4-
/**
5-
* Keep track of a stream's speed
6-
* @param stream
7-
* @param frequency
8-
*/
94
/**
105
* Keep track of a stream's speed
116
* @param stream
127
* @param frequency
138
*/
149
export function monitorStreamSpeed(stream: Readable, frequency = 1000) {
15-
let totalBytes = 0
16-
const startTime = Date.now()
10+
let lastIntervalBytes = 0
1711

1812
const passThrough = new PassThrough()
1913

20-
const interval = setInterval(() => {
21-
const currentTime = Date.now()
22-
const elapsedTime = (currentTime - startTime) / 1000
23-
const currentSpeedBytesPerSecond = totalBytes / elapsedTime
24-
14+
const emitSpeed = () => {
15+
const currentSpeedBytesPerSecond = lastIntervalBytes / (frequency / 1000)
2516
passThrough.emit('speed', currentSpeedBytesPerSecond)
17+
lastIntervalBytes = 0 // Reset for the next interval
18+
}
19+
20+
const interval = setInterval(() => {
21+
emitSpeed()
2622
}, frequency)
2723

2824
passThrough.on('data', (chunk) => {
29-
totalBytes += chunk.length
25+
lastIntervalBytes += chunk.length // Increment bytes for the current interval
3026
})
3127

3228
const cleanup = () => {
29+
emitSpeed()
3330
clearInterval(interval)
3431
passThrough.removeAllListeners('speed')
3532
}

0 commit comments

Comments
 (0)