diff --git a/docs/src/main/paradox/client-side/http2.md b/docs/src/main/paradox/client-side/http2.md index c003a1748..b89604a8c 100644 --- a/docs/src/main/paradox/client-side/http2.md +++ b/docs/src/main/paradox/client-side/http2.md @@ -102,6 +102,22 @@ The default maximum age is `infinite`, which disables age-based retirement. The programmatically with `Http2ClientSettings.withPersistentConnectionMaxAge` and `Http2ClientSettings.withPersistentConnectionMaxAgeJitter`. +## Graceful close on a direct connection + +A connection created by `http2()` or `http2WithPriorKnowledge()` can notify the server when the application +has finished sending requests. This is off by default. Enable it with +`pekko.http.client.http2.send-goaway-on-graceful-close = on` in your configuration. +For per-connection settings, use `ClientConnectionSettings.mapHttp2Settings` with +`_.withSendGoAwayOnGracefulClose(true)` in Scala, or pass the same configuration override to +`ClientConnectionSettings.create(String)` in Java. Pass those settings to the builder with +`withClientConnectionSettings`. + +Complete the request source normally when it has no more requests, for example by completing its materialized +`SourceQueue`. The client sends one graceful HTTP/2 GOAWAY and lets requests already in flight finish. Continue consuming +the response stream and entities until they complete. The existing `completion-timeout` bounds this wait. +Cancelling the response stream or failing the request source is not graceful close. This setting does not +apply to the managed persistent connection builders or configure how the client handles a peer's GOAWAY. + ## 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 6cd4bc716..6b1376e26 100644 --- a/http-core/src/main/resources/reference.conf +++ b/http-core/src/main/resources/reference.conf @@ -715,6 +715,11 @@ pekko.http { # This also bounds the drain of a connection retired after `persistent-connection-max-age`. completion-timeout = 3s + # Send one NO_ERROR GOAWAY when the request source of a direct HTTP/2 connection completes normally. + # Already started requests can still complete within completion-timeout. Managed persistent + # connections are not affected. + send-goaway-on-graceful-close = off + frame-type-throttle { # Configure the throttle for frames received from the server (https://github.com/apache/pekko-http/issues/1393). # It works like `pekko.http.server.http2.frame-type-throttle` and supports the same frame-types: 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..adf954172 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 @@ -73,6 +73,7 @@ private[http2] class Http2ClientDemux(http2Settings: Http2ClientSettings, master } override def completionTimeout: FiniteDuration = http2Settings.completionTimeout + override protected def sendGoAwayOnGracefulClose: Boolean = http2Settings.sendGoAwayOnGracefulClose // the client side limits the age of managed persistent connections in PersistentConnection instead, // see `persistent-connection-max-age` @@ -277,6 +278,7 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, def wrapTrailingHeaders(headers: ParsedHeadersFrame): Option[HttpEntity.ChunkStreamPart] def completionTimeout: FiniteDuration + protected def sendGoAwayOnGracefulClose: Boolean = false def maxConnectionAge: Duration def maxConnectionAgeGrace: Duration def maxConnectionAgeJitter: Double @@ -310,6 +312,7 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, private val terminationPromise = Promise[Http.HttpTerminated]() private var terminating: Boolean = false + private var clientGracefulGoAwaySent = false 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 @@ -400,9 +403,16 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, } } + // A later error GOAWAY must not increase the last stream ID advertised during graceful close. + // The locally allocated request IDs are not part of the peer-initiated stream ID space. + private def goAwayLastStreamId(): Int = + if (clientGracefulGoAwaySent) Http2Protocol.NoStreamId else lastStreamId() + + private def pushGoAwayFrame(errorCode: ErrorCode, debug: ByteString): Unit = + multiplexer.pushControlFrame(GoAwayFrame(goAwayLastStreamId(), errorCode, debug)) + override def pushGOAWAY(errorCode: ErrorCode, debug: String): Unit = { - val frame = GoAwayFrame(lastStreamId(), errorCode, ByteString(debug)) - multiplexer.pushControlFrame(frame) + pushGoAwayFrame(errorCode, ByteString(debug)) // FIXME: handle the connection closing according to the specification } private var allowReadingIncomingFrames: Boolean = true @@ -562,7 +572,13 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, if (isServer) // on the server side conservatively shut everything down if user handler completes prematurely super.onUpstreamFinish() else { // on the client side allow ongoing responses to be delivered for a while even if requests are done - completeIfDone() + // The FIFO control queue preserves any initial request HEADERS already accepted by the demux. + // Push is disabled, so there are no peer-initiated streams to acknowledge, regardless of our own IDs. + if (stage.sendGoAwayOnGracefulClose && !isClosed(frameOut)) { + clientGracefulGoAwaySent = true + // The multiplexer calls completeIfDone when GOAWAY is flushed, possibly during this call. + pushGoAwayFrame(ErrorCode.NO_ERROR, ByteString.empty) + } else completeIfDone() scheduleOnce(CompletionTimeout, completionTimeout) } }) @@ -589,7 +605,8 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, // Fail the stage, rather than only pushing a GOAWAY, so that all active streams are shut down and the // connection is closed. `Http2Blueprint.errorHandling` renders the GOAWAY; pass on the last stream id, // so the peer knows which streams were processed and does not retry them. - failStage(new Http2Compliance.Http2ProtocolException(ex.errorCode, ex.getMessage, lastStreamId())) + failStage(new Http2Compliance.Http2ProtocolException(ex.errorCode, ex.getMessage, + goAwayLastStreamId())) settingsAppliedOk = false } } else { diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/OutgoingConnectionBuilderImpl.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/OutgoingConnectionBuilderImpl.scala index 96ddc75cd..4d711b064 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/OutgoingConnectionBuilderImpl.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/OutgoingConnectionBuilderImpl.scala @@ -97,7 +97,7 @@ private[pekko] object OutgoingConnectionBuilderImpl { override def managedPersistentHttp2(): Flow[HttpRequest, HttpResponse, NotUsed] = PersistentConnection.managedConnection( - http2(), + withoutClientGoAway.http2(), clientConnectionSettings.http2Settings) override def http2WithPriorKnowledge(): Flow[HttpRequest, HttpResponse, Future[OutgoingConnection]] = { @@ -108,9 +108,16 @@ private[pekko] object OutgoingConnectionBuilderImpl { override def managedPersistentHttp2WithPriorKnowledge(): Flow[HttpRequest, HttpResponse, NotUsed] = PersistentConnection.managedConnection( - http2WithPriorKnowledge(), + withoutClientGoAway.http2WithPriorKnowledge(), clientConnectionSettings.http2Settings) + // The wrapper completes its inner request source on both retirement and downstream cancellation. + private def withoutClientGoAway: Impl = + if (clientConnectionSettings.http2Settings.sendGoAwayOnGracefulClose) + copy( + clientConnectionSettings = clientConnectionSettings.mapHttp2Settings(_.withSendGoAwayOnGracefulClose(false))) + else this + override private[pekko] def toJava: JOutgoingConnectionBuilder = new JavaAdapter(this) } diff --git a/http-core/src/main/scala/org/apache/pekko/http/javadsl/settings/Http2ClientSettings.scala b/http-core/src/main/scala/org/apache/pekko/http/javadsl/settings/Http2ClientSettings.scala index 4721b7fdf..11035ad26 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/javadsl/settings/Http2ClientSettings.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/javadsl/settings/Http2ClientSettings.scala @@ -119,6 +119,18 @@ trait Http2ClientSettings { self: scaladsl.settings.Http2ClientSettings.Http2Cli def getCompletionTimeout: Duration = Duration.ofMillis(completionTimeout.toMillis) def withCompletionTimeout(timeout: Duration): Http2ClientSettings = copy(completionTimeout = timeout.toMillis.millis) + /** + * Whether to send GOAWAY on normal request source completion for a direct HTTP/2 connection. + * In-flight requests can still complete within [[getCompletionTimeout]]. Disabled by default. + * + * @since 2.1.0 + */ + def getSendGoAwayOnGracefulClose: Boolean = self.sendGoAwayOnGracefulClose + + /** @since 2.1.0 */ + def withSendGoAwayOnGracefulClose(enabled: Boolean): Http2ClientSettings = + self.withSendGoAwayOnGracefulClose(enabled) + def getBaseConnectionBackoff: Duration = Duration.ofMillis(baseConnectionBackoff.toMillis) def withBaseConnectionBackoff(backoff: Duration): Http2ClientSettings = copy(baseConnectionBackoff = backoff.toMillis.millis) diff --git a/http-core/src/main/scala/org/apache/pekko/http/scaladsl/settings/Http2ServerSettings.scala b/http-core/src/main/scala/org/apache/pekko/http/scaladsl/settings/Http2ServerSettings.scala index 007857a86..261806951 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/scaladsl/settings/Http2ServerSettings.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/scaladsl/settings/Http2ServerSettings.scala @@ -386,6 +386,22 @@ trait Http2ClientSettings extends javadsl.settings.Http2ClientSettings with Http def completionTimeout: FiniteDuration def withCompletionTimeout(timeout: FiniteDuration): Http2ClientSettings = copy(completionTimeout = timeout) + /** + * Whether to send GOAWAY on normal request source completion for a direct HTTP/2 connection. + * In-flight requests can still complete within [[completionTimeout]]. Disabled by default. + * + * @since 2.1.0 + */ + def sendGoAwayOnGracefulClose: Boolean = self.internalSettings match { + case Some(_: Http2ClientSettings.GracefulGoAwayEnabled) => true + case _ => false + } + + /** @since 2.1.0 */ + override def withSendGoAwayOnGracefulClose(enabled: Boolean): Http2ClientSettings = + if (enabled == sendGoAwayOnGracefulClose) this + else copy(internalSettings = Http2ClientSettings.withGracefulGoAway(self.internalSettings, enabled)) + def baseConnectionBackoff: FiniteDuration def withBaseConnectionBackoff(backoff: FiniteDuration): Http2ClientSettings = copy(baseConnectionBackoff = backoff) @@ -441,7 +457,7 @@ trait Http2ClientSettings extends javadsl.settings.Http2ClientSettings with Http private[http] def internalSettings: Option[Http2InternalClientSettings] @InternalApi private[http] def withInternalSettings(newValue: Http2InternalClientSettings): Http2ClientSettings = - copy(internalSettings = Some(newValue)) + copy(internalSettings = Http2ClientSettings.withGracefulGoAway(Some(newValue), sendGoAwayOnGracefulClose)) } @ApiMayChange @@ -449,6 +465,18 @@ object Http2ClientSettings extends SettingsCompanion[Http2ClientSettings] { def apply(config: Config): Http2ClientSettings = Http2ClientSettingsImpl(config) def apply(configOverrides: String): Http2ClientSettings = Http2ClientSettingsImpl(configOverrides) + // Keep the released settings product shape; only opted-in settings need a wrapper. + private final case class GracefulGoAwayEnabled(delegate: Option[Http2InternalClientSettings]) + extends Http2InternalClientSettings + + private def withGracefulGoAway( + settings: Option[Http2InternalClientSettings], + enabled: Boolean): Option[Http2InternalClientSettings] = + settings match { + case Some(GracefulGoAwayEnabled(delegate)) => if (enabled) settings else delegate + case _ => if (enabled) Some(GracefulGoAwayEnabled(settings)) else settings + } + private[http] case class Http2ClientSettingsImpl( maxConcurrentStreams: Int, maxHeaderListSize: Int, @@ -518,7 +546,7 @@ object Http2ClientSettings extends SettingsCompanion[Http2ClientSettings] { frameTypeThrottleCost = c.getInt("frame-type-throttle.cost"), frameTypeThrottleBurst = c.getInt("frame-type-throttle.burst"), frameTypeThrottleInterval = c.getFiniteDuration("frame-type-throttle.interval"), - internalSettings = None // no possibility to configure internal settings with config + internalSettings = withGracefulGoAway(None, c.getBoolean("send-goaway-on-graceful-close")) ) } } diff --git a/http-core/src/test/scala/org/apache/pekko/http/scaladsl/settings/Http2ClientSettingsSpec.scala b/http-core/src/test/scala/org/apache/pekko/http/scaladsl/settings/Http2ClientSettingsSpec.scala index 0c079ef4c..497aa2e66 100644 --- a/http-core/src/test/scala/org/apache/pekko/http/scaladsl/settings/Http2ClientSettingsSpec.scala +++ b/http-core/src/test/scala/org/apache/pekko/http/scaladsl/settings/Http2ClientSettingsSpec.scala @@ -27,6 +27,43 @@ import scala.concurrent.duration._ class Http2ClientSettingsSpec extends PekkoSpec { + "Http2ClientSettings send-goaway-on-graceful-close" should { + "default to false and accept an explicit opt-in" in { + Http2ClientSettings(system).sendGoAwayOnGracefulClose shouldBe false + Http2ClientSettings("pekko.http.client.http2.send-goaway-on-graceful-close = on") + .sendGoAwayOnGracefulClose shouldBe true + } + + "set and read the option through the Java API" in { + val settings: javadsl.settings.Http2ClientSettings = Http2ClientSettings(system) + val enabled = settings.withSendGoAwayOnGracefulClose(true) + enabled.getSendGoAwayOnGracefulClose shouldBe true + enabled.withSendGoAwayOnGracefulClose(false).getSendGoAwayOnGracefulClose shouldBe false + } + + "preserve the setting and its value semantics across ordinary copies" in { + val defaults = Http2ClientSettings(system) + val enabled = defaults.withSendGoAwayOnGracefulClose(true) + val copied = enabled.withMaxConcurrentStreams(17) + copied.sendGoAwayOnGracefulClose shouldBe true + copied.maxConcurrentStreams shouldBe 17 + enabled shouldBe defaults.withSendGoAwayOnGracefulClose(true) + enabled.hashCode shouldBe defaults.withSendGoAwayOnGracefulClose(true).hashCode + enabled.withSendGoAwayOnGracefulClose(false) shouldBe defaults + } + + "retain internal settings when opting in or out" in { + val first = new Http2InternalClientSettings {} + val second = new Http2InternalClientSettings {} + val defaults = Http2ClientSettings(system).withInternalSettings(first) + val enabled = defaults.withSendGoAwayOnGracefulClose(true) + enabled.withSendGoAwayOnGracefulClose(false).internalSettings shouldBe Some(first) + val replaced = enabled.withInternalSettings(second) + replaced.sendGoAwayOnGracefulClose shouldBe true + replaced.withSendGoAwayOnGracefulClose(false).internalSettings shouldBe Some(second) + } + } + "Http2ClientSettings persistent-connection-max-age" should { "be disabled by default" in { 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..1b8d0eefb 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 @@ -1293,6 +1293,85 @@ class Http2ClientSpec extends PekkoSpecWithMaterializer(""" }) } + "send client GOAWAY on graceful close" should { + abstract class Enabled extends TestSetup with NetProbes { + override def settings = super.settings.mapHttp2Settings( + _.withSendGoAwayOnGracefulClose(true).withCompletionTimeout(30.seconds)) + } + + "be disabled by default".inAssertAllStagesStopped(new TestSetup with NetProbes { + user.responseIn.ensureSubscription() + user.requestOut.sendComplete() + expectGracefulCompletion() + }) + + "flush exactly one GOAWAY before completing an idle connection".inAssertAllStagesStopped(new Enabled { + user.responseIn.ensureSubscription() + user.requestOut.sendComplete() + network.expect[GoAwayFrame]() shouldBe GoAwayFrame(0, ErrorCode.NO_ERROR) + expectGracefulCompletion() + }) + + "send accepted request HEADERS before GOAWAY and drain the streaming response".inAssertAllStagesStopped( + new Enabled { + user.emitRequest(Get("https://www.example.com/")) + user.requestOut.sendComplete() + network.expectDecodedResponseHEADERSPairs(1) + network.expect[GoAwayFrame]() shouldBe GoAwayFrame(0, ErrorCode.NO_ERROR) + + network.sendHEADERS(1, endStream = false, Seq(RawHeader(":status", "200"))) + val response = user.expectResponse() + response.status shouldBe StatusCodes.OK + val entity = ByteStringSinkProbe(response.entity.dataBytes) + val body = ByteString("remaining response") + network.sendDATA(1, endStream = true, body) + entity.expectBytes(body) + entity.expectComplete() + user.responseIn.expectComplete() + }) + + "honor the existing completion timeout while an accepted request is pending".inAssertAllStagesStopped( + new Enabled { + override def settings = super.settings.mapHttp2Settings(_.withCompletionTimeout(1.second)) + + user.emitRequest(Get("https://www.example.com/")) + network.expectDecodedResponseHEADERSPairs(1) + user.requestOut.sendComplete() + network.expect[GoAwayFrame]() shouldBe GoAwayFrame(0, ErrorCode.NO_ERROR) + user.responseIn.ensureSubscription() + user.responseIn.expectNoMessage(100.millis) + expectGracefulCompletion() + }) + + "not raise the GOAWAY boundary if keepalive later times out".inAssertAllStagesStopped(new Enabled { + override def settings = super.settings.mapHttp2Settings( + _.withPingInterval(800.millis).withPingTimeout(400.millis)) + + user.emitRequest(Get("https://www.example.com/")) + network.expectDecodedResponseHEADERSPairs(1) + user.requestOut.sendComplete() + network.expect[GoAwayFrame]() shouldBe GoAwayFrame(0, ErrorCode.NO_ERROR) + + network.expectFrame(FrameType.PING, ByteFlag.Zero, 0, ConfigurablePing.Ping.data) + val timedOut = network.expect[GoAwayFrame]() + timedOut.lastStreamId shouldBe 0 + timedOut.errorCode shouldBe ErrorCode.PROTOCOL_ERROR + }) + + "not send a graceful GOAWAY when the response stream is cancelled".inAssertAllStagesStopped(new Enabled { + user.responseIn.cancel() + user.requestOut.expectCancellation() + network.toNet.expectComplete() + }) + + "not send GOAWAY on transport EOF".inAssertAllStagesStopped(new Enabled { + user.responseIn.ensureSubscription() + network.fromNet.sendComplete() + expectGracefulCompletion() + user.requestOut.expectCancellation() + }) + } + "delay stage completion" should { "complete when the last response entity is cancelled after request input completion".inAssertAllStagesStopped(