Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support compression in websockets #611 #2162

Merged
merged 14 commits into from
Oct 21, 2021
Merged

support compression in websockets #611 #2162

merged 14 commits into from
Oct 21, 2021

Conversation

cooliscool
Copy link
Contributor

#611

Here's my research on compression in Websockets :

permessage-deflate compression is defined in RFC7692 and gorilla/websockets has implemented this as an experimental feature.
read this here

permessage-deflate will work only if both client and server supports this extension - and successfully negotiates it through Sec-Websocket-Extensions header.

If EnableCompression is set to true, gorilla/websocket will automatically try to negotiate compression with peer.

var upgrader = websocket.Upgrader{
    EnableCompression: true,
}

Upon successful negotiation any message received in compressed form will be automatically decompressed by gorilla/websocket. So compression/decompression is taken care by gorilla/websocket if its supported.

Also, use of compression is experimental and may result in decreased performance.

the official RFC7692 has only defined deflate algorithm for compression in the specification as of now ( deflate from permessage-deflate). In future, say both a client and server wants to support algorithm 'foo' then this has to be negotiated through extension 'permessage-foo'. Few newer ones being discussed by IETF are 'permessage-bzip2', 'permessage-lz4', 'permessage-snappy'. These have not yet made it into the official RFCs. I'm not sure if any browsers are having experimental support for additional permessage algorithms.
More about in this stackoverflow question

I'd like to propose a PR for enabling EnableCompression: true to make compression work wherever it's supported.

@codebien
Copy link
Contributor

codebien commented Oct 7, 2021

HI @cooliscool, thanks for your contribution 🙏

As you noted, the feature is still marked as experimental and may result in decreased performance, we would prefer to not add it by default. Add a compression option to the connect param object can avoid unexpected use-cases for users. We already have the same thing for the HTTP params.

It would be useful also to add benchmarks with compression enabled and not.

@cooliscool
Copy link
Contributor Author

cooliscool commented Oct 8, 2021

Thanks for the review @codebien
Adding a compression option to connect params feels like the right way to do this.
I'm working on this. 👍

@cooliscool cooliscool marked this pull request as draft October 11, 2021 08:50
@cooliscool cooliscool marked this pull request as ready for review October 12, 2021 08:00
@cooliscool
Copy link
Contributor Author

i've added 'compression' param and tests for it.
benchmark is yet to be done. working on it.

@codecov-commenter
Copy link

codecov-commenter commented Oct 13, 2021

Codecov Report

Merging #2162 (e22217e) into master (42f2e60) will increase coverage by 0.04%.
The diff coverage is 81.81%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #2162      +/-   ##
==========================================
+ Coverage   72.71%   72.76%   +0.04%     
==========================================
  Files         184      184              
  Lines       14571    14586      +15     
==========================================
+ Hits        10596    10613      +17     
+ Misses       3333     3331       -2     
  Partials      642      642              
Flag Coverage Δ
ubuntu 72.71% <81.81%> (+0.06%) ⬆️
windows 72.48% <81.81%> (+0.11%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Impacted Files Coverage Δ
cmd/login_cloud.go 0.00% <0.00%> (ø)
cmd/login_influxdb.go 0.00% <0.00%> (ø)
cmd/ui.go 20.61% <0.00%> (ø)
js/compiler/compiler.go 55.00% <ø> (ø)
lib/execution_segment.go 92.73% <ø> (ø)
lib/executor/ramping_vus.go 94.66% <ø> (ø)
lib/metrics/metrics.go 100.00% <ø> (ø)
ui/form_fields.go 45.71% <0.00%> (ø)
js/modules/k6/ws/ws.go 84.02% <100.00%> (+0.87%) ⬆️
output/csv/config.go 74.00% <100.00%> (+4.23%) ⬆️
... and 2 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update f7a1ba1...e22217e. Read the comment docs.

@cooliscool
Copy link
Contributor Author

Added benchmarks - with and without compression

Here's what I did :

ws handler will send a message of 1KB to the client after Upgrade, then close the websocket

benchmarked this for the two scenarios - with and without compression

from the benchmark, time taken for a single operation is more - when compression is enabled - which could be explained by the overhead caused by encoding and decoding. (the advantages in network latency due to compression may not be captured here properly - because there's no real network, everthing is in memory right?)

PS: I had to separate the two benchmarks into different functions because of the increased cyclop complexity.

@codebien codebien self-requested a review October 19, 2021 10:59
@mstoykov mstoykov added this to the v0.35.0 milestone Oct 19, 2021
js/modules/k6/ws/ws_test.go Outdated Show resolved Hide resolved
js/modules/k6/ws/ws_test.go Outdated Show resolved Hide resolved
js/modules/k6/ws/ws_test.go Outdated Show resolved Hide resolved
js/modules/k6/ws/ws_test.go Outdated Show resolved Hide resolved
js/modules/k6/ws/ws_test.go Outdated Show resolved Hide resolved
js/modules/k6/ws/ws_test.go Outdated Show resolved Hide resolved
js/modules/k6/ws/ws_test.go Outdated Show resolved Hide resolved
na--
na-- previously approved these changes Oct 20, 2021
Copy link
Member

@na-- na-- left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly LGTM, thanks! 🙇

The only nitpick I have is that it seems that a lot of the code in BenchmarkCompressionEnabled() and BenchmarkCompressionDisabled() can probably be moved to a common function that just accepts compressionEnabled as a parameter.

Also, what are the results of actually running the benchmarks through something like benchstat?

@na-- na-- requested review from yorugac and inancgumus October 20, 2021 11:30
@cooliscool
Copy link
Contributor Author

cooliscool commented Oct 20, 2021

i could shrink the code to this :

func BenchmarkCompression(b *testing.B) {
	const textMessage = 1
	tb, samples, rt := newRuntime(b)
	sr := tb.Replacer.Replace

	cases := []struct {
		handler           string
		testCode          string
		compressionEnabled bool
	}{
		{
			"/ws-compression-enabled-echo",
			sr(`
			var res = ws.connect("WSBIN_URL/ws-compression-enabled-echo", {"compression":"deflate"}, (socket) => {
				socket.on('message', (data) => {
					socket.close()
				})
			});
			`),
			true,
		},
		{
			"/ws-compression-disabled-echo",
			sr(`
			var res = ws.connect("WSBIN_URL/ws-compression-disabled-echo", {}, (socket) => {
				socket.on('message', (data) => {
					socket.close()
				})
			});
			`),
			false,
		},
	}

	for i := 0; i < 2; i++ {
		i := i
		kbData := bytes.Repeat([]byte("0123456789"), 100)

		tb.Mux.HandleFunc(cases[i].handler, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			// upgrade connection, send the first (long) message, disconnect
			upgrader := websocket.Upgrader{
				EnableCompression: cases[i].compressionEnabled,
				ReadBufferSize:    1024,
				WriteBufferSize:   1024,
			}

			conn, e := upgrader.Upgrade(w, req, w.Header())
			if e != nil {
				b.Fatalf(cases[i].handler+" cannot upgrade request: %v", e)
				return
			}

			if err := conn.WriteMessage(textMessage, kbData); err != nil {
				b.Fatalf(cases[i].handler+" cannot write message: %v", err)
				return
			}

			e = conn.Close()
			if e != nil {
				b.Logf("error while closing connection in "+cases[i].handler+": %v", e)
				return
			}
		}))
	}

	go func() {
		ctxDone := tb.Context.Done()
		for {
			select {
			case <-samples:
			case <-ctxDone:
				return
			}
		}
	}()

	b.ResetTimer()
	b.Run("compression-enabled", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			if _, err := rt.RunString(cases[0].testCode); err != nil {
				b.Error(err)
			}
		}
	})

	b.Run("compression-disabled", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			if _, err := rt.RunString(cases[1].testCode); err != nil {
				b.Error(err)
			}
		}
	})
}

but this still has a cyclomatic complexity of 12 and lint check fails 😅 - only upto 10 is allowed.
any thoughts on reducing the complexity further ?

Benchstat results:

name                                old time/op  new time/op  delta
Compression/compression-disabled-4   314µs ± 0%   314µs ± 0%   ~     (p=1.000 n=1+1)
Compression/compression-enabled-4    347µs ± 0%   347µs ± 0%   ~     (p=1.000 n=1+1)

@mstoykov
Copy link
Contributor

LGTM as well, I would also prefer to get them in one function instead of multiple.

Looking at the code I think you can have 1 endpoint with the compression enabled and just not enable it on the client ? It shouldn't be used if the client doesn't have it enabled I hope?

I wonder about multiple body sizes, but I guess that wouldn't really matter for localhost networking 🤔

@cooliscool
Copy link
Contributor Author

Looking at the code I think you can have 1 endpoint with the compression enabled and just not enable it on the client ? It shouldn't be used if the client doesn't have it enabled I hope?

Yes. It shouldn't matter. Thanks for the suggestion.

@cooliscool cooliscool requested a review from na-- October 21, 2021 11:19
Copy link
Member

@na-- na-- left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

Copy link
Contributor

@codebien codebien left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks for your contribution 🎉

@mstoykov mstoykov merged commit 576f73a into grafana:master Oct 21, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants