Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions docs/src/main/paradox/server-side/websocket-support.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)].
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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...
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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 }
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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")
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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))
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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))
}
Original file line number Diff line number Diff line change
@@ -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<Object, TextMessage, NotUsed> handler =
Flow.fromSinkAndSource(Sink.<Object>ignore(), Source.single(TextMessage.create("ready")));
HttpResponse response =
selectProtocol
? upgrade.handleMessagesWith(handler, "chat")
: upgrade.handleMessagesWith(handler);
return WebSocket.withCompletionClose(response, 4200, "finished");
}
}
Loading