Skip to content
Draft
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
37 changes: 30 additions & 7 deletions docs/src/main/paradox/client-side/http2.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -102,6 +95,36 @@ 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
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
Expand Down
5 changes: 5 additions & 0 deletions docs/src/main/paradox/server-side/http2.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
9 changes: 5 additions & 4 deletions http-core/src/main/resources/reference.conf
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -310,6 +310,14 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings,

private val terminationPromise = Promise[Http.HttpTerminated]()
private var terminating: Boolean = 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 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
Expand All @@ -328,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
Expand All @@ -344,7 +352,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))
Expand Down Expand Up @@ -410,16 +418,17 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings,
if (allow != allowReadingIncomingFrames)
if (allow) {
debug("Resume reading incoming frames")
if (!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 (!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)
Expand All @@ -430,14 +439,14 @@ 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 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()
Expand Down Expand Up @@ -473,6 +482,27 @@ 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
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
Expand All @@ -487,10 +517,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)
Expand All @@ -515,7 +547,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 || isPeerRetiring) 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))
Expand All @@ -524,7 +574,63 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings,
override def onAllStreamsClosed(): Unit = completeIfDone()
override def onAllDataFlushed(): Unit = completeIfDone()

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.RequestAdmissionClosed)
// Retire the writer at the same time; retained response buffers no longer need to send frames.
if (!isClosed(frameOut)) complete(frameOut)
val unansweredAtEof = retainCompletedClientEntities()
unansweredAtRetirement ||= unansweredAtEof
closingClientStreams = false
scheduleOnce(ReadCompletionTimeout, completionTimeout)
completeIfDone()
}

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) {
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) {
Expand Down Expand Up @@ -563,7 +669,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)
}
})

Expand Down Expand Up @@ -632,6 +739,10 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings,
debug("Connection reached the configured max-connection-age, closing it gracefully")
triggerTermination(maxConnectionAgeGrace)
}
case ReadCompletionTimeout =>
abortClientDrain()
case CompletionTimeout if clientReadClosed || isPeerRetiring =>
abortClientDrain()
case CompletionTimeout =>
if (isServer)
info(
Expand All @@ -658,6 +769,10 @@ private[http2] abstract class Http2Demux(http2Settings: Http2CommonSettings,
*/
@InternalApi
private[pekko] object Http2Demux {
case object RequestAdmissionClosed
extends RuntimeException("HTTP/2 connection stopped accepting requests") with scala.util.control.NoStackTrace

case object CompletionTimeout
case object ReadCompletionTimeout
case object MaxConnectionAge
}
Loading