diff --git a/docs/src/main/paradox/client-side/http2.md b/docs/src/main/paradox/client-side/http2.md index c003a1748..844b9c491 100644 --- a/docs/src/main/paradox/client-side/http2.md +++ b/docs/src/main/paradox/client-side/http2.md @@ -66,13 +66,6 @@ Java The Apache Pekko HTTP client doesn't support HTTP/1 to HTTP/2 negotiation over plaintext using the `Upgrade` mechanism. -If the HTTP/2 connection reaches end-of-input normally while a delivered response entity is still open, consuming -that entity fails with a connection-aborted `IllegalStateException`. Receiving response headers does not guarantee -that the full response body is available to the application. This also applies when the peer has already ended the -response stream but some of its data is still buffered and has not reached the application when the connection closes. - -This behavior applies only to HTTP/2 client response entities, not to HTTP/2 server request entities. - ## Limiting managed persistent connection lifetime Managed persistent HTTP/2 clients can periodically retire long-lived connections so that later requests establish @@ -102,6 +95,36 @@ The default maximum age is `infinite`, which disables age-based retirement. The programmatically with `Http2ClientSettings.withPersistentConnectionMaxAge` and `Http2ClientSettings.withPersistentConnectionMaxAgeJitter`. +## Peer-initiated connection retirement + +When the server sends a graceful `GOAWAY`, the HTTP/2 client stops opening streams on that connection. +Requests already accepted by the server can finish their uploads and receive their responses. A later +`GOAWAY` can reduce the set of accepted streams. See [RFC 9113, section 6.8](https://www.rfc-editor.org/rfc/rfc9113.html#section-6.8). + +Once the accepted responses have finished on the wire, the managed client can send new requests on a replacement +connection, even while a previously accepted upload finishes on the old connection. It does not replay requests +already dispatched on the old one: a request left without a response receives the usual +`502 Bad Gateway`. You can still consume a fully received response body after the old connection closes. +The client's `completion-timeout` bounds draining from the first graceful `GOAWAY`, unless an earlier +connection completion deadline applies. + +## Consuming responses after the peer closes + +When the client observes clean transport read EOF after a complete HTTP/2 response has arrived, it can still +deliver the already-received body and trailers. Buffered responses are retained for at most the HTTP/2 client +`completion-timeout`, or until an earlier connection completion deadline expires. Consume or discard each +response entity as usual. + +For TLS, `pekko.http.client.stream-cancellation-delay` (100 milliseconds by default) gives read completion +time to reach the HTTP/2 client before the TLS layer's cancellation of the write side. If write cancellation +arrives first, such as when the delay is disabled, buffered entities can still fail instead of draining. + +A clean read close does not make a response complete on its own: a streamed response body whose HTTP/2 stream +has not ended fails with a connection-aborted `IllegalStateException`. These rules apply to client response +entities, not server request entities. If dispatched requests never received a final response, a direct client reports failure +after delivering already-received responses; a managed client uses its normal disconnect handling and does not +replay dispatched requests. + ## Request-response ordering For HTTP/2 connections the responses are not guaranteed to arrive in the same order that the requests were emitted to diff --git a/docs/src/main/paradox/server-side/http2.md b/docs/src/main/paradox/server-side/http2.md index f38e26e60..7a566d63d 100644 --- a/docs/src/main/paradox/server-side/http2.md +++ b/docs/src/main/paradox/server-side/http2.md @@ -132,6 +132,11 @@ connection is closed even if they have not completed: pekko.http.server.http2.max-connection-age-grace = 30s ``` +When a client sends a graceful HTTP/2 `GOAWAY`, the server sends its own `GOAWAY` with the last client stream it accepted. +Requests already accepted can finish their uploads and receive their complete responses before the connection closes. +The same `max-connection-age-grace` bounds this drain, even when `max-connection-age` is disabled. +A later peer `GOAWAY` does not restart a drain already in progress. + The default grace period is 30 seconds. Set it to `infinite` to wait for all requests in flight to complete, however long they take. diff --git a/http-core/src/main/resources/reference.conf b/http-core/src/main/resources/reference.conf index 6cd4bc716..702efd22c 100644 --- a/http-core/src/main/resources/reference.conf +++ b/http-core/src/main/resources/reference.conf @@ -381,10 +381,10 @@ pekko.http { # The value `infinite` disables this mechanism and is the default. max-connection-age = infinite - # The time that requests in flight are given to complete after a connection reached `max-connection-age` - # and the GOAWAY frame was sent. When the grace period expires, the connection is closed even if requests - # are still in flight. The value `infinite` disables the limit: the connection is closed only once all - # requests in flight have completed. + # The time that requests in flight are given to complete after a server begins draining an HTTP/2 + # connection at `max-connection-age` or after receiving a graceful GOAWAY from the client. When the + # grace period expires, the connection is closed even if requests are still in flight. The value + # `infinite` disables the limit: the connection is closed only once all requests in flight have completed. max-connection-age-grace = 30s # The jitter applied to `max-connection-age`, as a fraction of the configured value: with the default of @@ -713,6 +713,7 @@ pekko.http { # When gracefully closing the HTTP/2 client, await at most `completion-timeout` for in-flight # requests to complete. When the timeout expires, remaining in-flight requests are terminated. # This also bounds the drain of a connection retired after `persistent-connection-max-age`. + # After a peer read EOF, completed response bodies may be retained only within this bound. completion-timeout = 3s frame-type-throttle { diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2Demux.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2Demux.scala index 351e41a38..43a6fdd12 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2Demux.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2Demux.scala @@ -288,7 +288,7 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, with GenericOutletSupport with StageLogging with LogHelper with ServerTerminator { logic => - import Http2Demux.{ CompletionTimeout, MaxConnectionAge } + import Http2Demux.{ CompletionTimeout, MaxConnectionAge, ReadCompletionTimeout } def wrapTrailingHeaders(headers: ParsedHeadersFrame): Option[HttpEntity.ChunkStreamPart] = stage.wrapTrailingHeaders(headers) @@ -310,6 +310,14 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, private val terminationPromise = Promise[Http.HttpTerminated]() private var terminating: Boolean = false + private var peerLastStreamId = -1 // NO_ERROR retirement closes admission, not the transport. + private var peerDrainCheckPending = false + private var clientReadClosed = false // logical read drain; the physical transport may still be closing + private var closingClientStreams = false + private var unansweredAtRetirement = false + private var clientResponseAwaitingPull = false + override def isClientReadClosed: Boolean = clientReadClosed + override def isPeerRetiring: Boolean = peerLastStreamId >= 0 private var lastIdBeforeTermination: Int = 0 // when the forced close of a terminating connection is due, unset while no forced close is scheduled private var forcedCloseDeadline: OptionVal[Deadline] = OptionVal.None @@ -328,10 +336,10 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, lastIdBeforeTermination = lastStreamId() completeIfDone() } - scheduleForcedCloseIfEarlier(deadline) + if (!isClosed(frameOut)) scheduleForcedCloseIfEarlier(deadline) } private def scheduleForcedCloseIfEarlier(deadline: Duration): Unit = deadline match { - case deadline: FiniteDuration if !isClosed(frameOut) => + case deadline: FiniteDuration => val due = Deadline.now + deadline val earlier = forcedCloseDeadline match { case OptionVal.Some(scheduled) => due < scheduled @@ -344,7 +352,7 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, case _ => // no deadline, wait for open requests to complete } - def frameOutFinished(): Unit = { + def frameOutFinished(): Unit = if (!clientReadClosed) { // Fail the client response outlet before cleanup: closing the last stream can otherwise // complete it normally when the request input has already completed. if (!isServer && !isClosed(substreamOut)) @@ -410,16 +418,17 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, if (allow != allowReadingIncomingFrames) if (allow) { debug("Resume reading incoming frames") - if (!hasBeenPulled(frameIn)) pull(frameIn) + if (!clientReadClosed && !isClosed(frameIn) && !hasBeenPulled(frameIn)) pull(frameIn) } else debug("Suspended reading incoming frames") // can't retract pending pull but that's ok allowReadingIncomingFrames = allow } def pullFrameIn(): Unit = - if (allowReadingIncomingFrames && !hasBeenPulled(frameIn) && !isClosed(frameIn)) pull(frameIn) + if (!clientReadClosed && allowReadingIncomingFrames && !hasBeenPulled(frameIn) && !isClosed(frameIn)) + pull(frameIn) def tryPullSubStreams(): Unit = { - if (!hasBeenPulled(substreamIn) && !isClosed(substreamIn)) { + if (!clientReadClosed && !hasBeenPulled(substreamIn) && !isClosed(substreamIn)) { // While we don't support PUSH_PROMISE there's only capacity control on the client if (isServer) pull(substreamIn) else if (hasCapacityToCreateStreams) pull(substreamIn) @@ -430,14 +439,14 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, setHandler(frameIn, new InHandler { - override def onUpstreamFinish(): Unit = { - // Default stage completion completes open sub-sources before postStop can fail them. - if (!isServer) failOpenIncomingEntities() - super.onUpstreamFinish() - } + override def onUpstreamFinish(): Unit = + if (isServer) super.onUpstreamFinish() + else beginClientReadDrain() def onPush(): Unit = { val frame = grab(frameIn) + // A pending pull can still complete while a retired transport closes. + if (clientReadClosed) return frame match { case _: PingFrame => // handle later case _ => pingState.onDataFrameSeen() @@ -473,6 +482,27 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, // are enforced from the start of the connection so there's no need to invoke // `enforceSettings(initialLocalSettings)` + case GoAwayFrame(_, ErrorCode.NO_ERROR, _) if isServer => + // The client's last stream ID covers server-initiated streams (push is not supported). + // Use our own last accepted client stream ID to drain requests and close the connection. + if (!terminating) triggerTermination(maxConnectionAgeGrace) + + case GoAwayFrame(lastStreamId, errorCode, _) if !isServer => + if (errorCode == ErrorCode.NO_ERROR) { + val firstGoAway = !isPeerRetiring + if (firstGoAway) scheduleForcedCloseIfEarlier(completionTimeout) + val boundary = if (firstGoAway) lastStreamId else math.min(peerLastStreamId, lastStreamId) + peerLastStreamId = boundary + setKeepGoing(true) + if (!isClosed(substreamIn)) cancel(substreamIn, Http2Demux.RequestAdmissionClosed) + peerLastStreamId = multiplexer.retireClientRequests(boundary) + val rejected = rejectClientRequestsAfter(peerLastStreamId) + unansweredAtRetirement ||= rejected + } else { + failStage(new Http2Compliance.Http2ProtocolException(errorCode, "HTTP/2 peer sent GOAWAY")) + return + } + case PingFrame(true, data) => if (data != ConfigurablePing.Ping.data) { // We only ever push static data, responding with anything else is wrong @@ -487,10 +517,12 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, debug(s"Got unhandled event $e") // ignore unknown frames } + if (isPeerRetiring) completeIfDone() pullFrameIn() } override def onUpstreamFailure(ex: Throwable): Unit = { + if (clientReadClosed) return // the accepted response data is already owned by the drain ex match { case e: Http2Compliance.InvalidConnectionPreface => failStage(e) @@ -515,7 +547,25 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, // ----------------------------------------------------------------- // FIXME: What if user handler doesn't pull in new substreams? Should we reject them // after a while or buffer only a limited amount? - val bufferedSubStreamOutput = new BufferedOutlet[Http2SubStream](fromOutlet(substreamOut)) + val bufferedSubStreamOutput = new BufferedOutlet[Http2SubStream](fromOutlet(substreamOut)) { + override protected def doPush(subStream: Http2SubStream): Unit = { + if (!isServer) clientResponseAwaitingPull = true + super.doPush(subStream) + } + + override def onPull(): Unit = { + clientResponseAwaitingPull = false + super.onPull() + if (clientReadClosed || isPeerRetiring) completeIfDone() + } + + override def onDownstreamFinish(cause: Throwable): Unit = + if (!clientReadClosed) super.onDownstreamFinish(cause) + else { + buffer.clear() + completeIfDone() + } + } override def dispatchSubstream(initialHeaders: ParsedHeadersFrame, data: Either[ByteString, Source[Any, Any]], correlationAttributes: Map[AttributeKey[?], ?]): Unit = bufferedSubStreamOutput.push(Http2SubStream(initialHeaders, OptionVal.None, data, correlationAttributes)) @@ -524,7 +574,63 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, override def onAllStreamsClosed(): Unit = completeIfDone() override def onAllDataFlushed(): Unit = completeIfDone() + private def beginClientReadDrain(): Unit = if (!clientReadClosed) { + clientReadClosed = true + closingClientStreams = true + // The response stream and transport may end before a delivered entity has been consumed. + setKeepGoing(true) + cancelTimer(ConfigurablePing.Tick) + if (!isClosed(substreamIn)) cancel(substreamIn, Http2Demux.RequestAdmissionClosed) + // Retire the writer at the same time; retained response buffers no longer need to send frames. + if (!isClosed(frameOut)) complete(frameOut) + val unansweredAtEof = retainCompletedClientEntities() + unansweredAtRetirement ||= unansweredAtEof + closingClientStreams = false + scheduleOnce(ReadCompletionTimeout, completionTimeout) + completeIfDone() + } + + private def abortClientDrain(): Unit = { + if (!isClosed(substreamOut)) + bufferedSubStreamOutput.fail(Http2StreamHandling.ConnectionWasAbortedException) + shutdownStreamHandling() + completeStage() + } + + private def finishClientResponses(): Unit = + if (bufferedSubStreamOutput.buffer.isEmpty && !isClosed(substreamOut)) { + if (!unansweredAtRetirement) complete(substreamOut) + // Failing an outlet can overtake a just-pushed element; wait for the next pull or the drain deadline. + else if (!clientResponseAwaitingPull) + fail(substreamOut, Http2StreamHandling.ConnectionWasAbortedException) + } + + // Multiplexer and stream callbacks may run in the middle of a transition. Observe their committed states. + private val checkPeerDrain = getAsyncCallback[Unit] { _ => + peerDrainCheckPending = false + if (!clientReadClosed && clientResponsesFinished) { + finishClientResponses() + // Finish the writer without canceling the transport's read side while a retained + // response entity still needs this stage. Actual read EOF may arrive during this drain. + if (clientUploadsFinished && multiplexer.hasFlushedAllData) beginClientReadDrain() + } + } + private def completeIfDone(): Unit = { + if (clientReadClosed) { + if (!closingClientStreams) { + finishClientResponses() + if (activeStreamCount() == 0 && isClosed(substreamOut)) completeStage() + } + return + } + if (isPeerRetiring) { + if (!peerDrainCheckPending) { + peerDrainCheckPending = true + checkPeerDrain.invoke(()) + } + return + } val noMoreOutgoingStreams = (terminating || isClosed(substreamIn)) && activeStreamCount() == 0 def allOutgoingDataFlushed = isClosed(frameOut) || multiplexer.hasFlushedAllData if (noMoreOutgoingStreams && allOutgoingDataFlushed) { @@ -563,7 +669,8 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, super.onUpstreamFinish() else { // on the client side allow ongoing responses to be delivered for a while even if requests are done completeIfDone() - scheduleOnce(CompletionTimeout, completionTimeout) + // Keep the deadline even if the writer closed while a response waits for downstream demand. + scheduleForcedCloseIfEarlier(completionTimeout) } }) @@ -632,6 +739,10 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, debug("Connection reached the configured max-connection-age, closing it gracefully") triggerTermination(maxConnectionAgeGrace) } + case ReadCompletionTimeout => + abortClientDrain() + case CompletionTimeout if clientReadClosed || isPeerRetiring => + abortClientDrain() case CompletionTimeout => if (isServer) info( @@ -658,6 +769,10 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, */ @InternalApi private[pekko] object Http2Demux { + case object RequestAdmissionClosed + extends RuntimeException("HTTP/2 connection stopped accepting requests") with scala.util.control.NoStackTrace + case object CompletionTimeout + case object ReadCompletionTimeout case object MaxConnectionAge } diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2Multiplexer.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2Multiplexer.scala index c55a480fa..56018b913 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2Multiplexer.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2Multiplexer.scala @@ -41,6 +41,9 @@ private[http2] trait Http2Multiplexer { def enqueueOutStream(streamId: Int): Unit def dequeueOutStream(streamId: Int): Unit + /** Drop queued frames for client streams the peer will not process, including requests not yet sent. */ + def retireClientRequests(lastStreamId: Int): Int + def currentInitialWindow: Int def reportTimings(): Unit @@ -159,6 +162,21 @@ private[http2] trait Http2MultiplexerSupport { logic: GraphStageLogic with Stage private val controlFrameBuffer: mutable.Queue[FrameEvent] = new mutable.Queue[FrameEvent] private val sendableOutstreams: mutable.Queue[Int] = new mutable.Queue[Int] + override def retireClientRequests(lastStreamId: Int): Int = { + // Even a GOAWAY with the maximum stream ID forbids sending a new request's initial HEADERS. + val firstUnsent = controlFrameBuffer.collectFirst { + case h: ParsedHeadersFrame if h.keyValuePairs.exists(_._1 == ":method") => h.streamId + } + val accepted = firstUnsent.fold(lastStreamId)(id => math.min(lastStreamId, id - 1)) + controlFrameBuffer.filterInPlace { + case f: StreamFrameEvent => f.streamId <= accepted + case _ => true + } + if (controlFrameBuffer.isEmpty && (_state eq WaitingForNetworkToSendControlFrames)) + updateState(_ => if (sendableOutstreams.isEmpty) Idle else WaitingForNetworkToSendData) + accepted + } + private def enqueueStream(streamId: Int): Unit = { if (isDebugEnabled) require(!sendableOutstreams.contains(streamId), s"Stream [$streamId] was enqueued multiple times.") // requires expensive scanning -> avoid in production diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2StreamHandling.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2StreamHandling.scala index 74c4622a5..4a5cd6f72 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2StreamHandling.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2StreamHandling.scala @@ -131,6 +131,9 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper activeStreamCount() < maxConcurrentStreams } + def isClientReadClosed: Boolean + def isPeerRetiring: Boolean + /** Called when all streams in StreamHandling buffers are closed and the stage is completing. */ def onAllStreamsClosed(): Unit @@ -290,15 +293,56 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper ret } - /** Called to cleanup any state when the connection is torn down */ - def shutdownStreamHandling(): Unit = updateAllStates({ id => id.shutdown(); Closed }, "shutdownStreamHandling") + /** Remove only requests beyond the accepted boundary. Never replay their application sources. */ + def rejectClientRequestsAfter(lastStreamId: Int): Boolean = { + var unanswered = false + streamStates.keysIterator.filter(_ > lastStreamId).toVector.foreach { id => + updateState(id.toInt, + state => { + state match { + case _: OpenSendingData | _: HalfClosedLocalWaitingForPeerStream | _: CollectingIncomingData => + unanswered = true + case _ => + } + state.shutdown() + Closed + }, "rejectClientRequest") + } + unanswered + } - /** Fail open incoming entity outlets on client read EOF, without changing upload lifecycle. */ - def failOpenIncomingEntities(): Unit = streamStates.valuesIterator.foreach { - case receiving: ReceivingDataWithBuffer => receiving.failOpenIncomingEntity() - case _ => () + /** Whether every accepted response is finished on the wire, independently of application entity consumption. */ + def clientResponsesFinished: Boolean = streamStates.valuesIterator.forall { + case receiving: ReceivingDataWithBuffer => receiving.canDrainAfterClientReadClosed + case _: HalfClosedRemoteSendingData => true + case _ => false } + def clientUploadsFinished: Boolean = !streamStates.valuesIterator.exists(_.isInstanceOf[Sending]) + + /** Retain only complete incoming client entities and report whether a request had no final response. */ + def retainCompletedClientEntities(): Boolean = { + var unanswered = false + streamStates.keys.toVector.foreach { id => + updateState(id.toInt, + { + case receiving: ReceivingDataWithBuffer if receiving.canDrainAfterClientReadClosed => + receiving.finishSendingForClientReadClosed() + case state => + state match { + case _: OpenSendingData | _: HalfClosedLocalWaitingForPeerStream => unanswered = true + case _ => + } + state.shutdown() + Closed + }, "retainCompletedClientEntities") + } + unanswered + } + + /** Called to cleanup any state when the connection is torn down */ + def shutdownStreamHandling(): Unit = updateAllStates({ id => id.shutdown(); Closed }, "shutdownStreamHandling") + def resetStream(streamId: Int, errorCode: ErrorCode): Unit = { // Hand the RST_STREAM to the multiplexer first: closing the last stream can complete the connection once all // outgoing data is flushed, and a frame pushed after that would be lost. @@ -535,6 +579,8 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper trait Sending extends StreamState { self: Product => protected def outStream: OutStream + final def cancelSending(): Unit = outStream.cancelStream() + override def pullNextFrame(maxSize: Int): (StreamState, PullFrameResult) = { val frame = outStream.nextFrame(maxSize) @@ -706,7 +752,15 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper self: Product => protected def buffer: IncomingStreamBuffer - final def failOpenIncomingEntity(): Unit = if (!buffer.isDone) buffer.shutdown() + final def canDrainAfterClientReadClosed: Boolean = buffer.receivedEndStream && !buffer.isDone + + final def finishSendingForClientReadClosed(): StreamState = { + this match { + case sending: Sending => sending.cancelSending() + case _ => + } + HalfClosedLocal(buffer) + } override protected def onDataFrame(dataFrame: DataFrame): StreamState = { buffer.onDataFrame(dataFrame) @@ -827,7 +881,12 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper def onPull(): Unit = incomingStreamPulled(streamId) override def onDownstreamFinish(cause: Throwable): Unit = { debug(s"Incoming side of stream [$streamId]: cancelling because downstream finished") - multiplexer.pushControlFrame(RstStreamFrame(streamId, ErrorCode.CANCEL)) + // For a client that is draining after read EOF, the writer has already been retired. + if (!isClientReadClosed) multiplexer.pushControlFrame(RstStreamFrame(streamId, ErrorCode.CANCEL)) + if (isPeerRetiring) streamStates.getOrNull(streamId) match { + case sending: Sending => sending.cancelSending() + case _ => + } wasClosed = true discardBuffer() trailingHeaders = None @@ -846,6 +905,7 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper } def isDone: Boolean = outlet.isClosed + def receivedEndStream: Boolean = wasClosed def onDataFrame(data: DataFrame): Unit = if (wasClosed) { @@ -894,7 +954,7 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper debug( s"Dispatched chunk of $dataSize for stream [$streamId], remaining window space now $outstandingStreamWindow, buffered: ${buffer.length}") - updateWindows() + if (!isClientReadClosed) updateWindows() } if (buffer.isEmpty && wasClosed) { trailingHeaders match { diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/client/PersistentConnection.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/client/PersistentConnection.scala index b613bf13c..1d96feca8 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/client/PersistentConnection.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/client/PersistentConnection.scala @@ -22,6 +22,7 @@ import scala.util.{ Failure, Success } import org.apache.pekko import pekko.NotUsed import pekko.annotation.InternalApi +import pekko.http.impl.engine.http2.Http2Demux import pekko.http.scaladsl.Http.OutgoingConnection import pekko.http.scaladsl.model.{ AttributeKey, HttpRequest, HttpResponse, RequestResponseAssociation, StatusCodes } import pekko.http.scaladsl.settings.Http2ClientSettings @@ -211,6 +212,7 @@ private[http2] object PersistentConnection { responseIn: SubSinkInlet[HttpResponse]) extends State { private var ongoingRequests: Map[AssociationTag, Map[AttributeKey[?], RequestResponseAssociation]] = Map.empty private var retiring = false + private var disconnected = false persistentConnectionMaxAge match { case age: FiniteDuration => @@ -232,7 +234,10 @@ private[http2] object PersistentConnection { } else if (isClosed(requestIn)) requestOut.complete() else if (!hasBeenPulled(requestIn)) pull(requestIn) - override def onDownstreamFinish(cause: Throwable): Unit = onDisconnected() + override def onDownstreamFinish(cause: Throwable): Unit = + if (cause eq Http2Demux.RequestAdmissionClosed) { + if (!disconnected) stopAcceptingRequests() + } else onDisconnected() }) responseIn.setHandler(new InHandler { override def onPush(): Unit = { @@ -246,7 +251,8 @@ private[http2] object PersistentConnection { override def onUpstreamFinish(): Unit = onDisconnected() override def onUpstreamFailure(ex: Throwable): Unit = onDisconnected() // FIXME: log error }) - def onDisconnected(): Unit = { + def onDisconnected(): Unit = if (!disconnected) { + disconnected = true cancelTimer(MaxConnectionAgeReached) currentConnection = None @@ -274,18 +280,23 @@ private[http2] object PersistentConnection { if (!retiring) { retiring = true log.debug("Persistent HTTP/2 connection reached its configured maximum age, retiring it") - setHandler(requestIn, - new InHandler { - override def onPush(): Unit = () // keep at most one next request in the inlet slot - override def onUpstreamFinish(): Unit = () - override def onUpstreamFailure(ex: Throwable): Unit = { - responseIn.cancel() - failStage(ex) - } - }) + stopAcceptingRequests() requestOut.complete() } + private def stopAcceptingRequests(): Unit = { + cancelTimer(MaxConnectionAgeReached) + setHandler(requestIn, + new InHandler { + override def onPush(): Unit = () // keep at most one next request in the inlet slot for reconnection + override def onUpstreamFinish(): Unit = () + override def onUpstreamFailure(ex: Throwable): Unit = { + responseIn.cancel() + failStage(ex) + } + }) + } + def dispatchRequest(req: HttpRequest): Unit = { val tag = new AssociationTag // Some cross-compilation woes here: diff --git a/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ClientReadCompletionSpec.scala b/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ClientReadCompletionSpec.scala new file mode 100644 index 000000000..49e87a941 --- /dev/null +++ b/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ClientReadCompletionSpec.scala @@ -0,0 +1,456 @@ +/* + * 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.http2 + +import java.net.InetSocketAddress + +import scala.concurrent.Future +import scala.concurrent.duration._ + +import org.apache.pekko +import pekko.http.impl.engine.http2.FrameEvent.{ + DataFrame, + GoAwayFrame, + ParsedHeadersFrame, + SettingsAckFrame, + SettingsFrame +} +import pekko.http.impl.engine.http2.client.PersistentConnection +import pekko.http.impl.engine.parsing.HttpHeaderParser +import pekko.http.impl.util.PekkoSpecWithMaterializer +import pekko.http.scaladsl.Http.OutgoingConnection +import pekko.http.scaladsl.model.{ ContentTypes, HttpEntity, HttpMethods, HttpRequest, HttpResponse, StatusCodes } +import pekko.http.scaladsl.model.headers.RawHeader +import pekko.http.scaladsl.settings.ClientConnectionSettings +import pekko.stream.scaladsl.{ Flow, Keep, Source } +import pekko.stream.testkit.{ TestPublisher, TestSubscriber } +import pekko.stream.testkit.scaladsl.{ TestSink, TestSource } +import pekko.stream.testkit.Utils.assertAllStagesStopped +import pekko.testkit.{ ExplicitlyTriggeredScheduler, TestProbe } +import pekko.util.ByteString + +class Http2ClientReadCompletionSpec extends PekkoSpecWithMaterializer( + """ + pekko.scheduler.implementation = "org.apache.pekko.testkit.ExplicitlyTriggeredScheduler" + """) { + private val drainTimeout = 1.second + + "An HTTP/2 client at clean transport read completion" should { + "deliver the completed response body and trailers after the transport has closed" in assertAllStagesStopped { + val client = new Setup + val response = client.receiveCompletedResponse() + val followingId = client.sendRequest("/following") + client.peer.sendNext(headers(followingId, endStream = true, ":status" -> "204")) + val following = client.responses.expectNext() + following.status shouldBe StatusCodes.NoContent + following.entity.isKnownEmpty shouldBe true + client.finishReading() + + expectBodyAndTrailer(response) + } + + "deliver an accepted response before failing a direct connection with an unanswered request" in + assertAllStagesStopped { + val client = directClientWithUnansweredRequest() + client.responses.request(1) + client.responses.expectError() shouldBe theSameInstanceAs(Http2StreamHandling.ConnectionWasAbortedException) + } + + "fail a direct connection by the drain deadline when there is no further response demand" in + assertAllStagesStopped { + val client = directClientWithUnansweredRequest() + advanceToDrainDeadline() + client.responses.expectError() shouldBe theSameInstanceAs(Http2StreamHandling.ConnectionWasAbortedException) + } + + "preserve an already delivered entity when the response stream is cancelled after read completion" in + assertAllStagesStopped { + val client = new Setup(initialResponseDemand = 1) + val response = client.receiveCompletedResponse() + val acceptedId = client.sendRequest("/accepted") + client.peer.sendNext(headers(acceptedId, endStream = true, ":status" -> "204")) + client.finishTransport() + client.responses.cancel() + + expectBodyAndTrailer(response) + } + + "give a managed client the accepted responses before reconnecting for a subsequent request" in + assertAllStagesStopped { + val connections = TestProbe() + val (requests, responses) = managedClient(connections) + + // Leave demand for one response; the second accepted response must survive request-input cancellation. + responses.request(1) + requests.sendNext(request("/complete")) + val first = connections.expectMsgType[Transport] + val firstId = first.startForRequest("/complete") + requests.sendNext(request("/accepted")) + val acceptedId = first.expectRequest("/accepted") + first.sendCompletedBody(firstId) + val response = responses.expectNext() + response.status shouldBe StatusCodes.OK + first.peer.sendNext(headers(acceptedId, endStream = true, ":status" -> "204")) + first.peer.sendComplete() + first.wire.expectComplete() + + responses.request(1) + responses.expectNext().status shouldBe StatusCodes.NoContent + responses.request(1) + requests.sendNext(request("/after-eof")) + val second = connections.expectMsgType[Transport] + val nextId = second.startForRequest("/after-eof") + second.peer.sendNext(headers(nextId, endStream = true, ":status" -> "204")) + responses.expectNext().status shouldBe StatusCodes.NoContent + requests.sendComplete() + responses.expectComplete() + second.wire.expectComplete() + + expectBodyAndTrailer(response) + } + + "release a completed response that the application does not consume by the drain deadline" in { + val response = assertAllStagesStopped { + val client = new Setup + val response = client.receiveCompletedResponse() + client.finishReading() + advanceToDrainDeadline() + response + } + assertAllStagesStopped { + val bytes = response.entity.dataBytes.runWith(TestSink[ByteString]()) + bytes.request(1) + bytes.expectError() shouldBe theSameInstanceAs(Http2StreamHandling.ConnectionWasAbortedException) + } + } + } + + "An HTTP/2 client receiving graceful GOAWAY" should { + "not open a queued request after a GOAWAY advertising the maximum last-stream identifier" in + assertAllStagesStopped { + // The upload is materialized, but the initial request HEADERS have not been handed to the transport. + val client = new Setup(initialWireDemand = 2) + val upload = TestPublisher.probe[ByteString]() + client.requests.sendNext(request("/queued").withMethod(HttpMethods.POST).withEntity( + HttpEntity(ContentTypes.`application/octet-stream`, Source.fromPublisher(upload)))) + val subscription = upload.expectSubscription() + client.peer.sendNext(retire(Int.MaxValue)) + client.requests.expectCancellation() + subscription.expectCancellation() + client.wire.request(1) + client.wire.expectComplete() + client.responses.expectError() shouldBe theSameInstanceAs(Http2StreamHandling.ConnectionWasAbortedException) + } + + "release a cancelled upload without interrupting its accepted sibling" in assertAllStagesStopped { + val client = new Setup + val upload = TestPublisher.probe[ByteString]() + client.requests.sendNext(request("/cancel").withMethod(HttpMethods.POST).withEntity( + HttpEntity(ContentTypes.`application/octet-stream`, Source.fromPublisher(upload)))) + val opening = client.wire.expectNext().asInstanceOf[ParsedHeadersFrame] + val subscription = upload.expectSubscription() + val sibling = client.sendRequest("/sibling") + client.peer.sendNext(retire(sibling)) + client.requests.expectCancellation() + client.peer.sendNext(headers(opening.streamId, endStream = false, ":status" -> "200")) + val entity = client.responses.expectNext().entity + val body = entity.dataBytes.runWith(TestSink[ByteString]()) + body.cancel() + client.wire.expectNext() shouldBe FrameEvent.RstStreamFrame(opening.streamId, Http2Protocol.ErrorCode.CANCEL) + subscription.expectCancellation() + + client.peer.sendNext(headers(sibling, endStream = true, ":status" -> "204")) + client.responses.expectNext().status shouldBe StatusCodes.NoContent + client.responses.expectComplete() + client.wire.expectComplete() + } + + "finish an accepted upload, including trailers, after delivering its response" in assertAllStagesStopped { + val client = new Setup + val upload = TestPublisher.probe[HttpEntity.ChunkStreamPart]() + client.requests.sendNext(request("/upload").withMethod(HttpMethods.POST).withEntity( + HttpEntity.Chunked(ContentTypes.`application/octet-stream`, Source.fromPublisher(upload)))) + val opening = client.wire.expectNext().asInstanceOf[ParsedHeadersFrame] + opening.endStream shouldBe false + opening.keyValuePairs should contain(":path" -> "/upload") + client.peer.sendNext(retire(Int.MaxValue)) + client.requests.expectCancellation() + + client.peer.sendNext(headers(opening.streamId, endStream = true, ":status" -> "204")) + client.responses.expectNext().status shouldBe StatusCodes.NoContent + client.responses.expectComplete() + upload.sendNext(HttpEntity.Chunk(ByteString("body"))) + client.wire.expectNext() shouldBe DataFrame(opening.streamId, endStream = false, ByteString("body")) + upload.sendNext(HttpEntity.LastChunk(trailer = List(RawHeader("x-upload", "complete")))) + upload.sendComplete() + val trailers = client.wire.expectNext().asInstanceOf[ParsedHeadersFrame] + trailers.streamId shouldBe opening.streamId + trailers.endStream shouldBe true + trailers.keyValuePairs should contain("x-upload" -> "complete") + client.wire.expectComplete() + } + + "finish the old accepted upload after the managed replacement has completed its own request" in + assertAllStagesStopped { + val connections = TestProbe() + val (requests, responses) = managedClient(connections) + + responses.request(2) + val upload = TestPublisher.probe[HttpEntity.ChunkStreamPart]() + requests.sendNext(request("/old-upload").withMethod(HttpMethods.POST).withEntity( + HttpEntity.Chunked(ContentTypes.`application/octet-stream`, Source.fromPublisher(upload)))) + val first = connections.expectMsgType[Transport] + val oldId = first.startForRequest("/old-upload", endStream = false) + upload.sendNext(HttpEntity.Chunk(ByteString("first"))) + first.wire.expectNext() shouldBe DataFrame(oldId, endStream = false, ByteString("first")) + first.peer.sendNext(retire(oldId)) + first.peer.sendNext(headers(oldId, endStream = true, ":status" -> "201")) + responses.expectNext().status shouldBe StatusCodes.Created + + requests.sendNext(request("/replacement")) + val second = connections.expectMsgType[Transport] + val fresh = second.startForRequest("/replacement") + second.peer.sendNext(headers(fresh, endStream = true, ":status" -> "204")) + responses.expectNext().status shouldBe StatusCodes.NoContent + requests.sendComplete() + responses.expectComplete() + second.wire.expectComplete() + + upload.sendNext(HttpEntity.Chunk(ByteString("tail"))) + first.wire.expectNext() shouldBe DataFrame(oldId, endStream = false, ByteString("tail")) + upload.sendNext(HttpEntity.LastChunk(trailer = List(RawHeader("x-upload", "complete")))) + upload.sendComplete() + val trailers = first.wire.expectNext().asInstanceOf[ParsedHeadersFrame] + trailers.streamId shouldBe oldId + trailers.endStream shouldBe true + trailers.keyValuePairs should contain("x-upload" -> "complete") + first.wire.expectComplete() + } + + "close an old connection with an unfinished application upload at the retirement deadline" in + assertAllStagesStopped { + val connections = TestProbe() + val (requests, responses) = managedClient(connections) + + responses.request(3) + val upload = TestPublisher.probe[HttpEntity.ChunkStreamPart]() + requests.sendNext(request("/old-upload").withMethod(HttpMethods.POST).withEntity( + HttpEntity.Chunked(ContentTypes.`application/octet-stream`, Source.fromPublisher(upload)))) + val first = connections.expectMsgType[Transport] + val oldId = first.startForRequest("/old-upload", endStream = false) + first.peer.sendNext(retire(oldId)) + first.peer.sendNext(headers(oldId, endStream = true, ":status" -> "201")) + responses.expectNext().status shouldBe StatusCodes.Created + + requests.sendNext(request("/replacement")) + val second = connections.expectMsgType[Transport] + val fresh = second.startForRequest("/replacement") + second.peer.sendNext(headers(fresh, endStream = true, ":status" -> "204")) + responses.expectNext().status shouldBe StatusCodes.NoContent + + // The old connection still accepts data from the original application source until its deadline. + upload.sendNext(HttpEntity.Chunk(ByteString("body"))) + first.wire.expectNext() shouldBe DataFrame(oldId, endStream = false, ByteString("body")) + advanceToDrainDeadline() + upload.expectCancellation() + first.wire.expectComplete() + first.peer.expectCancellation() + + requests.sendNext(request("/still-open")) + val next = second.expectRequest("/still-open") + second.peer.sendNext(headers(next, endStream = true, ":status" -> "204")) + responses.expectNext().status shouldBe StatusCodes.NoContent + requests.sendComplete() + responses.expectComplete() + second.wire.expectComplete() + } + + "deliver accepted responses and reconnect for a fresh request without replaying a dispatched sibling" in + assertAllStagesStopped { + val connections = TestProbe() + val (requests, responses) = managedClient(connections) + + responses.request(3) + requests.sendNext(request("/accepted")) + val first = connections.expectMsgType[Transport] + val accepted = first.startForRequest("/accepted") + requests.sendNext(request("/not-processed")) + first.expectRequest("/not-processed") should be > accepted + first.peer.sendNext(retire(Int.MaxValue)) + first.peer.sendNext(retire(accepted)) + first.peer.sendNext(headers(accepted, endStream = false, ":status" -> "200")) + val response = responses.expectNext() + response.status shouldBe StatusCodes.OK + // The accepted response is still in flight. A fresh request must wait for a replacement connection. + requests.sendNext(request("/fresh")) + first.peer.sendNext(DataFrame(accepted, endStream = false, ByteString("body"))) + first.peer.sendNext(headers(accepted, endStream = true, "x-check" -> "complete")) + responses.expectNext().status shouldBe StatusCodes.BadGateway + first.wire.expectComplete() + + val second = connections.expectMsgType[Transport] + val fresh = second.startForRequest("/fresh") + second.peer.sendNext(headers(fresh, endStream = true, ":status" -> "204")) + responses.expectNext().status shouldBe StatusCodes.NoContent + requests.sendComplete() + responses.expectComplete() + second.wire.expectComplete() + expectBodyAndTrailer(response) + } + } + + private def retire(lastStreamId: Int): GoAwayFrame = + GoAwayFrame(lastStreamId, Http2Protocol.ErrorCode.NO_ERROR, ByteString.empty) + + private def directClientWithUnansweredRequest(): Setup = { + val client = new Setup(initialResponseDemand = 0) + val acceptedId = client.sendRequest("/accepted") + client.sendRequest("/unanswered") + client.peer.sendNext(headers(acceptedId, endStream = true, ":status" -> "204")) + client.finishTransport() + + // The first response must still be available even though the transport has already closed. + client.responses.request(1) + val accepted = client.responses.expectNext() + accepted.status shouldBe StatusCodes.NoContent + accepted.entity.isKnownEmpty shouldBe true + client + } + + private def advanceToDrainDeadline(): Unit = + system.scheduler.asInstanceOf[ExplicitlyTriggeredScheduler].timePasses(drainTimeout) + + private def headers(streamId: Int, endStream: Boolean, fields: (String, String)*): ParsedHeadersFrame = + ParsedHeadersFrame(streamId, endStream, fields, None, None) + + private val settings = { + val defaults = ClientConnectionSettings(system) + // Keep the standard initial window in this fixture so unrelated flow-credit frames do not enter the probe. + defaults.withHttp2Settings(defaults.http2Settings + .withCompletionTimeout(drainTimeout) + .withIncomingConnectionLevelBufferSize(Http2Protocol.InitialWindowSize)) + } + + private def request(path: String): HttpRequest = HttpRequest(uri = s"https://example.invalid$path") + + private def testConnection = { + val parser = HttpHeaderParser(settings.parserSettings, system.log) + val transport = Flow.fromSinkAndSourceMat(TestSink[FrameEvent](), TestSource[FrameEvent]())(Keep.both) + Http2Blueprint + .httpLayerClient(parser, settings, system.log) + .atop(Http2Blueprint.clientDemux(settings.http2Settings, parser)) + .joinMat(transport)(Keep.right) + } + + private def managedClient(connections: TestProbe) = { + val addresses = new InetSocketAddress("127.0.0.1", 0) + val connection = testConnection.mapMaterializedValue { + case (wire, peer) => + connections.ref ! new Transport(wire, peer) + Future.successful(OutgoingConnection(addresses, addresses)) + } + TestSource[HttpRequest]() + .via(PersistentConnection.managedConnection(connection, settings.http2Settings)) + .toMat(TestSink[HttpResponse]())(Keep.both) + .run() + } + + private def expectBodyAndTrailer(response: HttpResponse): Unit = { + val entity = response.entity.asInstanceOf[HttpEntity.Chunked] + val chunks = entity.chunks.runWith(TestSink[HttpEntity.ChunkStreamPart]()) + chunks.request(2) + chunks.expectNext(HttpEntity.Chunk(ByteString("body"))) + chunks.expectNext(HttpEntity.LastChunk(trailer = List(RawHeader("x-check", "complete")))) + chunks.expectComplete() + } + + private class Transport(val wire: TestSubscriber.Probe[FrameEvent], val peer: TestPublisher.Probe[FrameEvent]) { + private def sendInitialSettings(demand: Int = 16): Unit = { + wire.request(demand.toLong) + wire.expectNext() shouldBe a[SettingsFrame] + peer.sendNext(SettingsFrame(Nil)) + } + + def start(demand: Int): Unit = { + sendInitialSettings(demand) + wire.expectNext() shouldBe SettingsAckFrame(Nil) + } + + def startForRequest(path: String, endStream: Boolean = true): Int = { + sendInitialSettings() + // A managed connection is materialized by this request; the settings acknowledgement may follow it. + val first = wire.expectNext() + val second = wire.expectNext() + if (first == SettingsAckFrame(Nil)) expectRequest(path, second, endStream) + else { + second shouldBe SettingsAckFrame(Nil) + expectRequest(path, first, endStream) + } + } + + def expectRequest(path: String): Int = expectRequest(path, wire.expectNext(), endStream = true) + + private def expectRequest(path: String, frame: FrameEvent, endStream: Boolean): Int = { + val request = frame.asInstanceOf[ParsedHeadersFrame] + request.endStream shouldBe endStream + request.keyValuePairs should contain(":path" -> path) + request.streamId + } + + def sendCompletedBody(streamId: Int): Unit = { + peer.sendNext(headers(streamId, endStream = false, ":status" -> "200")) + peer.sendNext(DataFrame(streamId, endStream = false, ByteString("body"))) + peer.sendNext(headers(streamId, endStream = true, "x-check" -> "complete")) + } + } + + private class Setup(initialResponseDemand: Int = 16, initialWireDemand: Int = 16) { + val ((requests, (wire, peer)), responses) = TestSource[HttpRequest]() + .viaMat(testConnection)(Keep.both) + .toMat(TestSink[HttpResponse]())(Keep.both) + .run() + private val transport = new Transport(wire, peer) + + if (initialResponseDemand > 0) responses.request(initialResponseDemand) + transport.start(initialWireDemand) + + def sendRequest(path: String): Int = { + requests.sendNext(request(path)) + transport.expectRequest(path) + } + + def receiveCompletedResponse(): HttpResponse = { + val streamId = sendRequest("/complete") + transport.sendCompletedBody(streamId) + val response = responses.expectNext() + response.status shouldBe StatusCodes.OK + response + } + + def finishTransport(): Unit = { + peer.sendComplete() + requests.expectCancellation() + wire.expectComplete() + } + + def finishReading(): Unit = { + finishTransport() + responses.expectComplete() + } + } +} diff --git a/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ClientServerSpec.scala b/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ClientServerSpec.scala index 6ee016d36..cca9e0843 100644 --- a/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ClientServerSpec.scala +++ b/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ClientServerSpec.scala @@ -84,6 +84,31 @@ class Http2ClientServerSpec extends PekkoSpecWithMaterializer( Unmarshal(response.entity).to[String].futureValue shouldBe "pong" response.attribute(requestIdAttr).get.id shouldBe "request-1" } + "preserve a complete streamed response after the server closes a TLS connection" in new TestSetup { + val first = ByteString("first part ") + val last = ByteString("last part") + + try { + sendClientRequest(HttpRequest(uri = "/drain")) + val serverRequest = expectServerRequest() + serverRequest.request.protocol shouldBe HttpProtocols.`HTTP/2.0` + serverRequest.sendResponse(HttpResponse( + entity = HttpEntity.Chunked.fromData(ContentTypes.`application/octet-stream`, Source(List(first, last))))) + + val response = expectClientResponse() + response.protocol shouldBe HttpProtocols.`HTTP/2.0` + response.status shouldBe StatusCodes.OK + response.entity.isChunked shouldBe true + + binding.terminate(3.seconds).futureValue(timeout(5.seconds)) + clientResponsesIn.expectComplete() + // No entity subscription until the server has terminated and the client's response stream has closed. + response.entity.toStrict(3.seconds).futureValue(timeout(5.seconds)).data shouldBe (first ++ last) + } finally { + if (!binding.whenTerminated.isCompleted) + binding.terminate(1.second).futureValue(timeout(5.seconds)) + } + } "preserve repeated Set-Cookie field order across an HTTP/2 response" in new TestSetup { try { val theme = headers.`Set-Cookie`(headers.HttpCookie("theme", "dark")) diff --git a/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ClientSpec.scala b/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ClientSpec.scala index 24f9c5bac..3eb4aa828 100644 --- a/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ClientSpec.scala +++ b/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ClientSpec.scala @@ -1085,7 +1085,7 @@ class Http2ClientSpec extends PekkoSpecWithMaterializer(""" user.requestOut.expectCancellation() }) - "fail a response entity whose final data is still buffered when the peer closes its sending side".inAssertAllStagesStopped( + "deliver a response entity whose final data is still buffered when the peer closes its sending side".inAssertAllStagesStopped( new ReceivingResponseEntity { // Use up the demand of 2 signalled by the fixture. receiveEntityData() @@ -1093,18 +1093,19 @@ class Http2ClientSpec extends PekkoSpecWithMaterializer(""" network.expectWindowUpdate() network.expectWindowUpdate() - // The consumer has no demand left. One more chunk is still pulled out of the stream buffer by the entity - // stream, so the chunk carrying END_STREAM after it stays buffered and the entity outlet stays open. network.sendDATA(1, endStream = false, ByteString("more")) network.sendDATA(1, endStream = true, ByteString("tail")) - entity.expectNoMessage(100.millis) - network.fromNet.sendComplete() - - // The entity must not complete normally without its tail. - entity.expectError() shouldBe theSameInstanceAs(Http2StreamHandling.ConnectionWasAbortedException) expectGracefulCompletion() user.requestOut.expectCancellation() + + // Only ask for the retained bytes once the connection has completed, without assuming chunk boundaries. + val expected = ByteString("moretail") + entity.request(2) + val first = entity.expectNext() + val actual = if (first.length < expected.length) first ++ entity.expectNext() else first + actual shouldBe expected + entity.expectComplete() }) "preserve the connection failure in the delivered entity".inAssertAllStagesStopped( diff --git a/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ServerSpec.scala b/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ServerSpec.scala index 6f75480e7..f1110f1d6 100644 --- a/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ServerSpec.scala +++ b/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ServerSpec.scala @@ -2338,6 +2338,38 @@ class Http2ServerSpec extends Http2SpecWithMaterializer(""" } "support graceful shutdown" should { + "acknowledge a client GOAWAY and close an idle connection".inAssertAllStagesStopped( + new TestSetup with RequestResponseProbes { + user.requestIn.ensureSubscription() + + network.sendFrame(GoAwayFrame(0, ErrorCode.NO_ERROR, ByteString.empty)) + network.expectGOAWAY(0)._2 shouldBe ErrorCode.NO_ERROR + expectGracefulCompletion() + }) + "drain a client request after its GOAWAY and flush the response trailers".inAssertAllStagesStopped( + new TestSetup with RequestResponseProbes { + network.sendRequestHEADERS(1, HttpRequest(method = HttpMethods.POST), endStream = false) + val request = user.expectRequest() + val body = ByteStringSinkProbe(request.entity.dataBytes) + + // The client has not accepted any server-initiated streams; that does not exclude request 1. + network.sendFrame(GoAwayFrame(0, ErrorCode.NO_ERROR, ByteString.empty)) + network.expectGOAWAY(1)._2 shouldBe ErrorCode.NO_ERROR + network.sendDATA(1, endStream = true, ByteString("request")) + body.expectUtf8EncodedString("request") + body.expectComplete() + val credit = network.expect[WindowUpdateFrame]() + credit.streamId shouldBe 0 + + val response = HttpEntity.Chunked( + ContentTypes.`application/octet-stream`, + Source(List(HttpEntity.Chunk("response"), HttpEntity.LastChunk(trailer = Seq(RawHeader("x-end", "done")))))) + user.emitResponse(1, HttpResponse(entity = response)) + network.expectDecodedHEADERS(1, endStream = false) + network.expectDATA(1, endStream = false, ByteString("response")) + network.expectDecodedHEADERS(1).headers shouldBe Seq(RawHeader("x-end", "done")) + expectGracefulCompletion() + }) "close when the last request entity is cancelled during graceful shutdown".inAssertAllStagesStopped( new TestSetup with RequestResponseProbes { network.sendRequestHEADERS(1, HttpRequest(), endStream = false)