diff --git a/docs/src/main/paradox/client-side/http2.md b/docs/src/main/paradox/client-side/http2.md index c003a1748..55c032a31 100644 --- a/docs/src/main/paradox/client-side/http2.md +++ b/docs/src/main/paradox/client-side/http2.md @@ -102,6 +102,13 @@ The default maximum age is `infinite`, which disables age-based retirement. The programmatically with `Http2ClientSettings.withPersistentConnectionMaxAge` and `Http2ClientSettings.withPersistentConnectionMaxAgeJitter`. +## Peer stream concurrency + +The peer can limit how many streams the client starts at once, including temporarily allowing none. If that limit +drops while the client has already pulled a request, the client holds the request until the peer allows another stream. +If the connection closes first, the client cancels the held request's streamed entity. The existing completion timeout +still applies if the application completes its request stream while waiting. + ## 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/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 67f10c539..d17368424 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 @@ -44,6 +44,7 @@ import pekko.stream.Attributes import pekko.stream.BidiShape import pekko.stream.Inlet import pekko.stream.Outlet +import pekko.stream.scaladsl.Sink import pekko.stream.scaladsl.Source import pekko.stream.stage.{ GraphStageLogic, @@ -379,7 +380,6 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, } pullFrameIn() - // applyRemoteSettings may or may not have pulled `substreamIn` already tryPullSubStreams() // both client and server must send a settings frame as first frame @@ -418,14 +418,36 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, def pullFrameIn(): Unit = if (allowReadingIncomingFrames && !hasBeenPulled(frameIn) && !isClosed(frameIn)) pull(frameIn) + // The stage owns the pulled request and its unmaterialized entity until admission or shutdown. + private var pendingSubstream: OptionVal[Http2SubStream] = OptionVal.None + private var resumingPendingSubstream = false + private lazy val resumePendingSubstream = getAsyncCallback[Unit] { _ => + resumingPendingSubstream = false + if (pendingSubstream.isDefined && hasCapacityToCreateStreams) { + val sub = pendingSubstream.get + pendingSubstream = OptionVal.None + admitOutgoingSubstream(sub) + } + } + def tryPullSubStreams(): Unit = { - if (!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) + if (!hasBeenPulled(substreamIn) && (isServer || hasCapacityToCreateStreams)) { + // Only clients initiate streams. One pulled request may already be waiting for capacity. + if (pendingSubstream.isDefined) { + // Capacity can return while another stream is being closed. Do not re-enter its state machine. + if (!resumingPendingSubstream) { + resumingPendingSubstream = true + resumePendingSubstream.invoke(()) + } + } else if (!isClosed(substreamIn)) pull(substreamIn) } } + private def admitOutgoingSubstream(sub: Http2SubStream): Unit = { + handleOutgoingCreated(sub) + tryPullSubStreams() + } + // ----------------------------------------------------------------- setHandler(frameIn, new InHandler { @@ -461,7 +483,8 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, case SettingsFrame(settings) => if (settings.nonEmpty) debug(s"Got ${settings.length} settings!") - multiplexer.applyAndAcknowledgeSettings(settings)(applyRemoteSettings(settings)) + if (multiplexer.applyAndAcknowledgeSettings(settings)(applyRemoteSettings(settings))) + tryPullSubStreams() case SettingsAckFrame(_) => // Currently, we only expect an ack for the initial settings frame, sent @@ -522,7 +545,8 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, override def onAllDataFlushed(): Unit = completeIfDone() private def completeIfDone(): Unit = { - val noMoreOutgoingStreams = (terminating || isClosed(substreamIn)) && activeStreamCount() == 0 + val noMoreOutgoingStreams = + (terminating || (isClosed(substreamIn) && pendingSubstream.isEmpty)) && activeStreamCount() == 0 def allOutgoingDataFlushed = isClosed(frameOut) || multiplexer.hasFlushedAllData if (noMoreOutgoingStreams && allOutgoingDataFlushed) { log.debug("Closing connection after all streams are done and all data has been flushed.") @@ -550,9 +574,10 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, new InHandler { def onPush(): Unit = { val sub = grab(substreamIn) - handleOutgoingCreated(sub) - // Once the incoming stream is handled, we decide if we need to pull more. - tryPullSubStreams() + // SETTINGS can lower the peer's limit after we have pulled. Keep that single request until + // a SETTINGS update or a closed stream permits opening it. + if (isServer || hasCapacityToCreateStreams) admitOutgoingSubstream(sub) + else pendingSubstream = OptionVal.Some(sub) } override def onUpstreamFinish(): Unit = @@ -597,8 +622,6 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, multiplexer.updateMaxFrameSize(value) case Setting(Http2Protocol.SettingIdentifier.SETTINGS_MAX_CONCURRENT_STREAMS, value) => setMaxConcurrentStreams(value) - // once maxConcurrentStreams is updated, see if we can pull again - tryPullSubStreams() case Setting(id, value) => debug(s"Ignoring setting $id -> $value (in Demux)") } @@ -642,8 +665,17 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings, } override def postStop(): Unit = { - shutdownStreamHandling() - terminationPromise.success(Http.HttpConnectionTerminated) + try { + if (pendingSubstream.isDefined) { + val sub = pendingSubstream.get + pendingSubstream = OptionVal.None + // Admission never materialized this entity. Cancel it outside the stopping stage's interpreter. + sub.data.foreach(_.runWith(Sink.cancelled)(materializer)) + } + } finally { + shutdownStreamHandling() + terminationPromise.success(Http.HttpConnectionTerminated) + } } } (Logic, Logic) 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 72462d7df..9acb6b8fc 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 @@ -34,8 +34,11 @@ import pekko.stream.stage.StageLogging private[http2] trait Http2Multiplexer { def pushControlFrame(frame: FrameEvent): Unit - /** Applies received SETTINGS in order, acknowledging only a successful application before sending pending DATA. */ - def applyAndAcknowledgeSettings(settings: Seq[Setting])(applySettings: => Boolean): Unit + /** + * Applies received SETTINGS in order, acknowledging only a successful application before sending pending DATA. + * Returns true if the settings were acknowledged. + */ + def applyAndAcknowledgeSettings(settings: Seq[Setting])(applySettings: => Boolean): Boolean def updateConnectionLevelWindow(increment: Int): Boolean def updateMaxFrameSize(newMaxFrameSize: Int): Unit def updateDefaultWindow(newDefaultWindow: Int): Unit @@ -120,7 +123,7 @@ private[http2] trait Http2MultiplexerSupport { logic: GraphStageLogic with Stage private var applyingPeerSettings = false - override def applyAndAcknowledgeSettings(settings: Seq[Setting])(applySettings: => Boolean): Unit = { + override def applyAndAcknowledgeSettings(settings: Seq[Setting])(applySettings: => Boolean): Boolean = { applyingPeerSettings = true val applied = try applySettings finally applyingPeerSettings = false @@ -128,6 +131,7 @@ private[http2] trait Http2MultiplexerSupport { logic: GraphStageLogic with Stage // A window change can make pending DATA eligible. The ACK consumes existing demand via the // normal control-frame path before any DATA made eligible by these settings. if (applied) pushControlFrame(SettingsAckFrame(settings)) + applied } def updateConnectionLevelWindow(increment: Int): Boolean = { 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 b0b093ba7..cf5de9260 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 @@ -14,6 +14,7 @@ package org.apache.pekko.http.impl.engine.http2 import java.io.IOException +import java.net.InetSocketAddress import javax.net.ssl.SSLContext import scala.concurrent.ExecutionContext @@ -24,6 +25,7 @@ import scala.util.control.NonFatal import org.apache.pekko import pekko.NotUsed +import pekko.actor.ActorSystem import pekko.event.Logging import pekko.http.impl.engine.http2.FrameEvent._ import pekko.http.impl.engine.http2.Http2Protocol.ErrorCode @@ -34,6 +36,8 @@ import pekko.http.impl.engine.server.HttpAttributes import pekko.http.impl.engine.ws.ByteStringSinkProbe import pekko.http.impl.util.LogByteStringTools import pekko.http.impl.util.PekkoSpecWithMaterializer +import pekko.http.scaladsl.ClientTransport +import pekko.http.scaladsl.Http import pekko.http.scaladsl.client.RequestBuilding.Get import pekko.http.scaladsl.client.RequestBuilding.Post import pekko.http.scaladsl.model._ @@ -957,6 +961,81 @@ class Http2ClientSpec extends PekkoSpecWithMaterializer(""" network.expect[HeadersFrame]().streamId shouldBe 11 network.expect[HeadersFrame]().streamId shouldBe 13 }) + def withPendingRequestAtZero(request: HttpRequest)( + verify: (NetworkSide, TestSubscriber.Probe[HttpResponse]) => Unit): Unit = { + val frames = Http2FrameProbe() + val fromPeer = TestPublisher.probe[ByteString]() + val network = new NetworkSide(fromPeer, frames.plainDataProbe, frames) + val transport = new ClientTransport { + override def connectTo(host: String, port: Int, settings: ClientConnectionSettings)( + implicit system: ActorSystem): Flow[ByteString, ByteString, Future[Http.OutgoingConnection]] = { + val local = new InetSocketAddress(0) + val remote = InetSocketAddress.createUnresolved(host, port) + Flow.fromSinkAndSource(network.toNet.sink, Source.fromPublisher(fromPeer)) + .mapMaterializedValue(_ => Future.successful(Http.OutgoingConnection(local, remote))) + } + } + val requestSeen = Promise[Unit]() + val requests = TestPublisher.probe[HttpRequest]() + val responses = TestSubscriber.probe[HttpResponse]() + val settings = ClientConnectionSettings(system) + .mapHttp2Settings(_.withCompletionTimeout(5.seconds)) + .withTransport(transport) + val client = + Http().connectionTo("www.example.com").withClientConnectionSettings(settings).http2WithPriorKnowledge() + Source.fromPublisher(requests).map { request => + requestSeen.success(()) + request + }.via(client).runWith(Sink.fromSubscriber(responses)) + + try { + val limit = SettingIdentifier.SETTINGS_MAX_CONCURRENT_STREAMS + network.toNet.expectBytes(Http2Protocol.ClientConnectionPreface) + network.expectSETTINGS() + network.sendSETTING(limit, 0) + network.expectSettingsAck() + + requests.sendNext(request) + requestSeen.future.futureValue(Timeout(remainingOrDefault), Interval(10.millis)) + requests.sendComplete() + + // The request reached the client flow, but only SETTINGS may be acknowledged at zero capacity. + network.sendFrame(SettingsFrame(Nil)) + network.expectSettingsAck() + verify(network, responses) + } finally network.toNet.cancel() + } + + "keep a request pending while the peer allows zero streams and send it when capacity returns" in + StreamTestKit.assertAllStagesStopped { + withPendingRequestAtZero(Get("http://www.example.com/pending")) { (network, responses) => + network.sendSETTING(SettingIdentifier.SETTINGS_MAX_CONCURRENT_STREAMS, 1) + network.expectSettingsAck() + + val headers = network.expectDecodedResponseHEADERSPairs(1) + headers should contain(":method" -> "GET") + headers should contain(":path" -> "/pending") + network.sendHEADERS(1, endStream = true, Seq(RawHeader(":status", "200"))) + responses.requestNext().status shouldBe StatusCodes.OK + responses.expectComplete() + network.toNet.expectComplete() + } + } + + "cancel the held request entity if the peer closes normally before capacity returns" in + StreamTestKit.assertAllStagesStopped { + val body = TestPublisher.probe[ByteString]() + val request = Post("http://www.example.com/pending-upload", + HttpEntity(ContentTypes.`application/octet-stream`, Source.fromPublisher(body))) + withPendingRequestAtZero(request) { (network, responses) => + responses.request(1) + network.fromNet.sendComplete() + responses.expectComplete() + network.toNet.expectComplete() + body.expectCancellation() + } + } + "pull the next request when a cancelled response entity frees a stream slot".inAssertAllStagesStopped( new TestSetup(Setting(SettingIdentifier.SETTINGS_MAX_CONCURRENT_STREAMS, 1)) with NetProbes { val request = HttpRequest(uri = "https://www.example.com/")