diff --git a/docs/src/main/paradox/server-side/websocket-support.md b/docs/src/main/paradox/server-side/websocket-support.md index ea2704c8b6..8949aecad6 100644 --- a/docs/src/main/paradox/server-side/websocket-support.md +++ b/docs/src/main/paradox/server-side/websocket-support.md @@ -119,6 +119,45 @@ which allows to pass an output-generating @apidoc[Source[Message, \_]] and an in Note that a handler is required to consume the data stream of each message to make place for new messages. Otherwise, subsequent messages may be stuck and message traffic in this direction will stall. +### Closing after the last outgoing message + +When the server's outgoing stream finishes normally, Pekko HTTP sends a Close frame with code `1000` and an empty +reason. To tell the peer why a finite stream finished, set the code and reason on the upgrade **response**: + +Scala +: ```scala + val response = upgrade.handleMessages(handler) + WebSocketUpgrade.withCompletionClose(response, 1001, "Server shutting down") + ``` + +Java +: ```java + HttpResponse response = upgrade.handleMessagesWith(handler); + return WebSocket.withCompletionClose(response, 1001, "Server shutting down"); + ``` + +Use a status code permitted for servers and a reason of at most 123 UTF-8 bytes. Because the handler is chosen first, +this works with any subprotocol or compression policy. It does not override a peer-initiated close or a handler failure. + +When using @ref[handleWebSocketMessages](../routing-dsl/directives/websocket-directives/handleWebSocketMessages.md), +wrap the directive with @ref[mapResponse](../routing-dsl/directives/basic-directives/mapResponse.md) to set the same policy: + +Scala +: ```scala + val route = + mapResponse(response => WebSocketUpgrade.withCompletionClose(response, 1001, "Server shutting down")) { + handleWebSocketMessages(handler) + } + ``` + +Java +: ```java + Route route = + mapResponse( + response -> WebSocket.withCompletionClose(response, 1001, "Server shutting down"), + () -> handleWebSocketMessages(handler)); + ``` + ### Example Let's look at an @scala[@github[example](/docs/src/test/scala/docs/http/scaladsl/server/WebSocketExampleSpec.scala)]@java[@github[example](/docs/src/test/java/docs/http/javadsl/server/WebSocketCoreExample.java)]. diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/rendering/HttpResponseRendererFactory.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/rendering/HttpResponseRendererFactory.scala index dfe4f2bddd..866f120dfa 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/rendering/HttpResponseRendererFactory.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/rendering/HttpResponseRendererFactory.scala @@ -245,7 +245,7 @@ private[http] class HttpResponseRendererFactory( else if (connHeader != null && connHeader.hasUpgrade) { r ~~ connHeader HttpHeader.fastFind(classOf[UpgradeToOtherProtocolResponseHeader], headers) match { - case OptionVal.Some(header) => closeMode = SwitchToOtherProtocol(header.handler) + case OptionVal.Some(header) => closeMode = SwitchToOtherProtocol(header.handlerFor(ctx.response)) case _ => // nothing to do here... } } diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/server/UpgradeToOtherProtocolResponseHeader.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/server/UpgradeToOtherProtocolResponseHeader.scala index 59f156c828..7c56cc8280 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/server/UpgradeToOtherProtocolResponseHeader.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/server/UpgradeToOtherProtocolResponseHeader.scala @@ -15,7 +15,10 @@ package org.apache.pekko.http.impl.engine.server import org.apache.pekko import pekko.annotation.InternalApi +import pekko.http.impl.engine.ws.FrameOutHandler +import pekko.http.scaladsl.model.HttpResponse import pekko.http.scaladsl.model.headers.CustomHeader +import pekko.stream.Attributes import pekko.stream.scaladsl.Flow import pekko.util.ByteString @@ -24,7 +27,11 @@ import pekko.util.ByteString */ @InternalApi private[http] final case class UpgradeToOtherProtocolResponseHeader(handler: Flow[ByteString, ByteString, Any]) - extends InternalCustomHeader("UpgradeToOtherProtocolResponseHeader") + extends InternalCustomHeader("UpgradeToOtherProtocolResponseHeader") { + def handlerFor(response: HttpResponse): Flow[ByteString, ByteString, Any] = + response.attribute(FrameOutHandler.completionCloseKey).fold(handler)(close => + handler.addAttributes(Attributes(close))) +} /** * Internal API diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/ws/FrameOutHandler.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/ws/FrameOutHandler.scala index cfc2a70977..2af16131ae 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/ws/FrameOutHandler.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/ws/FrameOutHandler.scala @@ -13,6 +13,9 @@ package org.apache.pekko.http.impl.engine.ws +import java.nio.CharBuffer +import java.nio.charset.{ CharacterCodingException, StandardCharsets } + import scala.annotation.tailrec import scala.concurrent.duration.FiniteDuration @@ -21,6 +24,7 @@ import pekko.NotUsed import pekko.annotation.InternalApi import pekko.event.LoggingAdapter import pekko.http.impl.engine.ws.FrameHandler.{ UserHandlerErredOut, _ } +import pekko.http.scaladsl.model.AttributeKey import pekko.stream.scaladsl.Flow import pekko.stream.stage._ import pekko.stream.{ Attributes, FlowShape, Inlet, Outlet } @@ -87,7 +91,8 @@ private[http] class FrameOutHandler(serverSide: Boolean, _closeTimeout: FiniteDu push(out, closeFrame) case UserHandlerCompleted => setHandler(in, new WaitingForPeerCloseFrame) - push(out, FrameEvent.closeFrame(Protocol.CloseCodes.Regular)) + val frame = if (serverSide) inheritedAttributes.get[FrameOutHandler.CompletionClose].map(_.frame) else None + push(out, frame.getOrElse(FrameEvent.closeFrame(Protocol.CloseCodes.Regular))) case UserHandlerErredOut(e) => log.error(e, "Websocket handler failed with {}", e.getMessage) setHandler(in, new WaitingForPeerCloseFrame) @@ -207,6 +212,24 @@ private[http] class FrameOutHandler(serverSide: Boolean, _closeTimeout: FiniteDu private[http] object FrameOutHandler { type Input = AnyRef + final class CompletionClose(val frame: FrameStart) extends Attributes.Attribute + val completionCloseKey = AttributeKey[CompletionClose]("pekko.http.websocket.completion-close") + + def completionClose(code: Int, reason: String): CompletionClose = { + import Protocol.CloseCodes + require(CloseCodes.isValid(code) && code != CloseCodes.ClientRejectsExtension, + s"Invalid server WebSocket close status: $code") + require(reason != null && reason.length <= 123, "WebSocket Close reason must be at most 123 UTF-8 bytes") + val encodedLength = + try StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(reason)).remaining() + catch { + case _: CharacterCodingException => + throw new IllegalArgumentException("WebSocket Close reason must be valid UTF-8") + } + require(encodedLength <= 123, "WebSocket Close reason must be at most 123 UTF-8 bytes") + new CompletionClose(FrameEvent.closeFrame(code, reason)) + } + def create(serverSide: Boolean, closeTimeout: FiniteDuration, log: LoggingAdapter): Flow[Input, FrameStart, NotUsed] = Flow[Input].via(new FrameOutHandler(serverSide, closeTimeout, log)).named("frameOutHandler") } diff --git a/http-core/src/main/scala/org/apache/pekko/http/javadsl/model/ws/WebSocket.scala b/http-core/src/main/scala/org/apache/pekko/http/javadsl/model/ws/WebSocket.scala index b56fbe4b45..23ef5fba47 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/javadsl/model/ws/WebSocket.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/javadsl/model/ws/WebSocket.scala @@ -14,6 +14,7 @@ package org.apache.pekko.http.javadsl.model.ws import org.apache.pekko +import pekko.http.impl.engine.ws.FrameOutHandler import pekko.http.impl.util.JavaMapping.Implicits._ import pekko.http.javadsl.model._ import pekko.stream.javadsl.Flow @@ -30,4 +31,17 @@ object WebSocket { case Some(header) => header.handleMessagesWith(handler) case None => HttpResponse.create().withStatus(StatusCodes.BAD_REQUEST).withEntity("Expected WebSocket request") } + + /** + * Sets the Close status and reason sent by a server WebSocket message handler when its outgoing stream + * completes normally before the peer initiates closing. Apply this to the response returned by any message + * handler overload; it does not change the negotiated subprotocol, compression, peer-initiated closes or failures. + * Other responses are rendered normally. The status must be permitted for servers by RFC 6455, and the reason + * must encode to at most 123 UTF-8 bytes. + * + * @since 2.1.0 + */ + def withCompletionClose(response: HttpResponse, closeCode: Int, closeReason: String): HttpResponse = + response.addAttribute(FrameOutHandler.completionCloseKey, + FrameOutHandler.completionClose(closeCode, closeReason)) } diff --git a/http-core/src/main/scala/org/apache/pekko/http/scaladsl/model/ws/WebSocketUpgrade.scala b/http-core/src/main/scala/org/apache/pekko/http/scaladsl/model/ws/WebSocketUpgrade.scala index 65bea06c53..0ef84db402 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/scaladsl/model/ws/WebSocketUpgrade.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/scaladsl/model/ws/WebSocketUpgrade.scala @@ -18,6 +18,7 @@ import java.util.function.{ Predicate => JPredicate } import org.apache.pekko import pekko.NotUsed +import pekko.http.impl.engine.ws.FrameOutHandler import pekko.http.impl.util.JavaMapping import pekko.http.javadsl.{ model => jm } import pekko.http.scaladsl.model.HttpResponse @@ -327,3 +328,19 @@ trait WebSocketUpgrade extends jm.ws.WebSocketUpgrade { outSource.asInstanceOf[Graph[SourceShape[jm.ws.Message], Any]])(scaladsl.Keep.none): Graph[FlowShape[ jm.ws.Message, jm.ws.Message], NotUsed]) } + +object WebSocketUpgrade { + + /** + * Sets the Close status and reason sent by a server WebSocket message handler when its outgoing stream + * completes normally before the peer initiates closing. Apply this to the response returned by any message + * handler overload; it does not change the negotiated subprotocol, compression, peer-initiated closes or failures. + * Other responses are rendered normally. The status must be permitted for servers by RFC 6455, and the reason + * must encode to at most 123 UTF-8 bytes. + * + * @since 2.1.0 + */ + def withCompletionClose(response: HttpResponse, closeCode: Int, closeReason: String): HttpResponse = + response.addAttribute(FrameOutHandler.completionCloseKey, + FrameOutHandler.completionClose(closeCode, closeReason)) +} diff --git a/http-core/src/test/java/org/apache/pekko/http/impl/engine/ws/WebSocketCompletionCloseJavaApi.java b/http-core/src/test/java/org/apache/pekko/http/impl/engine/ws/WebSocketCompletionCloseJavaApi.java new file mode 100644 index 0000000000..33077aa0d2 --- /dev/null +++ b/http-core/src/test/java/org/apache/pekko/http/impl/engine/ws/WebSocketCompletionCloseJavaApi.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.pekko.http.impl.engine.ws; + +import org.apache.pekko.NotUsed; +import org.apache.pekko.http.javadsl.model.HttpResponse; +import org.apache.pekko.http.javadsl.model.ws.TextMessage; +import org.apache.pekko.http.javadsl.model.ws.WebSocket; +import org.apache.pekko.http.javadsl.model.ws.WebSocketUpgrade; +import org.apache.pekko.stream.javadsl.Flow; +import org.apache.pekko.stream.javadsl.Sink; +import org.apache.pekko.stream.javadsl.Source; + +public final class WebSocketCompletionCloseJavaApi { + private WebSocketCompletionCloseJavaApi() {} + + public static HttpResponse upgrade(WebSocketUpgrade upgrade, boolean selectProtocol) { + Flow handler = + Flow.fromSinkAndSource(Sink.ignore(), Source.single(TextMessage.create("ready"))); + HttpResponse response = + selectProtocol + ? upgrade.handleMessagesWith(handler, "chat") + : upgrade.handleMessagesWith(handler); + return WebSocket.withCompletionClose(response, 4200, "finished"); + } +} diff --git a/http-core/src/test/scala/org/apache/pekko/http/impl/engine/ws/WebSocketCompletionCloseSpec.scala b/http-core/src/test/scala/org/apache/pekko/http/impl/engine/ws/WebSocketCompletionCloseSpec.scala new file mode 100644 index 0000000000..7964b860fc --- /dev/null +++ b/http-core/src/test/scala/org/apache/pekko/http/impl/engine/ws/WebSocketCompletionCloseSpec.scala @@ -0,0 +1,186 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.pekko.http.impl.engine.ws + +import java.util.concurrent.atomic.AtomicInteger + +import scala.concurrent.duration._ + +import org.apache.pekko +import pekko.event.NoLogging +import pekko.http.impl.engine.rendering.{ + DateHeaderRendering, + HttpResponseRendererFactory, + ResponseRenderingContext, + ResponseRenderingOutput +} +import pekko.http.impl.engine.ws.FrameHandler.{ PeerClosed, UserHandlerCompleted, UserHandlerErredOut } +import pekko.http.impl.util.{ AddFutureAwaitResult, PekkoSpecWithMaterializer } +import pekko.http.scaladsl.model.headers.{ + Date, + WebSocketExtension, + `Sec-WebSocket-Extensions`, + `Sec-WebSocket-Key`, + `Sec-WebSocket-Protocol` +} +import pekko.http.scaladsl.model.ws.{ Message, TextMessage, WebSocketUpgrade } +import pekko.http.scaladsl.model.{ DateTime, HttpResponse, StatusCodes } +import pekko.http.scaladsl.settings.ServerSettings +import pekko.stream.Attributes +import pekko.stream.scaladsl.{ Flow, Keep, Sink, Source } +import pekko.stream.testkit.scaladsl.{ TestSink, TestSource } +import pekko.testkit._ + +class WebSocketCompletionCloseSpec extends PekkoSpecWithMaterializer { + private def upgrade(offerCompression: Boolean = false): WebSocketUpgrade = + Handshake.Server.websocketUpgrade( + List( + Handshake.UpgradeHeader, + Handshake.ConnectionUpgradeHeader, + Handshake.SecWebSocketVersionHeader, + `Sec-WebSocket-Key`("dGhlIHNhbXBsZSBub25jZQ=="), + `Sec-WebSocket-Protocol`(Seq("chat"))) ++ + (if (offerCompression) List(`Sec-WebSocket-Extensions`(Seq(WebSocketExtension("permessage-deflate")))) else Nil), + hostHeaderPresent = true, + ServerSettings(system).websocketSettings, + NoLogging).get + + private def handler = + Flow.fromSinkAndSource[Message, Message](Sink.ignore, Source.single(TextMessage("ready"))) + + private def render(response: HttpResponse): ResponseRenderingOutput = + Source.single(ResponseRenderingContext(response)) + .via(new HttpResponseRendererFactory(None, 256, NoLogging, DateHeaderRendering()).renderer) + .runWith(Sink.head) + .awaitResult(3.seconds.dilated) + + private def assertClose(response: HttpResponse, code: Int, reason: String): Unit = { + response.status shouldEqual StatusCodes.SwitchingProtocols + val nativeHandler = render(response) match { + case ResponseRenderingOutput.SwitchToOtherProtocol(_, upgraded) => upgraded + case _ => fail("Expected a WebSocket upgrade") + } + val frames = Source.maybe[FrameEvent].via(WebSocket.framing.reversed.join(nativeHandler)) + .map { + case frame: FrameStart => frame + case _ => fail("Expected a complete frame") + } + .take(2) + .runWith(Sink.seq) + .awaitResult(3.seconds.dilated) + frames.map(_.header.opcode) shouldEqual Seq(Protocol.Opcode.Text, Protocol.Opcode.Close) + frames.head.header.rsv1 shouldEqual false + frames.head.data.utf8String shouldEqual "ready" + FrameEventParser.parseCloseCode(frames.last.data) shouldEqual Some((code, reason)) + } + + "Server WebSocket completion close" should { + "keep normal closure by default" in { + assertClose(upgrade().handleMessages(handler), Protocol.CloseCodes.Regular, "") + } + + "send the selected close after the final application message" in { + val reason = "Red\u00e9marrage" + assertClose( + WebSocketUpgrade.withCompletionClose( + upgrade().handleMessages(handler), Protocol.CloseCodes.ServiceRestart, reason), + Protocol.CloseCodes.ServiceRestart, + reason) + } + + "preserve an explicit compression opt-out" in { + val response = WebSocketUpgrade.withCompletionClose( + upgrade(offerCompression = true).handleMessages(handler, None, compressionEnabled = false), 4200, "done") + response.header[`Sec-WebSocket-Extensions`] shouldBe empty + assertClose(response, 4200, "done") + } + + "preserve the per-message compression predicate and the selected subprotocol" in { + val seen = new AtomicInteger + val response = WebSocketUpgrade.withCompletionClose( + upgrade(offerCompression = true).handleMessages(handler, Some("chat"), + (_: Message) => { + seen.incrementAndGet() + false + }), 4200, "done") + response.header[`Sec-WebSocket-Extensions`].get.extensions.map(_.name) shouldEqual Seq("permessage-deflate") + response.header[`Sec-WebSocket-Protocol`].get.protocols shouldEqual Seq("chat") + assertClose(response, 4200, "done") + seen.get() shouldEqual 1 + } + + "leave a response that declines the upgrade unchanged on the wire" in { + val ordinary = HttpResponse(StatusCodes.NotFound).addHeader(Date(DateTime(0L))) + val decorated = WebSocketUpgrade.withCompletionClose(ordinary, 4200, "done") + render(decorated) shouldEqual render(ordinary) + } + + for (selectProtocol <- List(false, true)) { + s"expose the same behavior to Java (subprotocol selected = $selectProtocol)" in { + val response = WebSocketCompletionCloseJavaApi.upgrade(upgrade(), selectProtocol).asInstanceOf[HttpResponse] + response.header[`Sec-WebSocket-Protocol`].map(_.protocols) shouldEqual ( + if (selectProtocol) Some(Seq("chat")) else None) + assertClose(response, 4200, "finished") + } + } + + "preserve the peer-initiated close and handler-failure paths" in { + val ownClose = FrameOutHandler.completionClose(Protocol.CloseCodes.ServiceRestart, "restarting") + def createProbes() = + TestSource[FrameOutHandler.Input]() + .via(FrameOutHandler.create(serverSide = true, 5.seconds.dilated, NoLogging).addAttributes( + Attributes(ownClose))) + .toMat(TestSink[FrameStart]())(Keep.both) + .run() + + val (peerFirstIn, peerFirstOut) = createProbes() + peerFirstOut.request(1) + peerFirstIn.sendNext(PeerClosed(Some(Protocol.CloseCodes.GoingAway), "away")) + peerFirstIn.sendNext(UserHandlerCompleted) + FrameEventParser.parseCloseCode(peerFirstOut.expectNext().data) shouldEqual ( + Some((Protocol.CloseCodes.GoingAway, "away"))) + peerFirstOut.expectComplete() + + val (failedIn, failedOut) = createProbes() + failedOut.request(1) + failedIn.sendNext(UserHandlerErredOut(new IllegalStateException("test handler failure"))) + FrameEventParser.parseCloseCode(failedOut.expectNext().data) shouldEqual ( + Some((Protocol.CloseCodes.UnexpectedCondition, "internal error"))) + failedOut.request(1) + failedIn.sendNext(PeerClosed(Some(Protocol.CloseCodes.Regular), "")) + failedOut.expectComplete() + } + + "reject an invalid server status or reason when the application configures it" in { + val response = upgrade().handleMessages(handler) + for ((code, reason) <- List( + (Protocol.CloseCodes.ClientRejectsExtension, ""), + (4200, "\u00e9" * 62), + (4200, "\ud800"))) { + intercept[IllegalArgumentException](WebSocketUpgrade.withCompletionClose(response, code, reason)) + } + } + + "accept a reason at the UTF-8 byte limit" in { + val reason = "\u00e9" * 61 + "x" + assertClose(WebSocketUpgrade.withCompletionClose(upgrade().handleMessages(handler), Protocol.CloseCodes.GoingAway, + reason), + Protocol.CloseCodes.GoingAway, reason) + } + } +}