From 964123d0335775a6d96d2b46de21c3d948b0bc9b Mon Sep 17 00:00:00 2001 From: "He-Pin(kerr)" Date: Thu, 26 Nov 2026 21:12:48 +0800 Subject: [PATCH 1/3] fix: preserve completed HTTP/2 client responses at read EOF Motivation: A clean transport read close is not an HTTP/2 stream end. A client should keep already completed response bodies and trailers without retaining abandoned entities indefinitely or dropping accepted responses while reporting unanswered requests. Modification: Retire only the client writer and request admission on clean read EOF. Drain completed response entities within the existing completion timeout, respecting earlier deadlines. Complete or fail the response stream without overtaking its already accepted responses; keep the managed client's disconnect handling and avoid replaying requests. Retain the current server path and normal stream ordering. Result: An accepted response survives transport retirement, and queued responses are delivered before a direct connection reports unanswered requests. The configured deadline releases abandoned buffers and settles a client that asks for no more responses. Tests: JDK 17, Scala 2.13.18 and 3.3.9. Six focused typed client checks and two existing ordinary HTTP/2 flow controls per version; scoped formatting, header checks, and http-core MiMa. References: Addresses review on #1440. Related #1445 and #1525. RFC 9113 Section 8.1. --- docs/src/main/paradox/client-side/http2.md | 24 +- http-core/src/main/resources/reference.conf | 1 + .../http/impl/engine/http2/Http2Demux.scala | 84 +++++- .../engine/http2/Http2StreamHandling.scala | 46 ++- .../http2/client/PersistentConnection.scala | 33 ++- .../http2/Http2ClientReadCompletionSpec.scala | 269 ++++++++++++++++++ .../engine/http2/Http2ClientServerSpec.scala | 25 ++ .../impl/engine/http2/Http2ClientSpec.scala | 17 +- 8 files changed, 454 insertions(+), 45 deletions(-) create mode 100644 http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ClientReadCompletionSpec.scala diff --git a/docs/src/main/paradox/client-side/http2.md b/docs/src/main/paradox/client-side/http2.md index c003a17482..e8a16cfea9 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,23 @@ The default maximum age is `infinite`, which disables age-based retirement. The programmatically with `Http2ClientSettings.withPersistentConnectionMaxAge` and `Http2ClientSettings.withPersistentConnectionMaxAgeJitter`. +## 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/http-core/src/main/resources/reference.conf b/http-core/src/main/resources/reference.conf index 6cd4bc7162..28d2960c26 100644 --- a/http-core/src/main/resources/reference.conf +++ b/http-core/src/main/resources/reference.conf @@ -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 351e41a382..6eaefe92f4 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,11 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, private val terminationPromise = Promise[Http.HttpTerminated]() private var terminating: Boolean = false + private var clientReadClosed = false + private var closingClientStreams = false + private var unansweredAtReadCompletion = false + private var clientResponseAwaitingPull = false + override def isClientReadClosed: Boolean = clientReadClosed 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 @@ -344,7 +349,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,7 +415,7 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, if (allow != allowReadingIncomingFrames) if (allow) { debug("Resume reading incoming frames") - if (!hasBeenPulled(frameIn)) pull(frameIn) + if (!isClosed(frameIn) && !hasBeenPulled(frameIn)) pull(frameIn) } else debug("Suspended reading incoming frames") // can't retract pending pull but that's ok allowReadingIncomingFrames = allow @@ -419,7 +424,7 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, if (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,11 +435,9 @@ 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 finishClientRead() def onPush(): Unit = { val frame = grab(frameIn) @@ -515,7 +518,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) 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 +545,42 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, override def onAllStreamsClosed(): Unit = completeIfDone() override def onAllDataFlushed(): Unit = completeIfDone() + private def finishClientRead(): Unit = { + 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.IncomingReadComplete) + // Retire the writer at the same time; retained response buffers no longer need to send frames. + if (!isClosed(frameOut)) complete(frameOut) + unansweredAtReadCompletion = retainCompletedClientEntities() + closingClientStreams = false + scheduleOnce(ReadCompletionTimeout, completionTimeout) + completeIfDone() + } + + private def abortClientReadDrain(): Unit = { + if (!isClosed(substreamOut)) + bufferedSubStreamOutput.fail(Http2StreamHandling.ConnectionWasAbortedException) + shutdownStreamHandling() + completeStage() + } + private def completeIfDone(): Unit = { + if (clientReadClosed) { + if (!closingClientStreams) { + if (bufferedSubStreamOutput.buffer.isEmpty && !isClosed(substreamOut)) { + if (!unansweredAtReadCompletion) complete(substreamOut) + // Failing a graph outlet can overtake an element just pushed to it. Let the response advance + // before failing on more demand; the drain deadline also applies if no further demand arrives. + else if (!clientResponseAwaitingPull) + fail(substreamOut, Http2StreamHandling.ConnectionWasAbortedException) + } + if (activeStreamCount() == 0 && isClosed(substreamOut)) completeStage() + } + return + } val noMoreOutgoingStreams = (terminating || isClosed(substreamIn)) && activeStreamCount() == 0 def allOutgoingDataFlushed = isClosed(frameOut) || multiplexer.hasFlushedAllData if (noMoreOutgoingStreams && allOutgoingDataFlushed) { @@ -632,6 +688,10 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, debug("Connection reached the configured max-connection-age, closing it gracefully") triggerTermination(maxConnectionAgeGrace) } + case ReadCompletionTimeout => + abortClientReadDrain() + case CompletionTimeout if clientReadClosed => + abortClientReadDrain() case CompletionTimeout => if (isServer) info( @@ -658,6 +718,10 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, */ @InternalApi private[pekko] object Http2Demux { + case object IncomingReadComplete + extends RuntimeException("HTTP/2 peer completed its input") 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/Http2StreamHandling.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2StreamHandling.scala index 74c4622a53..6c777544fc 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,8 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper activeStreamCount() < maxConcurrentStreams } + def isClientReadClosed: Boolean + /** Called when all streams in StreamHandling buffers are closed and the stage is completing. */ def onAllStreamsClosed(): Unit @@ -290,15 +292,29 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper ret } + /** 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") - /** 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 _ => () - } - 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 +551,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 +724,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 +853,8 @@ 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)) wasClosed = true discardBuffer() trailingHeaders = None @@ -846,6 +873,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 +922,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 b613bf13c2..ac23452b4b 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.IncomingReadComplete) { + 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 0000000000..7bf59462ed --- /dev/null +++ b/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ClientReadCompletionSpec.scala @@ -0,0 +1,269 @@ +/* + * 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, 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.{ HttpEntity, HttpRequest, HttpResponse, StatusCodes } +import pekko.http.scaladsl.model.headers.RawHeader +import pekko.http.scaladsl.settings.ClientConnectionSettings +import pekko.stream.scaladsl.{ Flow, Keep } +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 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)) + } + val (requests, responses) = TestSource[HttpRequest]() + .via(PersistentConnection.managedConnection(connection, settings.http2Settings)) + .toMat(TestSink[HttpResponse]())(Keep.both) + .run() + + // 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) + } + } + } + + 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 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(): Unit = { + wire.request(16) + wire.expectNext() shouldBe a[SettingsFrame] + peer.sendNext(SettingsFrame(Nil)) + } + + def start(): Unit = { + sendInitialSettings() + wire.expectNext() shouldBe SettingsAckFrame(Nil) + } + + def startForRequest(path: String): 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) + else { + second shouldBe SettingsAckFrame(Nil) + expectRequest(path, first) + } + } + + def expectRequest(path: String): Int = expectRequest(path, wire.expectNext()) + + private def expectRequest(path: String, frame: FrameEvent): Int = { + val request = frame.asInstanceOf[ParsedHeadersFrame] + request.endStream shouldBe true + 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) { + 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() + + 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 6ee016d366..cca9e0843d 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 24f9c5bac0..3eb4aa8283 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( From 33b742ed6bd5de4a2502ec02cf652411eb46cebd Mon Sep 17 00:00:00 2001 From: "He-Pin(kerr)" Date: Thu, 26 Nov 2026 21:13:52 +0800 Subject: [PATCH 2/3] fix: retire HTTP/2 client connections on peer GOAWAY Motivation: A graceful GOAWAY closes request admission on the receiving connection, but does not cancel exchanges the peer has accepted. Modification: Stop opening client streams as soon as the peer retires the connection. Remove requests still queued at the transport boundary or above the advertised limit; allow accepted uploads and responses to finish. Keep managed retries limited to requests not dispatched on the old connection and retain completed response entities for their consumers. Bound draining from the first graceful GOAWAY with the existing client completion timeout without extending an earlier deadline. Close the quiescent writer without canceling transport input ahead of draining already accepted response bodies. Treat subsequent read termination as idempotent. Result: A replacement connection can accept a fresh request without replaying a dispatched sibling or losing an accepted upload, response, or trailer. Tests: Exercise the ordinary client and managed connection with typed HTTP/2 events, including queued admission, accepted uploads, cancellation, a decreasing stream boundary, completed response trailers, reconnect, and retirement of an unfinished local streaming upload on a controlled deadline without disturbing its replacement connection. Retain the clean read-completion cases and ordinary TLS streamed response coverage from the prerequisite. References: RFC 9113 section 6.8; apache/pekko-http#1440; apache/pekko-http#1445 --- docs/src/main/paradox/client-side/http2.md | 13 + .../http/impl/engine/http2/Http2Demux.scala | 96 +++++-- .../impl/engine/http2/Http2Multiplexer.scala | 18 ++ .../engine/http2/Http2StreamHandling.scala | 32 +++ .../http2/client/PersistentConnection.scala | 2 +- .../http2/Http2ClientReadCompletionSpec.scala | 237 ++++++++++++++++-- 6 files changed, 347 insertions(+), 51 deletions(-) diff --git a/docs/src/main/paradox/client-side/http2.md b/docs/src/main/paradox/client-side/http2.md index e8a16cfea9..844b9c4914 100644 --- a/docs/src/main/paradox/client-side/http2.md +++ b/docs/src/main/paradox/client-side/http2.md @@ -95,6 +95,19 @@ 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 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 6eaefe92f4..ec810562de 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 @@ -310,11 +310,14 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, private val terminationPromise = Promise[Http.HttpTerminated]() private var terminating: Boolean = false - private var clientReadClosed = 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 unansweredAtReadCompletion = 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 @@ -333,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 @@ -415,13 +418,14 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, if (allow != allowReadingIncomingFrames) if (allow) { debug("Resume reading incoming frames") - if (!isClosed(frameIn) && !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 (!clientReadClosed && !hasBeenPulled(substreamIn) && !isClosed(substreamIn)) { @@ -437,10 +441,12 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, override def onUpstreamFinish(): Unit = if (isServer) super.onUpstreamFinish() - else finishClientRead() + 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() @@ -476,6 +482,22 @@ 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(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 @@ -490,10 +512,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) @@ -527,7 +551,7 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, override def onPull(): Unit = { clientResponseAwaitingPull = false super.onPull() - if (clientReadClosed) completeIfDone() + if (clientReadClosed || isPeerRetiring) completeIfDone() } override def onDownstreamFinish(cause: Throwable): Unit = @@ -545,42 +569,63 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, override def onAllStreamsClosed(): Unit = completeIfDone() override def onAllDataFlushed(): Unit = completeIfDone() - private def finishClientRead(): Unit = { + 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.IncomingReadComplete) + 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) - unansweredAtReadCompletion = retainCompletedClientEntities() + val unansweredAtEof = retainCompletedClientEntities() + unansweredAtRetirement ||= unansweredAtEof closingClientStreams = false scheduleOnce(ReadCompletionTimeout, completionTimeout) completeIfDone() } - private def abortClientReadDrain(): Unit = { + 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) { - if (bufferedSubStreamOutput.buffer.isEmpty && !isClosed(substreamOut)) { - if (!unansweredAtReadCompletion) complete(substreamOut) - // Failing a graph outlet can overtake an element just pushed to it. Let the response advance - // before failing on more demand; the drain deadline also applies if no further demand arrives. - else if (!clientResponseAwaitingPull) - fail(substreamOut, Http2StreamHandling.ConnectionWasAbortedException) - } + 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) { @@ -619,7 +664,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) } }) @@ -689,9 +735,9 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, triggerTermination(maxConnectionAgeGrace) } case ReadCompletionTimeout => - abortClientReadDrain() - case CompletionTimeout if clientReadClosed => - abortClientReadDrain() + abortClientDrain() + case CompletionTimeout if clientReadClosed || isPeerRetiring => + abortClientDrain() case CompletionTimeout => if (isServer) info( @@ -718,8 +764,8 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, */ @InternalApi private[pekko] object Http2Demux { - case object IncomingReadComplete - extends RuntimeException("HTTP/2 peer completed its input") with scala.util.control.NoStackTrace + case object RequestAdmissionClosed + extends RuntimeException("HTTP/2 connection stopped accepting requests") with scala.util.control.NoStackTrace case object CompletionTimeout case object ReadCompletionTimeout 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 c55a480fac..56018b9139 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 6c777544fc..4a5cd6f72d 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 @@ -132,6 +132,7 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper } def isClientReadClosed: Boolean + def isPeerRetiring: Boolean /** Called when all streams in StreamHandling buffers are closed and the stage is completing. */ def onAllStreamsClosed(): Unit @@ -292,6 +293,33 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper ret } + /** 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 + } + + /** 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 @@ -855,6 +883,10 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper debug(s"Incoming side of stream [$streamId]: cancelling because downstream finished") // 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 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 ac23452b4b..1d96feca8d 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 @@ -235,7 +235,7 @@ private[http2] object PersistentConnection { else if (!hasBeenPulled(requestIn)) pull(requestIn) override def onDownstreamFinish(cause: Throwable): Unit = - if (cause eq Http2Demux.IncomingReadComplete) { + if (cause eq Http2Demux.RequestAdmissionClosed) { if (!disconnected) stopAcceptingRequests() } else onDisconnected() }) 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 index 7bf59462ed..49e87a9415 100644 --- 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 @@ -23,15 +23,21 @@ import scala.concurrent.Future import scala.concurrent.duration._ import org.apache.pekko -import pekko.http.impl.engine.http2.FrameEvent.{ DataFrame, ParsedHeadersFrame, SettingsAckFrame, SettingsFrame } +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.{ HttpEntity, HttpRequest, HttpResponse, StatusCodes } +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 } +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 @@ -87,16 +93,7 @@ class Http2ClientReadCompletionSpec extends PekkoSpecWithMaterializer( "give a managed client the accepted responses before reconnecting for a subsequent request" in assertAllStagesStopped { val 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)) - } - val (requests, responses) = TestSource[HttpRequest]() - .via(PersistentConnection.managedConnection(connection, settings.http2Settings)) - .toMat(TestSink[HttpResponse]())(Keep.both) - .run() + val (requests, responses) = managedClient(connections) // Leave demand for one response; the second accepted response must survive request-input cancellation. responses.request(1) @@ -143,6 +140,183 @@ class Http2ClientReadCompletionSpec extends PekkoSpecWithMaterializer( } } + "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") @@ -183,6 +357,19 @@ class Http2ClientReadCompletionSpec extends PekkoSpecWithMaterializer( .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]()) @@ -193,34 +380,34 @@ class Http2ClientReadCompletionSpec extends PekkoSpecWithMaterializer( } private class Transport(val wire: TestSubscriber.Probe[FrameEvent], val peer: TestPublisher.Probe[FrameEvent]) { - private def sendInitialSettings(): Unit = { - wire.request(16) + private def sendInitialSettings(demand: Int = 16): Unit = { + wire.request(demand.toLong) wire.expectNext() shouldBe a[SettingsFrame] peer.sendNext(SettingsFrame(Nil)) } - def start(): Unit = { - sendInitialSettings() + def start(demand: Int): Unit = { + sendInitialSettings(demand) wire.expectNext() shouldBe SettingsAckFrame(Nil) } - def startForRequest(path: String): Int = { + 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) + if (first == SettingsAckFrame(Nil)) expectRequest(path, second, endStream) else { second shouldBe SettingsAckFrame(Nil) - expectRequest(path, first) + expectRequest(path, first, endStream) } } - def expectRequest(path: String): Int = expectRequest(path, wire.expectNext()) + def expectRequest(path: String): Int = expectRequest(path, wire.expectNext(), endStream = true) - private def expectRequest(path: String, frame: FrameEvent): Int = { + private def expectRequest(path: String, frame: FrameEvent, endStream: Boolean): Int = { val request = frame.asInstanceOf[ParsedHeadersFrame] - request.endStream shouldBe true + request.endStream shouldBe endStream request.keyValuePairs should contain(":path" -> path) request.streamId } @@ -232,7 +419,7 @@ class Http2ClientReadCompletionSpec extends PekkoSpecWithMaterializer( } } - private class Setup(initialResponseDemand: Int = 16) { + 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) @@ -240,7 +427,7 @@ class Http2ClientReadCompletionSpec extends PekkoSpecWithMaterializer( private val transport = new Transport(wire, peer) if (initialResponseDemand > 0) responses.request(initialResponseDemand) - transport.start() + transport.start(initialWireDemand) def sendRequest(path: String): Int = { requests.sendNext(request(path)) From 76ac937e36a66566373cc61addd61c681ad2b45c Mon Sep 17 00:00:00 2001 From: "He-Pin(kerr)" Date: Fri, 27 Nov 2026 02:07:10 +0800 Subject: [PATCH 3/3] fix: drain HTTP/2 servers after client GOAWAY Motivation: The server does not begin retirement when a client sends a graceful HTTP/2 GOAWAY. Modification: Start the existing graceful server drain using its own accepted stream boundary and server grace period. Keep accepted streams and their response trailers intact. Result: Idle connections close; active requests can finish without a repeated peer notice extending the deadline. Tests: Focused JDK 17 Scala 2.13 and 3.3 suites; 15 passed on each axis. References: RFC 9113 section 6.8; stacked on apache/pekko-http#1445. --- docs/src/main/paradox/server-side/http2.md | 5 +++ http-core/src/main/resources/reference.conf | 8 ++--- .../http/impl/engine/http2/Http2Demux.scala | 5 +++ .../impl/engine/http2/Http2ServerSpec.scala | 32 +++++++++++++++++++ 4 files changed, 46 insertions(+), 4 deletions(-) diff --git a/docs/src/main/paradox/server-side/http2.md b/docs/src/main/paradox/server-side/http2.md index f38e26e606..7a566d63d7 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 28d2960c26..702efd22ce 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 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 ec810562de..43a6fdd120 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 @@ -482,6 +482,11 @@ 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 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 6f75480e72..f1110f1d6d 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)