GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Merge pull request #12477 from mkurz/netty-websocket-compression · playframework/playframework@bf03999

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • core/play-integration-test/src/test/scala/play/it/http/websocket
    • WebSocketClient.scala
    • WebSocketSpec.scala
  • documentation/manual
    • releases/release31
      • Highlights31.md
    • working
      • javaGuide/main/async
        • JavaWebSockets.md
      • scalaGuide/main/async
        • ScalaWebSockets.md
  • transport/server
    • play-netty-server/src/main
      • resources
        • reference.conf
      • scala/play/core/server
        • NettyServer.scala
    • play-server/src/main/resources
      • reference.conf
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎core/play-integration-test/src/test/scala/play/it/http/websocket/WebSocketClient.scala‎

Copy file name to clipboardExpand all lines: core/play-integration-test/src/test/scala/play/it/http/websocket/WebSocketClient.scala
+43-4Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import io.netty.channel.socket.nio.NioSocketChannel
2727
import io.netty.channel.socket.SocketChannel
2828
import io.netty.handler.codec.http._
2929
import io.netty.handler.codec.http.websocketx._
30+
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler
3031
import io.netty.util.ReferenceCountUtil
3132
import org.apache.pekko.stream.scaladsl._
3233
import org.apache.pekko.stream.stage._
@@ -52,7 +53,12 @@ trait WebSocketClient {
5253
*
5354
* @return A future that will be redeemed when the connection is closed.
5455
*/
55-
def connect(url: URI, version: WebSocketVersion = WebSocketVersion.V13, subprotocol: Option[String] = None)(
56+
def connect(
57+
url: URI,
58+
version: WebSocketVersion = WebSocketVersion.V13,
59+
subprotocol: Option[String] = None,
60+
compressionMode: WebSocketClient.CompressionMode = WebSocketClient.CompressionMode.Disabled
61+
)(
5662
onConnect: (immutable.Seq[(String, String)], Flow[ExtendedMessage, ExtendedMessage, ?]) => Unit
5763
): Future[?]
5864

@@ -73,6 +79,15 @@ object WebSocketClient {
7379
}
7480
case class SimpleMessage(message: Message, finalFragment: Boolean) extends ExtendedMessage
7581
case class ContinuationMessage(data: ByteString, finalFragment: Boolean) extends ExtendedMessage
82+
case class RawWebSocketFrame(frameType: String, data: ByteString, rsv: Int, finalFragment: Boolean)
83+
extends ExtendedMessage
84+
85+
sealed trait CompressionMode
86+
object CompressionMode {
87+
case object Disabled extends CompressionMode
88+
case class Enabled(maxAllocation: Int = 65536) extends CompressionMode
89+
case class RequestOnly(extensions: String = "permessage-deflate") extends CompressionMode
90+
}
7691

7792
def create(): WebSocketClient = new DefaultWebSocketClient
7893

@@ -116,7 +131,7 @@ object WebSocketClient {
116131
/**
117132
* Connect to the given URI
118133
*/
119-
def connect(url: URI, version: WebSocketVersion, subprotocol: Option[String])(
134+
def connect(url: URI, version: WebSocketVersion, subprotocol: Option[String], compressionMode: CompressionMode)(
120135
onConnected: (immutable.Seq[(String, String)], Flow[ExtendedMessage, ExtendedMessage, ?]) => Unit
121136
): Future[?] = {
122137
val normalized = url.normalize()
@@ -130,12 +145,25 @@ object WebSocketClient {
130145
.connect(tgt.getHost, tgt.getPort)
131146
.toScala
132147
.map { channel =>
148+
compressionMode match {
149+
case CompressionMode.Enabled(maxAllocation) =>
150+
channel.pipeline().addLast("ws-compressor", new WebSocketClientCompressionHandler(maxAllocation))
151+
case CompressionMode.Disabled | _: CompressionMode.RequestOnly =>
152+
}
153+
154+
val headers = new DefaultHttpHeaders()
155+
compressionMode match {
156+
case CompressionMode.RequestOnly(extensions) =>
157+
headers.add(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS, extensions)
158+
case CompressionMode.Disabled | _: CompressionMode.Enabled =>
159+
}
160+
133161
val handshaker = WebSocketClientHandshakerFactory.newHandshaker(
134162
tgt,
135163
version,
136164
subprotocol.orNull,
137-
false,
138-
new DefaultHttpHeaders()
165+
compressionMode != CompressionMode.Disabled,
166+
headers
139167
)
140168
channel.pipeline().addLast("supervisor", new WebSocketSupervisor(disconnected, handshaker, onConnected))
141169
handshaker.handshake(channel)
@@ -233,6 +261,17 @@ object WebSocketClient {
233261

234262
val framesToMessages = Flow[WebSocketFrame].map { frame =>
235263
val message = frame match {
264+
case text: TextWebSocketFrame if text.rsv() != 0 =>
265+
RawWebSocketFrame("text", toByteString(text), text.rsv(), text.isFinalFragment)
266+
case binary: BinaryWebSocketFrame if binary.rsv() != 0 =>
267+
RawWebSocketFrame("binary", toByteString(binary), binary.rsv(), binary.isFinalFragment)
268+
case continuation: ContinuationWebSocketFrame if continuation.rsv() != 0 =>
269+
RawWebSocketFrame(
270+
"continuation",
271+
toByteString(continuation),
272+
continuation.rsv(),
273+
continuation.isFinalFragment
274+
)
236275
case text: TextWebSocketFrame => SimpleMessage(TextMessage(text.text()), text.isFinalFragment)
237276
case binary: BinaryWebSocketFrame =>
238277
SimpleMessage(BinaryMessage(toByteString(binary)), binary.isFinalFragment)
Collapse file

‎core/play-integration-test/src/test/scala/play/it/http/websocket/WebSocketSpec.scala‎

Copy file name to clipboardExpand all lines: core/play-integration-test/src/test/scala/play/it/http/websocket/WebSocketSpec.scala
+194-12Lines changed: 194 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44

55
package play.it.http.websocket
66

7+
import java.io.ByteArrayOutputStream
78
import java.net.URI
89
import java.util.concurrent.atomic.AtomicReference
10+
import java.util.zip.Inflater
911

1012
import scala.collection.immutable
1113
import scala.concurrent.duration._
@@ -40,11 +42,165 @@ import play.api.test._
4042
import play.api.Application
4143
import play.api.Configuration
4244
import play.it._
45+
import play.it.http.websocket.WebSocketClient.CompressionMode
4346
import play.it.http.websocket.WebSocketClient.ContinuationMessage
4447
import play.it.http.websocket.WebSocketClient.ExtendedMessage
48+
import play.it.http.websocket.WebSocketClient.RawWebSocketFrame
4549
import play.it.http.websocket.WebSocketClient.SimpleMessage
4650

47-
class NettyWebSocketSpec extends WebSocketSpec with NettyIntegrationSpecification
51+
class NettyWebSocketSpec extends WebSocketSpec with NettyIntegrationSpecification {
52+
"Plays WebSockets using netty backend with compression" should {
53+
"negotiate permessage-deflate" in {
54+
withServer(app =>
55+
WebSocket.accept[String, String] { req => Flow.fromSinkAndSource(Sink.ignore, Source.maybe[String]) }
56+
) { (app, port) =>
57+
import app.materializer
58+
val (_, headers) = runWebSocket(
59+
port,
60+
{ flow =>
61+
Source.empty[ExtendedMessage].via(flow).runWith(Sink.ignore)
62+
Future.successful(())
63+
},
64+
subprotocol = None,
65+
handleConnect = c => c,
66+
compressionMode = CompressionMode.Enabled()
67+
)
68+
69+
headers.collectFirst {
70+
case (name, value) if name.equalsIgnoreCase("Sec-WebSocket-Extensions") => value
71+
} must beSome(contain("permessage-deflate"))
72+
}
73+
}
74+
75+
"decompress inbound permessage-deflate frames before passing them to the application" in {
76+
val consumed = Promise[List[String]]()
77+
withServer(app =>
78+
WebSocket.accept[String, String] { req =>
79+
Flow.fromSinkAndSource(onFramesConsumed[String](consumed.success(_)), Source.maybe[String])
80+
}
81+
) { (app, port) =>
82+
import app.materializer
83+
val result = runWebSocket(
84+
port,
85+
{ flow =>
86+
sendFrames(
87+
TextMessage("compressed client message"),
88+
CloseMessage(1000)
89+
).via(flow).runWith(Sink.ignore)
90+
consumed.future
91+
},
92+
compressionMode = CompressionMode.Enabled()
93+
)
94+
95+
result must_== Seq("compressed client message")
96+
}
97+
}
98+
99+
"compress outbound permessage-deflate frames sent by the application" in {
100+
withServer(app =>
101+
WebSocket.accept[String, String] { req =>
102+
Flow.fromSinkAndSource(Sink.ignore, Source.single("compressed server message"))
103+
}
104+
) { (app, port) =>
105+
import app.materializer
106+
val frames = runWebSocket(
107+
port,
108+
{ flow => Source.maybe[ExtendedMessage].via(flow).runWith(consumeFrames) },
109+
compressionMode = CompressionMode.RequestOnly()
110+
)
111+
112+
frames.collectFirst {
113+
case RawWebSocketFrame("text", data, rsv, true) => (data, rsv)
114+
} must beSome[(ByteString, Int)].which {
115+
case (data, rsv) =>
116+
data.nonEmpty &&
117+
(rsv & 4) == 4 &&
118+
data != ByteString("compressed server message") &&
119+
inflatePerMessageDeflate(data).utf8String == "compressed server message"
120+
}
121+
}
122+
}
123+
124+
"not negotiate compression when websocket compression is disabled" in {
125+
withServer(
126+
app => WebSocket.accept[String, String] { req => Flow.fromSinkAndSource(Sink.ignore, Source.maybe[String]) },
127+
Map("play.server.websocket.compression.enabled" -> false)
128+
) { (app, port) =>
129+
import app.materializer
130+
val (_, headers) = runWebSocket(
131+
port,
132+
{ flow =>
133+
Source.empty[ExtendedMessage].via(flow).runWith(Sink.ignore)
134+
Future.successful(())
135+
},
136+
subprotocol = None,
137+
handleConnect = c => c,
138+
compressionMode = CompressionMode.RequestOnly()
139+
)
140+
141+
headers.collectFirst {
142+
case (name, value) if name.equalsIgnoreCase("Sec-WebSocket-Extensions") => value
143+
} must beNone
144+
}
145+
}
146+
147+
"use configured Netty permessage-deflate negotiation settings" in {
148+
withServer(
149+
app => WebSocket.accept[String, String] { req => Flow.fromSinkAndSource(Sink.ignore, Source.maybe[String]) },
150+
Map(
151+
"play.server.netty.websocket.compression.perMessageDeflate.allowServerWindowSize" -> true,
152+
"play.server.netty.websocket.compression.perMessageDeflate.serverWindowSize" -> 12,
153+
"play.server.netty.websocket.compression.perMessageDeflate.memLevel" -> 7,
154+
"play.server.netty.websocket.compression.perMessageDeflate.preferredClientWindowSize" -> 11,
155+
"play.server.netty.websocket.compression.perMessageDeflate.allowServerNoContext" -> true,
156+
"play.server.netty.websocket.compression.perMessageDeflate.preferredClientNoContext" -> true,
157+
"play.server.netty.websocket.compression.perMessageDeflate.compressionLevel" -> 5
158+
)
159+
) { (app, port) =>
160+
import app.materializer
161+
val (_, headers) = runWebSocket(
162+
port,
163+
{ flow =>
164+
Source.empty[ExtendedMessage].via(flow).runWith(Sink.ignore)
165+
Future.successful(())
166+
},
167+
subprotocol = None,
168+
handleConnect = c => c,
169+
compressionMode = CompressionMode.RequestOnly(
170+
"permessage-deflate; client_max_window_bits; server_max_window_bits=15; " +
171+
"client_no_context_takeover; server_no_context_takeover"
172+
)
173+
)
174+
175+
val extension = headers.collectFirst {
176+
case (name, value) if name.equalsIgnoreCase("Sec-WebSocket-Extensions") => value
177+
}
178+
179+
extension must beSome[String].which { value =>
180+
value.contains("permessage-deflate") &&
181+
value.contains("server_max_window_bits=12") &&
182+
value.contains("client_max_window_bits=11") &&
183+
value.contains("server_no_context_takeover") &&
184+
value.contains("client_no_context_takeover")
185+
}
186+
}
187+
}
188+
189+
"fail clearly when Netty websocket compression maxAllocation exceeds Netty's integer limit" in {
190+
withServer(
191+
app => WebSocket.accept[String, String] { req => Flow.fromSinkAndSource(Sink.ignore, Source.maybe[String]) },
192+
Map("play.server.netty.websocket.compression.maxAllocation" -> "3g")
193+
) { (_, _) =>
194+
()
195+
} must throwA[RuntimeException].like {
196+
case exception =>
197+
(exception.getCause must beAnInstanceOf[play.core.server.ServerStartException])
198+
.and(exception.getMessage must contain("play.server.netty.websocket.compression.maxAllocation"))
199+
}
200+
}
201+
202+
}
203+
}
48204
class PekkoHttpWebSocketSpec extends WebSocketSpec with PekkoHttpIntegrationSpecification {
49205
"Plays WebSockets using pekko-http backend with HTTP2 enabled" should {
50206
"time out after play.server.http.idleTimeout" in delayedSend(
@@ -391,7 +547,8 @@ trait WebSocketSpec
391547
sendFrames(TextMessage("foo"), CloseMessage(1000)).via(flow).runWith(Sink.ignore)
392548
},
393549
Some("my_crazy_subprotocol"),
394-
c => c
550+
c => c,
551+
CompressionMode.Disabled
395552
)
396553
(headers
397554
.map { case (key, value) => (key.toLowerCase, value) }
@@ -411,7 +568,8 @@ trait WebSocketSpec
411568
sendFrames(TextMessage("foo"), CloseMessage(1000)).via(flow).runWith(Sink.ignore)
412569
},
413570
Some("first-protocol, second-protocol, third-protocol"),
414-
c => c
571+
c => c,
572+
CompressionMode.Disabled
415573
)
416574
(headers
417575
.map { case (key, value) => (key.toLowerCase, value) }
@@ -436,7 +594,8 @@ trait WebSocketSpec
436594
sendFrames(TextMessage("foo"), CloseMessage(1000)).via(flow).runWith(Sink.ignore)
437595
},
438596
Some("graphql-ws, graphql-transport-ws"),
439-
c => c
597+
c => c,
598+
CompressionMode.Disabled
440599
)
441600
(headers
442601
.map { case (key, value) => (key.toLowerCase, value) }
@@ -666,7 +825,8 @@ trait WebSocketSpec
666825
sendFrames(TextMessage("foo"), CloseMessage(1000)).via(flow).runWith(Sink.ignore)
667826
},
668827
Some("graphql-ws, graphql-transport-ws"),
669-
c => c
828+
c => c,
829+
CompressionMode.Disabled
670830
)
671831
(headers
672832
.map { case (key, value) => (key.toLowerCase, value) }
@@ -784,32 +944,54 @@ trait WebSocketSpecMethods extends PlaySpecification with WsTestClient with Serv
784944
def runWebSocket[A](
785945
port: Int,
786946
handler: Flow[ExtendedMessage, ExtendedMessage, ?] => Future[A],
787-
handleConnect: Future[?] => Future[?] = c => c
947+
handleConnect: Future[?] => Future[?] = c => c,
948+
compressionMode: CompressionMode = CompressionMode.Disabled
788949
): A =
789-
runWebSocket(port, handler, subprotocol = None, handleConnect) match { case (result, _) => result }
950+
runWebSocket(port, handler, subprotocol = None, handleConnect, compressionMode) match { case (result, _) => result }
790951

791952
def runWebSocket[A](
792953
port: Int,
793954
handler: Flow[ExtendedMessage, ExtendedMessage, ?] => Future[A],
794955
subprotocol: Option[String],
795-
handleConnect: Future[?] => Future[?]
956+
handleConnect: Future[?] => Future[?],
957+
compressionMode: CompressionMode
796958
): (A, immutable.Seq[(String, String)]) = {
797959
WebSocketClient { client =>
798960
val innerResult = Promise[A]()
799961
val responseHeaders = Promise[immutable.Seq[(String, String)]]()
800962
await(
801963
handleConnect(
802-
client.connect(URI.create("ws://localhost:" + port + "/stream"), subprotocol = subprotocol) {
803-
(headers, flow) =>
804-
innerResult.completeWith(handler(flow))
805-
responseHeaders.success(headers)
964+
client.connect(
965+
URI.create("ws://localhost:" + port + "/stream"),
966+
subprotocol = subprotocol,
967+
compressionMode = compressionMode
968+
) { (headers, flow) =>
969+
innerResult.completeWith(handler(flow))
970+
responseHeaders.success(headers)
806971
}
807972
)
808973
)
809974
(await(innerResult.future), await(responseHeaders.future))
810975
}
811976
}
812977

978+
def inflatePerMessageDeflate(data: ByteString): ByteString = {
979+
val inflater = new Inflater(true)
980+
try {
981+
inflater.setInput((data ++ ByteString(0x00, 0x00, 0xff.toByte, 0xff.toByte)).toArray)
982+
val output = new ByteArrayOutputStream()
983+
val buffer = new Array[Byte](256)
984+
var count = inflater.inflate(buffer)
985+
while (count > 0) {
986+
output.write(buffer, 0, count)
987+
count = inflater.inflate(buffer)
988+
}
989+
ByteString.fromArray(output.toByteArray)
990+
} finally {
991+
inflater.end()
992+
}
993+
}
994+
813995
def pongFrame(matcher: Matcher[String]): Matcher[ExtendedMessage] = beLike {
814996
case SimpleMessage(PongMessage(data), _) => data.utf8String must matcher
815997
}
Collapse file

‎documentation/manual/releases/release31/Highlights31.md‎

Copy file name to clipboardExpand all lines: documentation/manual/releases/release31/Highlights31.md
+14Lines changed: 14 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,20 @@ This section highlights the new features of Play 3.1. If you want to learn about
66

77
## Other Additions
88

9+
### Netty WebSocket Compression
10+
11+
The Play Netty server backend now supports WebSocket compression using the RFC 7692 `permessage-deflate` extension.
12+
13+
Compression is enabled by default and is negotiated during the WebSocket handshake when the client offers `permessage-deflate` in the `Sec-WebSocket-Extensions` header. Applications can disable WebSocket compression for all server backends with:
14+
15+
```hocon
16+
play.server.websocket.compression.enabled = false
17+
```
18+
19+
The Netty backend also exposes Netty-specific tuning options under `play.server.netty.websocket.compression`, including the compression level, server and client window-size behavior, memory level, context-takeover behavior, and the decompression allocation limit. By default, the allocation limit follows `play.server.websocket.frame.maxLength`.
20+
21+
For more details, see the [[Scala WebSocket documentation|ScalaWebSockets#Configuring-WebSocket-compression]] and [[Java WebSocket documentation|JavaWebSockets#Configuring-WebSocket-compression]].
22+
923
### WebSocket Subprotocol Selection
1024

1125
Play now lets applications explicitly select the WebSocket subprotocol that is sent back in the successful `101 Switching Protocols` response.

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.