diff --git a/docs/src/main/paradox/client-side/http2.md b/docs/src/main/paradox/client-side/http2.md index c003a17482..8efbcf7bc8 100644 --- a/docs/src/main/paradox/client-side/http2.md +++ b/docs/src/main/paradox/client-side/http2.md @@ -102,6 +102,21 @@ The default maximum age is `infinite`, which disables age-based retirement. The programmatically with `Http2ClientSettings.withPersistentConnectionMaxAge` and `Http2ClientSettings.withPersistentConnectionMaxAgeJitter`. +## HTTP/2 stream identifier exhaustion + +HTTP/2 stream identifiers cannot be reused on a connection. When a direct HTTP/2 connection flow (TLS or prior +knowledge) allocates its last request stream identifier, it cancels the request input with a +`org.apache.pekko.http.scaladsl.model.http2.StreamIdExhaustedException` and lets in-flight responses drain within +`pekko.http.client.http2.completion-timeout`. The cancellation is not an error on the response stream. + +Use the request source's `watchTermination` immediately before the connection flow to observe this cancellation. +The materialized @scala[`Future`]@java[`CompletionStage`] fails with the exception if the request source was +still open. A queue's successful offer only means the request was buffered upstream, not that it was assigned +to this connection. Correlate the assigned responses and create a new connection for further requests. + +The managed persistent variants retire the exhausted connection and establish a replacement for subsequent unassigned +requests. They do not replay requests already assigned to the old connection. + ## Request-response ordering For HTTP/2 connections the responses are not guaranteed to arrive in the same order that the requests were emitted to diff --git a/docs/src/main/paradox/compatibility-guidelines.md b/docs/src/main/paradox/compatibility-guidelines.md index 9366e09ab8..a23cc0c2f7 100644 --- a/docs/src/main/paradox/compatibility-guidelines.md +++ b/docs/src/main/paradox/compatibility-guidelines.md @@ -95,6 +95,7 @@ Scala org.apache.pekko.http.scaladsl.model.headers.Trailer org.apache.pekko.http.scaladsl.model.http2.PeerClosedStreamException org.apache.pekko.http.scaladsl.model.http2.Http2Exception + org.apache.pekko.http.scaladsl.model.http2.StreamIdExhaustedException org.apache.pekko.http.scaladsl.model.SimpleRequestResponseAttribute org.apache.pekko.http.scaladsl.model.RequestResponseAssociation ``` diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2Blueprint.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2Blueprint.scala index 7eb21f0d3a..0ef2d7b3e0 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2Blueprint.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2Blueprint.scala @@ -199,10 +199,17 @@ private[http] object Http2Blueprint { def httpLayerClient(masterHttpHeaderParser: HttpHeaderParser, settings: ClientConnectionSettings, log: LoggingAdapter, connectionScheme: String, connectionAuthority: Uri.Authority) : BidiFlow[HttpRequest, Http2SubStream, Http2SubStream, HttpResponse, NotUsed] = + httpLayerClient(masterHttpHeaderParser, settings, log, connectionScheme, connectionAuthority, ClientStreamIds.First) + + private[http2] def httpLayerClient( + masterHttpHeaderParser: HttpHeaderParser, + settings: ClientConnectionSettings, + log: LoggingAdapter, + connectionScheme: String, + connectionAuthority: Uri.Authority, + firstStreamId: Int): BidiFlow[HttpRequest, Http2SubStream, Http2SubStream, HttpResponse, NotUsed] = BidiFlow.fromFlows( - Flow[HttpRequest].statefulMap(() => - new RequestRendering(settings, log, connectionScheme, connectionAuthority))((renderer, request) => - (renderer, renderer(request)), _ => None), + Flow.fromGraph(new ClientRequestRendering(settings, log, connectionScheme, connectionAuthority, firstStreamId)), StreamUtils.statefulAttrsMap[Http2SubStream, HttpResponse] { attrs => val headerParser = masterHttpHeaderParser.createShallowCopy() stream => ResponseParsing.parseResponse(headerParser, settings.parserSettings, attrs)(stream) diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/HttpMessageRendering.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/HttpMessageRendering.scala index e2af68077c..b674f94927 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/HttpMessageRendering.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/HttpMessageRendering.scala @@ -13,8 +13,6 @@ package org.apache.pekko.http.impl.engine.http2 -import java.util.concurrent.atomic.AtomicInteger - import scala.collection.immutable.VectorBuilder import org.apache.pekko @@ -24,8 +22,11 @@ import pekko.http.impl.engine.http2.FrameEvent.ParsedHeadersFrame import pekko.http.impl.engine.rendering.DateHeaderRendering import pekko.http.scaladsl.model._ import pekko.http.scaladsl.model.headers.{ Host, `Raw-Request-URI` } +import pekko.http.scaladsl.model.http2.StreamIdExhaustedException import pekko.http.scaladsl.settings.ClientConnectionSettings import pekko.http.scaladsl.settings.ServerSettings +import pekko.stream.stage.{ GraphStage, GraphStageLogic, InHandler, OutHandler } +import pekko.stream.{ Attributes, FlowShape, Inlet, Outlet } import pekko.util.OptionVal /** INTERNAL API */ @@ -61,15 +62,73 @@ private[http2] class ResponseRendering(settings: ServerSettings, val log: Loggin } +private[http2] object ClientStreamIds { + // RFC 9113 ยง5.1.1: client-initiated stream IDs are positive, odd, and never reused on a connection. + final val First = 1 + final val Last = Int.MaxValue + + def remainingFrom(firstStreamId: Int): Int = { + require(firstStreamId > 0 && (firstStreamId & 1) == 1) + (Last - firstStreamId) / 2 + 1 + } + + final class Allocator(firstStreamId: Int) { + require(firstStreamId > 0 && (firstStreamId & 1) == 1) + // Keep the exhausted state outside the Int range, without wrapping or resetting the connection's allocation. + private var nextId: Long = firstStreamId.toLong + + def next(): Int = { + if (nextId > Last) throw new IllegalStateException("No HTTP/2 client stream IDs remain on this connection") + val allocated = nextId.toInt + nextId += 2 + allocated + } + } +} + +private[http2] final class ClientRequestRendering( + settings: ClientConnectionSettings, log: LoggingAdapter, + connectionScheme: String, connectionAuthority: Uri.Authority, firstStreamId: Int) + extends GraphStage[FlowShape[HttpRequest, Http2SubStream]] { + + private val in = Inlet[HttpRequest]("Http2ClientRequestRendering.in") + private val out = Outlet[Http2SubStream]("Http2ClientRequestRendering.out") + override val shape: FlowShape[HttpRequest, Http2SubStream] = FlowShape(in, out) + + override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = + new GraphStageLogic(shape) with InHandler with OutHandler { + // The renderer and its allocator belong to this physical connection, not to a restartable map operator. + private val render = new RequestRendering(settings, log, connectionScheme, connectionAuthority, firstStreamId) + setHandlers(in, out, this) + + override def onPull(): Unit = pull(in) + + override def onPush(): Unit = { + val substream = render(grab(in)) + push(out, substream) + if (substream.streamId == ClientStreamIds.Last) { + // Report retirement to the request producer without failing the response stream. A failure on the + // response side could discard already delivered responses still in downstream buffers. + cancel(in, new StreamIdExhaustedException) + complete(out) + } + } + } +} + /** INTERNAL API */ @InternalApi private[http2] class RequestRendering( settings: ClientConnectionSettings, val log: LoggingAdapter, - connectionScheme: String = "", connectionAuthority: Uri.Authority = Uri.Authority.Empty) + connectionScheme: String, connectionAuthority: Uri.Authority, firstStreamId: Int) extends MessageRendering[HttpRequest] { - private val streamId = new AtomicInteger(1) - protected override def nextStreamId(r: HttpRequest): Int = streamId.getAndAdd(2) + def this(settings: ClientConnectionSettings, log: LoggingAdapter, + connectionScheme: String = "", connectionAuthority: Uri.Authority = Uri.Authority.Empty) = + this(settings, log, connectionScheme, connectionAuthority, ClientStreamIds.First) + + private val streamIds = new ClientStreamIds.Allocator(firstStreamId) + protected override def nextStreamId(r: HttpRequest): Int = streamIds.next() protected override def initialHeaderPairs(request: HttpRequest): VectorBuilder[(String, String)] = { val headerPairs = new VectorBuilder[(String, String)]() 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..683924fcaf 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.ClientStreamIds import pekko.http.scaladsl.Http.OutgoingConnection import pekko.http.scaladsl.model.{ AttributeKey, HttpRequest, HttpResponse, RequestResponseAssociation, StatusCodes } import pekko.http.scaladsl.settings.Http2ClientSettings @@ -57,12 +58,19 @@ private[http2] object PersistentConnection { */ def managedConnection(connectionFlow: Flow[HttpRequest, HttpResponse, Future[OutgoingConnection]], settings: Http2ClientSettings): Flow[HttpRequest, HttpResponse, NotUsed] = + managedConnection(connectionFlow, settings, ClientStreamIds.First) + + private[http2] def managedConnection( + connectionFlow: Flow[HttpRequest, HttpResponse, Future[OutgoingConnection]], + settings: Http2ClientSettings, + firstStreamId: Int): Flow[HttpRequest, HttpResponse, NotUsed] = Flow.fromGraph(new Stage(connectionFlow, settings.maxPersistentAttempts match { case 0 => None case n => Some(n) }, settings.baseConnectionBackoff, settings.maxConnectionBackoff, - settings.persistentConnectionMaxAge, settings.persistentConnectionMaxAgeJitter)) + settings.persistentConnectionMaxAge, settings.persistentConnectionMaxAgeJitter, + ClientStreamIds.remainingFrom(firstStreamId))) private class AssociationTag extends RequestResponseAssociation private val associationTagKey = AttributeKey[AssociationTag]("PersistentConnection.associationTagKey") @@ -73,7 +81,7 @@ private[http2] object PersistentConnection { private class Stage(connectionFlow: Flow[HttpRequest, HttpResponse, Future[OutgoingConnection]], maxAttempts: Option[Int], baseEmbargo: FiniteDuration, _maxBackoff: FiniteDuration, - persistentConnectionMaxAge: Duration, persistentConnectionMaxAgeJitter: Double) + persistentConnectionMaxAge: Duration, persistentConnectionMaxAgeJitter: Double, requestsPerConnection: Int) extends GraphStage[FlowShape[HttpRequest, HttpResponse]] { val requestIn = Inlet[HttpRequest]("PersistentConnection.requestIn") val responseOut = Outlet[HttpResponse]("PersistentConnection.responseOut") @@ -138,6 +146,11 @@ private[http2] object PersistentConnection { override def onPush(): Unit = () // Pull might have happened before the connection failed. Element is kept in slot. + override def onUpstreamFinish(): Unit = + // The final request can arrive in the inlet just before its source completes. It still belongs to this + // connection attempt, including when this is a replacement for a retired connection. + if (!isAvailable(requestIn)) completeStage() + override def onPull(): Unit = { if (!isAvailable(requestIn) && !isClosed(requestIn) && !hasBeenPulled(requestIn)) // requestIn might already have been pulled when we failed and went back to Unconnected pull(requestIn) @@ -148,7 +161,8 @@ private[http2] object PersistentConnection { currentConnection = Some(newState) become(newState) if (requestOutPulled) { - if (isAvailable(requestIn)) newState.dispatchRequest(grab(requestIn)) + if (isAvailable(requestIn)) newState.dispatchBufferedRequest() + else if (isClosed(requestIn)) requestOut.complete() else if (!hasBeenPulled(requestIn)) pull(requestIn) } } @@ -211,6 +225,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 remainingRequests = requestsPerConnection persistentConnectionMaxAge match { case age: FiniteDuration => @@ -226,10 +241,8 @@ private[http2] object PersistentConnection { requestOut.setHandler(new OutHandler { override def onPull(): Unit = - if (isAvailable(requestIn)) { - dispatchRequest(grab(requestIn)) - if (isClosed(requestIn)) requestOut.complete() - } else if (isClosed(requestIn)) requestOut.complete() + if (isAvailable(requestIn)) dispatchBufferedRequest() + else if (isClosed(requestIn)) requestOut.complete() else if (!hasBeenPulled(requestIn)) pull(requestIn) override def onDownstreamFinish(cause: Throwable): Unit = onDisconnected() @@ -270,10 +283,13 @@ private[http2] object PersistentConnection { } } - def retire(): Unit = + def retire(): Unit = retire("configured maximum age reached") + + private def retire(reason: String): Unit = if (!retiring) { retiring = true - log.debug("Persistent HTTP/2 connection reached its configured maximum age, retiring it") + cancelTimer(MaxConnectionAgeReached) + log.debug("Retiring persistent HTTP/2 connection: {}", reason) setHandler(requestIn, new InHandler { override def onPush(): Unit = () // keep at most one next request in the inlet slot @@ -286,7 +302,12 @@ private[http2] object PersistentConnection { requestOut.complete() } - def dispatchRequest(req: HttpRequest): Unit = { + def dispatchBufferedRequest(): Unit = { + dispatchRequest(grab(requestIn)) + if (!retiring && isClosed(requestIn)) requestOut.complete() + } + + private def dispatchRequest(req: HttpRequest): Unit = { val tag = new AssociationTag // Some cross-compilation woes here: // Explicit type ascription is needed to make both 2.12 and 2.13 compile. @@ -295,6 +316,10 @@ private[http2] object PersistentConnection { case (key, value: RequestResponseAssociation) => key -> value }: PartialFunction[(AttributeKey[?], Any), (AttributeKey[?], RequestResponseAssociation)])) requestOut.push(req.addAttribute(associationTagKey, tag)) + remainingRequests -= 1 + // Close the inner request side ourselves after its final allotment, before its cancellation could be + // mistaken for a connection failure. Unassigned requests stay on the outer side for its replacement. + if (remainingRequests == 0) retire("client stream IDs exhausted") } override def onPush(): Unit = dispatchRequest(grab(requestIn)) diff --git a/http-core/src/main/scala/org/apache/pekko/http/scaladsl/model/http2/Http2Exception.scala b/http-core/src/main/scala/org/apache/pekko/http/scaladsl/model/http2/Http2Exception.scala index 98ce8c1afc..fe9758722d 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/scaladsl/model/http2/Http2Exception.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/scaladsl/model/http2/Http2Exception.scala @@ -35,3 +35,14 @@ class PeerClosedStreamException(val streamId: Int, val errorCode: String, val nu with NoStackTrace { private[http] def this(streamId: Int, errorCode: ErrorCode) = this(streamId, errorCode.toString, errorCode.id) } + +/** + * A direct HTTP/2 client connection has used all of its locally available stream identifiers. Create a new + * connection for subsequent requests. A request that was only buffered upstream may not have been assigned. + * + * @since 2.1.0 + */ +@ApiMayChange +final class StreamIdExhaustedException + extends Http2Exception("No HTTP/2 client stream identifiers remain; create a new connection") + with NoStackTrace 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..8ad453856f 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,8 @@ package org.apache.pekko.http.impl.engine.http2 import java.io.IOException +import java.net.InetSocketAddress +import java.util.concurrent.atomic.AtomicBoolean import javax.net.ssl.SSLContext import scala.concurrent.ExecutionContext @@ -22,17 +24,21 @@ import scala.concurrent.Promise import scala.concurrent.duration._ import org.apache.pekko +import pekko.Done import pekko.NotUsed import pekko.event.Logging import pekko.http.impl.engine.http2.FrameEvent._ import pekko.http.impl.engine.http2.Http2Protocol.ErrorCode import pekko.http.impl.engine.http2.Http2Protocol.FrameType import pekko.http.impl.engine.http2.Http2Protocol.SettingIdentifier +import pekko.http.impl.engine.http2.client.PersistentConnection import pekko.http.impl.engine.http2.framing.FrameRenderer +import pekko.http.impl.engine.parsing.HttpHeaderParser 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.Http import pekko.http.scaladsl.client.RequestBuilding.Get import pekko.http.scaladsl.client.RequestBuilding.Post import pekko.http.scaladsl.model._ @@ -51,12 +57,15 @@ import pekko.http.scaladsl.model.headers.{ RawHeader } import pekko.http.scaladsl.model.headers.CacheDirectives._ +import pekko.http.scaladsl.model.http2.StreamIdExhaustedException import pekko.http.scaladsl.settings.ClientConnectionSettings import pekko.stream.Attributes import pekko.stream.Attributes.LogLevels import pekko.stream.OverflowStrategy +import pekko.stream.QueueOfferResult import pekko.stream.scaladsl.BidiFlow import pekko.stream.scaladsl.Flow +import pekko.stream.scaladsl.Keep import pekko.stream.scaladsl.Sink import pekko.stream.scaladsl.Source import pekko.stream.testkit.TestPublisher @@ -65,6 +74,7 @@ import pekko.stream.testkit.scaladsl.StreamTestKit import pekko.stream.testkit.scaladsl.TestSink import pekko.testkit.EventFilter import pekko.testkit.TestDuration +import pekko.testkit.TestProbe import pekko.util.ByteString import org.scalatest.concurrent.Eventually @@ -88,6 +98,204 @@ class Http2ClientSpec extends PekkoSpecWithMaterializer(""" override implicit val patience: PatienceConfig = PatienceConfig(5.seconds, 5.seconds) override def failOnSevereMessages: Boolean = true + "HTTP/2 client stream ID exhaustion" should { + val lastId = ClientStreamIds.Last + val penultimateId = lastId - 2 + + "allocate the final positive client ID once and keep exhaustion sticky" in { + val ids = new ClientStreamIds.Allocator(penultimateId) + ClientStreamIds.remainingFrom(ClientStreamIds.First) shouldBe 1073741824 + ClientStreamIds.remainingFrom(penultimateId) shouldBe 2 + ids.next() shouldBe penultimateId + ids.next() shouldBe Int.MaxValue + intercept[IllegalStateException](ids.next()) + intercept[IllegalStateException](ids.next()) + new ClientStreamIds.Allocator(ClientStreamIds.First).next() shouldBe 1 + } + + "close the direct request queue and drain both assigned responses, including a streaming entity" in + StreamTestKit.assertAllStagesStopped { + val peer = new StreamIdTestPeer(penultimateId) + val output = TestSubscriber.probe[HttpResponse]() + val (queue, source) = Source.queue[HttpRequest](4, OverflowStrategy.backpressure).preMaterialize() + queue.offer(HttpRequest(uri = "/older")).futureValue shouldBe QueueOfferResult.Enqueued + queue.offer(HttpRequest(uri = "/last")).futureValue shouldBe QueueOfferResult.Enqueued + // The queue accepted this locally before the connection even subscribed. That isn't protocol admission. + queue.offer(HttpRequest(uri = "/not-assigned")).futureValue shouldBe QueueOfferResult.Enqueued + val requestTermination = source.watchTermination(Keep.right) + .via(peer.flow).to(Sink.fromSubscriber(output)).run() + output.request(1) + + peer.expectSettings() + peer.expectRequest(penultimateId, "/older") + peer.expectRequest(lastId, "/last") + requestTermination.failed.futureValue shouldBe a[StreamIdExhaustedException] + queue.watchCompletion().futureValue shouldBe Done + peer.acceptSettings() + peer.respond(lastId, "201", endStream = false) + val response = output.expectNext() + response.status shouldBe StatusCodes.Created + val payload = response.entity.dataBytes.runFold(ByteString.empty)(_ ++ _) + peer.fromPeer.sendNext(DataFrame(lastId, endStream = true, ByteString("last response"))) + payload.futureValue shouldBe ByteString("last response") + peer.respond(penultimateId, "200", endStream = true) + // Even after the transport closes, deliver the response buffered for downstream demand. + // No response is invented for the upstream-only queue item. + peer.toPeer.expectComplete() + peer.fromPeer.expectCancellation() + output.requestNext().status shouldBe StatusCodes.OK + output.expectComplete() + } + + "bound a direct exhaustion drain by the existing completion timeout" in + StreamTestKit.assertAllStagesStopped { + val peer = new StreamIdTestPeer(lastId, 500.millis) + val input = TestPublisher.probe[HttpRequest]() + val output = TestSubscriber.probe[HttpResponse]() + val requestTermination = Source.fromPublisher(input).watchTermination(Keep.right) + .via(peer.flow).to(Sink.fromSubscriber(output)).run() + output.request(1) + peer.expectSettings() + input.sendNext(HttpRequest(uri = "/last")) + peer.expectRequest(lastId, "/last") + requestTermination.failed.futureValue shouldBe a[StreamIdExhaustedException] + input.expectCancellation() + // The peer leaves the last assigned request open, so only the existing timeout can end the drain. + output.expectComplete() + peer.toPeer.expectComplete() + peer.fromPeer.expectCancellation() + } + + "preserve an ordinary transport failure during a direct exhaustion drain" in + StreamTestKit.assertAllStagesStopped { + val peer = new StreamIdTestPeer(lastId) + val input = TestPublisher.probe[HttpRequest]() + val output = TestSubscriber.probe[HttpResponse]() + val requestTermination = Source.fromPublisher(input).watchTermination(Keep.right) + .via(peer.flow).to(Sink.fromSubscriber(output)).run() + output.request(1) + peer.expectSettings() + input.sendNext(HttpRequest(uri = "/last")) + peer.expectRequest(lastId, "/last") + requestTermination.failed.futureValue shouldBe a[StreamIdExhaustedException] + input.expectCancellation() + val cause = new IOException("Transport stopped") + peer.fromPeer.sendError(cause) + output.expectError() shouldBe cause + peer.toPeer.expectError() shouldBe cause + } + + "leave ordinary direct request-source completion unchanged before exhaustion" in + StreamTestKit.assertAllStagesStopped { + val firstId = ClientStreamIds.First + val peer = new StreamIdTestPeer(firstId) + val input = TestPublisher.probe[HttpRequest]() + val output = TestSubscriber.probe[HttpResponse]() + val requestTermination = Source.fromPublisher(input).watchTermination(Keep.right) + .via(peer.flow).to(Sink.fromSubscriber(output)).run() + output.request(1) + peer.expectSettings() + input.sendNext(HttpRequest(uri = "/ordinary")) + peer.expectRequest(firstId, "/ordinary") + input.sendComplete() + requestTermination.futureValue shouldBe Done + peer.acceptSettings() + peer.respond(firstId, "200", endStream = true) + output.expectNext().status shouldBe StatusCodes.OK + output.expectComplete() + peer.toPeer.expectComplete() + peer.fromPeer.expectCancellation() + } + + "hand the managed connection's queued request to a replacement without replaying assigned requests" in + StreamTestKit.assertAllStagesStopped { + val connections = TestProbe() + val firstConnection = new AtomicBoolean(true) + val address = new InetSocketAddress("localhost", 12345) + val connected = Http.OutgoingConnection(address, address) + val replacementConnected = Promise[Http.OutgoingConnection]() + val connectionFlow = Flow.fromMaterializer { (_, _) => + val first = firstConnection.getAndSet(false) + val firstId = if (first) penultimateId else ClientStreamIds.First + val peer = new StreamIdTestPeer(firstId) + connections.ref ! peer + peer.flow.mapMaterializedValue(_ => if (first) Future.successful(connected) else replacementConnected.future) + }.mapMaterializedValue(_.flatten) + + val settings = ClientConnectionSettings(system) + val output = TestSubscriber.probe[HttpResponse]() + val queue = Source.queue[HttpRequest](4, OverflowStrategy.backpressure) + .via(PersistentConnection.managedConnection(connectionFlow, settings.http2Settings, penultimateId)) + .to(Sink.fromSubscriber(output)).run() + + output.request(3) + queue.offer(HttpRequest(method = HttpMethods.POST, uri = "/older")).futureValue shouldBe QueueOfferResult.Enqueued + queue.offer(HttpRequest(uri = "/last")).futureValue shouldBe QueueOfferResult.Enqueued + queue.offer(HttpRequest(uri = "/next")).futureValue shouldBe QueueOfferResult.Enqueued + queue.complete() + + val previous = connections.expectMsgType[StreamIdTestPeer] + previous.expectSettings() + previous.expectRequest(penultimateId, "/older") + previous.expectRequest(lastId, "/last") + previous.acceptSettings() + connections.expectNoMessage(100.millis) + previous.respond(lastId, "201", endStream = true) + previous.respond(penultimateId, "200", endStream = true) + output.expectNext().status shouldBe StatusCodes.Created + output.expectNext().status shouldBe StatusCodes.OK + previous.toPeer.expectComplete() + previous.fromPeer.expectCancellation() + + val replacement = connections.expectMsgType[StreamIdTestPeer] + replacement.expectSettings() + replacement.acceptSettings() + // The outer queue finishes while the replacement is still connecting. Its last element belongs to that + // pending connection attempt, not the retired connection and not a third connection. + queue.watchCompletion().futureValue shouldBe Done + output.expectNoMessage(100.millis) + replacementConnected.success(connected) + replacement.expectRequest(ClientStreamIds.First, "/next") + replacement.respond(ClientStreamIds.First, "204", endStream = true) + output.expectNext().status shouldBe StatusCodes.NoContent + output.expectComplete() + replacement.toPeer.expectComplete() + replacement.fromPeer.expectCancellation() + } + } + + private final class StreamIdTestPeer(firstStreamId: Int, completionTimeout: FiniteDuration = 5.seconds) { + private val settings = ClientConnectionSettings(system) + private val parser = HttpHeaderParser(settings.parserSettings, system.log) + private val http2Settings = settings.http2Settings.withCompletionTimeout(completionTimeout) + .withIncomingConnectionLevelBufferSize(Http2Protocol.InitialWindowSize) + .withIncomingStreamLevelBufferSize(Http2Protocol.InitialWindowSize) + val fromPeer = TestPublisher.probe[FrameEvent]() + val toPeer = TestSubscriber.probe[FrameEvent]() + private val transport = Flow.fromSinkAndSource(Sink.fromSubscriber(toPeer), Source.fromPublisher(fromPeer)) + val flow: Flow[HttpRequest, HttpResponse, NotUsed] = + Http2Blueprint.httpLayerClient(parser, settings, system.log, "https", Uri.Authority.Empty, firstStreamId) + .atop(Http2Blueprint.clientDemux(http2Settings, parser)) + .join(transport) + .addAttributes(Http.cancellationStrategyAttributeForDelay(settings.streamCancellationDelay)) + + def expectSettings(): Unit = toPeer.requestNext() shouldBe a[SettingsFrame] + + def acceptSettings(): Unit = { + fromPeer.sendNext(SettingsFrame(Nil)) + toPeer.requestNext() shouldBe SettingsAckFrame(Nil) + } + + def expectRequest(id: Int, path: String): Unit = { + val headers = toPeer.requestNext().asInstanceOf[ParsedHeadersFrame] + headers.streamId shouldBe id + headers.keyValuePairs should contain(":path" -> path) + } + + def respond(id: Int, status: String, endStream: Boolean): Unit = + fromPeer.sendNext(ParsedHeadersFrame(id, endStream, Vector(":status" -> status), None, None)) + } + "The Http/2 client implementation" should { for { interimStatuses <- Seq(Seq.empty[Int], Seq(103), Seq(102, 103), Seq(103, 103))