File tree 2 files changed +24
-18
lines changed
2 files changed +24
-18
lines changed Original file line number Diff line number Diff line change @@ -10,19 +10,28 @@ import { Readable } from 'node:stream'
10
10
export function monitorStream ( dataStream : Readable ) {
11
11
const speedMonitor = monitorStreamSpeed ( dataStream )
12
12
const byteCounter = createByteCounterStream ( )
13
+ const span = trace . getActiveSpan ( )
13
14
14
- let measures : number [ ] = [ ]
15
+ let measures : any [ ] = [ ]
15
16
16
17
// Handle the 'speed' event to collect speed measurements
17
18
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
+ } )
21
31
} )
22
32
23
33
speedMonitor . on ( 'close' , ( ) => {
24
34
measures = [ ]
25
- const span = trace . getActiveSpan ( )
26
35
span ?. setAttributes ( { uploadRead : byteCounter . bytes } )
27
36
} )
28
37
Original file line number Diff line number Diff line change 1
1
import { Readable } from 'stream'
2
2
import { PassThrough } from 'node:stream'
3
3
4
- /**
5
- * Keep track of a stream's speed
6
- * @param stream
7
- * @param frequency
8
- */
9
4
/**
10
5
* Keep track of a stream's speed
11
6
* @param stream
12
7
* @param frequency
13
8
*/
14
9
export function monitorStreamSpeed ( stream : Readable , frequency = 1000 ) {
15
- let totalBytes = 0
16
- const startTime = Date . now ( )
10
+ let lastIntervalBytes = 0
17
11
18
12
const passThrough = new PassThrough ( )
19
13
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 )
25
16
passThrough . emit ( 'speed' , currentSpeedBytesPerSecond )
17
+ lastIntervalBytes = 0 // Reset for the next interval
18
+ }
19
+
20
+ const interval = setInterval ( ( ) => {
21
+ emitSpeed ( )
26
22
} , frequency )
27
23
28
24
passThrough . on ( 'data' , ( chunk ) => {
29
- totalBytes += chunk . length
25
+ lastIntervalBytes += chunk . length // Increment bytes for the current interval
30
26
} )
31
27
32
28
const cleanup = ( ) => {
29
+ emitSpeed ( )
33
30
clearInterval ( interval )
34
31
passThrough . removeAllListeners ( 'speed' )
35
32
}
You can’t perform that action at this time.
0 commit comments