Skip to content

Commit

Permalink
Fix panic with setInterval in k6/ws
Browse files Browse the repository at this point in the history
The panic happens when interval between 0 and 1 is given.

The code that tested whether the interval was > 0 correctly converted to
floats first and then back to time. And then checked it in order to
prevent this very panic.

Unfortunately it then did the same calculation again but this time by
converting the interval directly to int before multiplying by
milliseconds. Which ends up rounding it to 0. Making the whole result
zero and leading to time.NewTicker to panic.

This was already done correctly for setTimeout when the same panic was
found there and the wrong conversation was added for setInterval.

Previous commit df3ad1b
  • Loading branch information
mstoykov committed Feb 2, 2023
1 parent 4e88cc1 commit b85d09d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
3 changes: 2 additions & 1 deletion js/modules/k6/ws/ws.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ func (mi *WS) Exports() modules.Exports {
}

// Connect establishes a WebSocket connection based on the parameters provided.
//
//nolint:funlen
func (mi *WS) Connect(url string, args ...goja.Value) (*HTTPResponse, error) {
ctx := mi.vu.Context()
Expand Down Expand Up @@ -453,7 +454,7 @@ func (s *Socket) SetInterval(fn goja.Callable, intervalMs float64) error {
return fmt.Errorf("setInterval requires a >0 timeout parameter, received %.2f", intervalMs)
}
go func() {
ticker := time.NewTicker(time.Duration(intervalMs) * time.Millisecond)
ticker := time.NewTicker(d)
defer ticker.Stop()

for {
Expand Down
20 changes: 19 additions & 1 deletion js/modules/k6/ws/ws_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ func TestSessionInterval(t *testing.T) {
assertSessionMetricsEmitted(t, metrics.GetBufferedSamples(test.samples), "", sr("WSBIN_URL/ws-echo"), statusProtocolSwitch, "")
}

func TestSessionBadInterval(t *testing.T) {
func TestSessionNegativeInterval(t *testing.T) {
t.Parallel()
tb := httpmultibin.NewHTTPMultiBin(t)
sr := tb.Replacer.Replace
Expand All @@ -236,6 +236,24 @@ func TestSessionBadInterval(t *testing.T) {
require.Contains(t, err.Error(), "setInterval requires a >0 timeout parameter, received -1.23 ")
}

func TestSessionIntervalSub1(t *testing.T) {
t.Parallel()
tb := httpmultibin.NewHTTPMultiBin(t)
sr := tb.Replacer.Replace

test := newTestState(t)
_, err := test.VU.Runtime().RunString(sr(`
var counter = 0;
var res = ws.connect("WSBIN_URL/ws-echo", function(socket){
socket.setInterval(function () {
counter += 1;
if (counter > 2) { socket.close(); }
}, 0.3);
});
`))
require.NoError(t, err)
}

func TestSessionTimeout(t *testing.T) {
t.Parallel()
tb := httpmultibin.NewHTTPMultiBin(t)
Expand Down

0 comments on commit b85d09d

Please sign in to comment.