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 #14118 from mkurz/websocket-compression-per-request · playframework/playframework@c183de6

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • core
    • play-integration-test/src/test
      • java/play/it/http/websocket
        • WebSocketSpecJavaActions.java
      • scala/play/it/http/websocket
        • WebSocketSpec.scala
    • play/src/main
      • java/play/mvc
        • WebSocket.java
      • scala/play
        • api/mvc
          • WebSocket.scala
        • core/routing
          • HandlerInvoker.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/scala/play/core/server
      • NettyServer.scala
      • netty
        • PlayRequestHandler.scala
    • play-pekko-http-server/src/main/scala
      • org/apache/pekko/http/play
        • WebSocketHandler.scala
      • play/core/server
        • PekkoHttpServer.scala
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎core/play-integration-test/src/test/java/play/it/http/websocket/WebSocketSpecJavaActions.java‎

Copy file name to clipboardExpand all lines: core/play-integration-test/src/test/java/play/it/http/websocket/WebSocketSpecJavaActions.java
+9Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,15 @@ public static WebSocket selectSubprotocol() {
6363
Flow.fromSinkAndSource(Sink.ignore(), Source.empty()), "graphql-transport-ws"));
6464
}
6565

66+
public static WebSocket selectSubprotocolWithoutCompression() {
67+
return WebSocket.Text.acceptWithOptions(
68+
request ->
69+
new WebSocket.Accepted<>(
70+
Flow.fromSinkAndSource(Sink.ignore(), Source.single("plain server message")),
71+
"graphql-transport-ws",
72+
false));
73+
}
74+
6675
public static WebSocket acceptText() {
6776
return WebSocket.Text.accept(request -> Flow.fromSinkAndSource(Sink.ignore(), emptySource()));
6877
}
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
+62-6Lines changed: 62 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -127,16 +127,44 @@ trait WebSocketCompressionSpec extends WebSocketSpecMethods {
127127

128128
"not negotiate compression when websocket compression is disabled" in {
129129
withServer(
130-
app => WebSocket.accept[String, String] { req => Flow.fromSinkAndSource(Sink.ignore, Source.maybe[String]) },
130+
app =>
131+
WebSocket.accept[String, String] { req =>
132+
Flow.fromSinkAndSource(Sink.ignore, Source.single("plain server message"))
133+
},
131134
Map("play.server.websocket.compression.enabled" -> false)
132135
) { (app, port) =>
133136
import app.materializer
134-
val (_, headers) = runWebSocket(
137+
val (frames, headers) = runWebSocket(
135138
port,
136-
{ flow =>
137-
Source.empty[ExtendedMessage].via(flow).runWith(Sink.ignore)
138-
Future.successful(())
139-
},
139+
{ flow => Source.maybe[ExtendedMessage].via(flow).runWith(consumeFrames) },
140+
subprotocol = None,
141+
handleConnect = c => c,
142+
compressionMode = CompressionMode.RequestOnly()
143+
)
144+
145+
headers.collectFirst {
146+
case (name, value) if name.equalsIgnoreCase("Sec-WebSocket-Extensions") => value
147+
} must beNone
148+
149+
frames.collectFirst {
150+
case SimpleMessage(TextMessage(data), true) => data
151+
} must beSome("plain server message")
152+
}
153+
}
154+
155+
"not negotiate compression when compression is disabled for the accepted WebSocket" in {
156+
withServer(app =>
157+
WebSocket.acceptWithOptions[String, String] { req =>
158+
WebSocket.Accepted(
159+
Flow.fromSinkAndSource(Sink.ignore, Source.single("plain server message")),
160+
compressionEnabled = false
161+
)
162+
}
163+
) { (app, port) =>
164+
import app.materializer
165+
val (frames, headers) = runWebSocket(
166+
port,
167+
{ flow => Source.maybe[ExtendedMessage].via(flow).runWith(consumeFrames) },
140168
subprotocol = None,
141169
handleConnect = c => c,
142170
compressionMode = CompressionMode.RequestOnly()
@@ -145,6 +173,10 @@ trait WebSocketCompressionSpec extends WebSocketSpecMethods {
145173
headers.collectFirst {
146174
case (name, value) if name.equalsIgnoreCase("Sec-WebSocket-Extensions") => value
147175
} must beNone
176+
177+
frames.collectFirst {
178+
case SimpleMessage(TextMessage(data), true) => data
179+
} must beSome("plain server message")
148180
}
149181
}
150182

@@ -853,6 +885,30 @@ trait WebSocketSpec
853885
}
854886
}
855887

888+
"allow selecting a subprotocol while disabling compression" in {
889+
withServer(_ => WebSocketSpecJavaActions.selectSubprotocolWithoutCompression()) { (app, port) =>
890+
import app.materializer
891+
val (frames, headers) = runWebSocket(
892+
port,
893+
{ flow => Source.maybe[ExtendedMessage].via(flow).runWith(consumeFrames) },
894+
Some("graphql-ws, graphql-transport-ws"),
895+
c => c,
896+
CompressionMode.RequestOnly()
897+
)
898+
899+
(headers
900+
.map { case (key, value) => (key.toLowerCase, value) }
901+
.collect { case ("sec-websocket-protocol", selectedProtocol) => selectedProtocol }
902+
.head must be).equalTo("graphql-transport-ws")
903+
headers.collectFirst {
904+
case (name, value) if name.equalsIgnoreCase("Sec-WebSocket-Extensions") => value
905+
} must beNone
906+
frames.collectFirst {
907+
case SimpleMessage(TextMessage(data), true) => data
908+
} must beSome("plain server message")
909+
}
910+
}
911+
856912
"close a text websocket when a binary frame is received" in {
857913
withServer(_ => WebSocketSpecJavaActions.acceptText()) { (app, port) =>
858914
import app.materializer
Collapse file

‎core/play/src/main/java/play/mvc/WebSocket.java‎

Copy file name to clipboardExpand all lines: core/play/src/main/java/play/mvc/WebSocket.java
+27-2Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -157,27 +157,50 @@ public static <In, Out> MappedWebSocketAcceptor<In, Out> json(Class<In> in) {
157157
public static class Accepted<In, Out> {
158158
private final Flow<In, Out, ?> flow;
159159
private final Optional<String> subprotocol;
160+
private final boolean compressionEnabled;
160161

161-
public Accepted(Flow<In, Out, ?> flow, Optional<String> subprotocol) {
162+
public Accepted(
163+
Flow<In, Out, ?> flow, Optional<String> subprotocol, boolean compressionEnabled) {
162164
this.flow = flow;
163165
this.subprotocol = subprotocol;
166+
this.compressionEnabled = compressionEnabled;
167+
}
168+
169+
public Accepted(Flow<In, Out, ?> flow, Optional<String> subprotocol) {
170+
this(flow, subprotocol, true);
164171
}
165172

166173
public Accepted(Flow<In, Out, ?> flow, String subprotocol) {
167174
this(flow, Optional.of(subprotocol));
168175
}
169176

177+
public Accepted(Flow<In, Out, ?> flow, String subprotocol, boolean compressionEnabled) {
178+
this(flow, Optional.of(subprotocol), compressionEnabled);
179+
}
180+
170181
public Accepted(Flow<In, Out, ?> flow) {
171182
this(flow, Optional.empty());
172183
}
173184

185+
public Accepted(Flow<In, Out, ?> flow, boolean compressionEnabled) {
186+
this(flow, Optional.empty(), compressionEnabled);
187+
}
188+
174189
public Flow<In, Out, ?> flow() {
175190
return flow;
176191
}
177192

178193
public Optional<String> subprotocol() {
179194
return subprotocol;
180195
}
196+
197+
/**
198+
* Returns whether this accepted WebSocket may negotiate compression when compression is enabled
199+
* in the server configuration. Returning {@code true} does not enable compression globally.
200+
*/
201+
public boolean compressionEnabled() {
202+
return compressionEnabled;
203+
}
181204
}
182205

183206
/**
@@ -317,7 +340,9 @@ public CompletionStage<F.Either<Result, Accepted<Message, Message>>> applyWithOp
317340
Flow.<Message>create().collect(inMapper),
318341
play.api.libs.streams.PekkoStreams.onlyFirstCanFinishMerge(2),
319342
accepted.flow().map(outMapper::apply));
320-
return F.Either.Right(new Accepted<>(flow, accepted.subprotocol()));
343+
return F.Either.Right(
344+
new Accepted<>(
345+
flow, accepted.subprotocol(), accepted.compressionEnabled()));
321346
}
322347
});
323348
}
Collapse file

‎core/play/src/main/scala/play/api/mvc/WebSocket.scala‎

Copy file name to clipboardExpand all lines: core/play/src/main/scala/play/api/mvc/WebSocket.scala
+12-2Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,14 @@ object WebSocket {
6565
*
6666
* @param flow the flow that handles WebSocket messages
6767
* @param subprotocol the WebSocket subprotocol selected by the application, if any
68+
* @param compressionEnabled whether this accepted WebSocket may negotiate compression when compression is enabled in
69+
* the server configuration; setting this to `true` does not enable compression globally
6870
*/
69-
case class Accepted[In, Out](flow: Flow[In, Out, ?], subprotocol: Option[String] = None)
71+
case class Accepted[In, Out](
72+
flow: Flow[In, Out, ?],
73+
subprotocol: Option[String] = None,
74+
compressionEnabled: Boolean = true
75+
)
7076

7177
/**
7278
* Transforms WebSocket message flows into message flows of another type.
@@ -243,7 +249,11 @@ object WebSocket {
243249

244250
override def applyWithOptions(request: RequestHeader): Future[Either[Result, Accepted[Message, Message]]] = {
245251
f(request).map(_.map { accepted =>
246-
Accepted(closeOnException(transformer.transform(accepted.flow)), accepted.subprotocol)
252+
Accepted(
253+
closeOnException(transformer.transform(accepted.flow)),
254+
accepted.subprotocol,
255+
accepted.compressionEnabled
256+
)
247257
})
248258
}
249259
}
Collapse file

‎core/play/src/main/scala/play/core/routing/HandlerInvoker.scala‎

Copy file name to clipboardExpand all lines: core/play/src/main/scala/play/core/routing/HandlerInvoker.scala
+2-1Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,8 @@ object HandlerInvokerFactory {
218218
case close: JMessage.Close =>
219219
CloseMessage(close.code.toScala.asInstanceOf[Option[Int]], close.reason)
220220
},
221-
accepted.subprotocol().toScala
221+
accepted.subprotocol().toScala,
222+
accepted.compressionEnabled()
222223
)
223224
)
224225
}
Collapse file

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

Copy file name to clipboardExpand all lines: documentation/manual/releases/release31/Highlights31.md
+2Lines changed: 2 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ play.server.websocket.compression.enabled = false
2424

2525
Common tuning options are available under `play.server.websocket.compression`, including the compression level, preferred client window size, context-takeover behavior, and the decompression allocation limit. By default, the allocation limit follows `play.server.websocket.frame.maxLength`. The Netty backend also exposes Netty-specific settings under `play.server.netty.websocket.compression.perMessageDeflate`, including `allowServerWindowSize`, `serverWindowSize`, and `memLevel`.
2626

27+
Applications can also keep compression enabled globally and disable it for a single accepted WebSocket by returning `WebSocket.Accepted` with `compressionEnabled = false`.
28+
2729
For more details, see the [[Scala WebSocket documentation|ScalaWebSockets#Configuring-WebSocket-compression]] and [[Java WebSocket documentation|JavaWebSockets#Configuring-WebSocket-compression]].
2830

2931
### WebSocket Subprotocol Selection
Collapse file

‎documentation/manual/working/javaGuide/main/async/JavaWebSockets.md‎

Copy file name to clipboardExpand all lines: documentation/manual/working/javaGuide/main/async/JavaWebSockets.md
+2Lines changed: 2 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,8 @@ play.server.websocket.compression.enabled = false
132132

133133
Common compression settings are available under `play.server.websocket.compression`. These settings include the compression level, the preferred client window size, context-takeover behavior, and the maximum decompression allocation. By default, `play.server.websocket.compression.maxAllocation` uses `play.server.websocket.frame.maxLength`, so the same limit applies to decompressed WebSocket messages. The Netty backend also has Netty-specific settings under `play.server.netty.websocket.compression.perMessageDeflate`, including `allowServerWindowSize`, `serverWindowSize`, and `memLevel`.
134134

135+
Applications can also disable compression for a single accepted WebSocket by returning `new WebSocket.Accepted<>(flow, false)` from `acceptWithOptions` or `acceptOrResultWithOptions`. This lets an application keep compression enabled globally but decline it for endpoints that carry sensitive data or are expected to exchange already-compressed messages.
136+
135137
> **Note:** WebSocket compression can increase CPU and memory usage. If messages include secrets alongside attacker-controlled data, consider whether compression is appropriate for that endpoint. Under the `play.server.websocket` config parent, the default context-takeover settings are `compression.perMessageDeflate.allowServerNoContext = false` and `compression.perMessageDeflate.preferredClientNoContext = false`. For a more conservative setup, set them to `true` so the server may accept `server_no_context_takeover` when the client requests it, and so the server requests `client_no_context_takeover` when the client supports it.
136138
137139
## Configuring keep-alive Frames
Collapse file

‎documentation/manual/working/scalaGuide/main/async/ScalaWebSockets.md‎

Copy file name to clipboardExpand all lines: documentation/manual/working/scalaGuide/main/async/ScalaWebSockets.md
+2Lines changed: 2 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,8 @@ play.server.websocket.compression.enabled = false
134134

135135
Common compression settings are available under `play.server.websocket.compression`. These settings include the compression level, the preferred client window size, context-takeover behavior, and the maximum decompression allocation. By default, `play.server.websocket.compression.maxAllocation` uses `play.server.websocket.frame.maxLength`, so the same limit applies to decompressed WebSocket messages. The Netty backend also has Netty-specific settings under `play.server.netty.websocket.compression.perMessageDeflate`, including `allowServerWindowSize`, `serverWindowSize`, and `memLevel`.
136136

137+
Applications can also disable compression for a single accepted WebSocket by returning `WebSocket.Accepted` with `compressionEnabled = false` from `acceptWithOptions` or `acceptOrResultWithOptions`. This lets an application keep compression enabled globally but decline it for endpoints that carry sensitive data or are expected to exchange already-compressed messages.
138+
137139
> **Note:** WebSocket compression can increase CPU and memory usage. If messages include secrets alongside attacker-controlled data, consider whether compression is appropriate for that endpoint. Under the `play.server.websocket` config parent, the default context-takeover settings are `compression.perMessageDeflate.allowServerNoContext = false` and `compression.perMessageDeflate.preferredClientNoContext = false`. For a more conservative setup, set them to `true` so the server may accept `server_no_context_takeover` when the client requests it, and so the server requests `client_no_context_takeover` when the client supports it.
138140
139141
## Configuring keep-alive Frames
Collapse file

‎transport/server/play-netty-server/src/main/scala/play/core/server/NettyServer.scala‎

Copy file name to clipboardExpand all lines: transport/server/play-netty-server/src/main/scala/play/core/server/NettyServer.scala
+7-1Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,13 @@ class NettyServer(
312312
nettyPerMessageDeflateConfig.get[Int]("memLevel"),
313313
maxAllocation
314314
)
315-
)
315+
) {
316+
protected override def isExtensionNegotiationEnabled(
317+
ctx: ChannelHandlerContext,
318+
response: HttpResponse
319+
): Boolean =
320+
Option(ctx.channel().attr(PlayWebSocketCompression.Enabled).get()).forall(_.booleanValue())
321+
}
316322
)
317323
}
318324
}
Collapse file

‎transport/server/play-netty-server/src/main/scala/play/core/server/netty/PlayRequestHandler.scala‎

Copy file name to clipboardExpand all lines: transport/server/play-netty-server/src/main/scala/play/core/server/netty/PlayRequestHandler.scala
+13-1Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import io.netty.channel._
1818
import io.netty.handler.codec.http._
1919
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory
2020
import io.netty.handler.codec.TooLongFrameException
21+
import io.netty.util.AttributeKey
2122
import org.apache.pekko.stream.Materializer
2223
import org.apache.pekko.util.ByteString
2324
import org.playframework.netty.http.DefaultWebSocketHttpResponse
@@ -39,6 +40,11 @@ private object PlayRequestHandler {
3940
private val logger: Logger = Logger(classOf[PlayRequestHandler])
4041
}
4142

43+
private[server] object PlayWebSocketCompression {
44+
val Enabled: AttributeKey[java.lang.Boolean] =
45+
AttributeKey.valueOf[java.lang.Boolean]("play.websocket.compressionEnabled")
46+
}
47+
4248
private[play] class PlayRequestHandler(
4349
val server: NettyServer,
4450
val serverHeader: Option[String],
@@ -217,8 +223,14 @@ private[play] class PlayRequestHandler(
217223
)
218224
val factory =
219225
new WebSocketServerHandshakerFactory(wsUrl, accepted.subprotocol.orNull, true, wsBufferLimit)
226+
channel.attr(PlayWebSocketCompression.Enabled).set(java.lang.Boolean.valueOf(accepted.compressionEnabled))
220227
Future.successful(
221-
new DefaultWebSocketHttpResponse(request.protocolVersion(), HttpResponseStatus.OK, processor, factory)
228+
new DefaultWebSocketHttpResponse(
229+
request.protocolVersion(),
230+
HttpResponseStatus.OK,
231+
processor,
232+
factory
233+
)
222234
)
223235
}
224236
.recoverWith {

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.