Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions docs/src/main/paradox/client-side/http2.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions docs/src/main/paradox/compatibility-guidelines.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 */
Expand Down Expand Up @@ -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)]()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand All @@ -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")
Expand Down Expand Up @@ -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)
Expand All @@ -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)
}
}
Expand Down Expand Up @@ -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 =>
Expand All @@ -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()
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading