From 916cc7e4ec48416098dd3024a5fe613c1c9140df Mon Sep 17 00:00:00 2001 From: "He-Pin(kerr)" Date: Fri, 27 Nov 2026 00:09:42 +0800 Subject: [PATCH 1/2] fix: account for HTTP/2 DATA padding in receive windows Motivation HTTP/2 flow control counts the full received DATA payload, while the entity exposes only its content. Modification Carry padding overhead separately from application bytes. Apply window accounting before and after request entity dispatch without charging buffered bytes twice. Reuse the existing batching policy for discarded padding. Result Receive windows reflect the DATA payload while entity bytes and Content-Length remain unchanged. References RFC 9113 sections 6.1 and 6.9.1. --- docs/src/main/paradox/server-side/http2.md | 5 + .../http/impl/engine/http2/FrameEvent.scala | 30 +++-- .../http/impl/engine/http2/FrameLogger.scala | 4 +- .../impl/engine/http2/Http2Blueprint.scala | 11 +- .../engine/http2/Http2StreamHandling.scala | 122 +++++++++++++----- .../engine/http2/framing/FrameRenderer.scala | 12 +- .../http2/framing/Http2FrameParsing.scala | 11 +- .../http2/IncomingFlowControllerSpec.scala | 38 ++++++ .../impl/engine/http2/Http2ClientSpec.scala | 34 +++++ .../impl/engine/http2/Http2ServerSpec.scala | 76 +++++++++++ .../http2/framing/Http2FramingSpec.scala | 16 ++- 11 files changed, 295 insertions(+), 64 deletions(-) diff --git a/docs/src/main/paradox/server-side/http2.md b/docs/src/main/paradox/server-side/http2.md index f38e26e606..bb40150c11 100644 --- a/docs/src/main/paradox/server-side/http2.md +++ b/docs/src/main/paradox/server-side/http2.md @@ -101,6 +101,11 @@ connection with `FLOW_CONTROL_ERROR`, as required by [RFC 9113 section 6.9.2](ht An overflow caused by a stream-specific `WINDOW_UPDATE` still affects only that stream. These rules also apply to the HTTP/2 client and do not change HTTP/1.1 fallback behavior. +On receive, both the application data and any padding in a DATA frame count toward its HTTP/2 flow-control +windows. Padding and its length field are discarded before delivering the entity and do not count toward +the HTTP Content-Length. Discarded padding can release receive credit even when no entity bytes have been consumed. +See [RFC 9113 §6.1](https://www.rfc-editor.org/rfc/rfc9113.html#section-6.1). + ## Limiting the lifetime of connections Long-lived HTTP/2 connections, for example those used by gRPC, can lead to an uneven load distribution across diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/FrameEvent.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/FrameEvent.scala index 718ca6cff0..6b4ded3bf7 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/FrameEvent.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/FrameEvent.scala @@ -39,20 +39,28 @@ private[http] object FrameEvent { lastStreamId: Int, errorCode: ErrorCode, debug: ByteString = ByteString.empty) extends FrameEvent { override def toString: String = s"GoAwayFrame($lastStreamId,$errorCode,debug:)" } + sealed trait DataFrameEvent extends StreamFrameEvent { self: Product => + def endStream: Boolean + def payload: ByteString + def paddingSize: Int = 0 + def sizeInWindow: Int + final override def frameTypeName: String = "DataFrame" + } + final case class DataFrame( streamId: Int, endStream: Boolean, - payload: ByteString) extends StreamFrameEvent { - - /** - * The amount of bytes this frame consumes of a window. According to RFC 7540, 6.9.1: - * - * For flow-control calculations, the 9-octet frame header is not - * counted. - * - * That means this size amounts to data size + padding size field + padding. - */ - def sizeInWindow: Int = payload.size // FIXME: take padding size into account, #1313 + payload: ByteString) extends DataFrameEvent { + override def sizeInWindow: Int = payload.size + } + + /** Received DATA with its padding stripped from the entity, but not from flow control (RFC 9113 §6.1). */ + final case class PaddedDataFrame( + streamId: Int, + endStream: Boolean, + payload: ByteString, + override val paddingSize: Int) extends DataFrameEvent { + override def sizeInWindow: Int = payload.size + paddingSize // includes the Pad Length field } /** diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/FrameLogger.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/FrameLogger.scala index 61bb0746ca..d464b224e8 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/FrameLogger.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/FrameLogger.scala @@ -71,8 +71,8 @@ private[http2] object FrameLogger { LogEntry(streamId, "HEAD", prioInfo + hex(payload), flag(endStream, "ES"), flag(endHeaders, "EH")) case ContinuationFrame(streamId, endHeaders, payload) => LogEntry(streamId, "CONT", hex(payload), flag(endHeaders, "EH")) - case DataFrame(streamId, endStream, payload) => - LogEntry(streamId, "DATA", hex(payload), flag(endStream, "ES")) + case data: DataFrameEvent => + LogEntry(data.streamId, "DATA", hex(data.payload), flag(data.endStream, "ES")) case GoAwayFrame(lastStreamId, errorCode, debug) => LogEntry(0, "GOAY", s"lastStreamId = $lastStreamId, errorCode = $errorCode, debug = ${debug.utf8String}") 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..afe2b703ab 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 @@ -276,9 +276,8 @@ private[http] object Http2Blueprint { * Not a real `frameTypeName`, so it never matches one directly: [[frameCost]] recognises it and charges every DATA * frame that carries no payload. * - * Such a frame consumes no flow-control window, so unlike a data-carrying one its number is not bounded by flow - * control at all and a peer can send them continuously. Data-carrying frames are deliberately not covered, because - * throttling those would throttle legitimate throughput along with them. + * DATA without either content or padding consumes no flow-control window. Data-carrying frames are deliberately not + * covered, because throttling those would throttle legitimate throughput along with them. */ private[http2] val EmptyDataFrameThrottleName = "EmptyDataFrame" @@ -294,11 +293,11 @@ private[http] object Http2Blueprint { private[http2] def frameCost(frameTypesForThrottle: Set[String], event: FrameEvent): Int = if (frameTypesForThrottle.contains(event.frameTypeName)) 1 else event match { - case d: DataFrame if d.payload.isEmpty && isThrottledEmptyDataFrame(frameTypesForThrottle, d) => 1 - case _ => 0 + case d: DataFrameEvent if d.payload.isEmpty && isThrottledEmptyDataFrame(frameTypesForThrottle, d) => 1 + case _ => 0 } - private def isThrottledEmptyDataFrame(frameTypesForThrottle: Set[String], frame: DataFrame): Boolean = + private def isThrottledEmptyDataFrame(frameTypesForThrottle: Set[String], frame: DataFrameEvent): Boolean = frameTypesForThrottle.contains(EmptyDataFrameThrottleName) || (!frame.endStream && frameTypesForThrottle.contains(EmptyDataFrameNoEndStreamThrottleName)) diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2StreamHandling.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2StreamHandling.scala index 74c4622a53..547bd7822f 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2StreamHandling.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2StreamHandling.scala @@ -440,20 +440,31 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper } else if (settings.minCollectStrictEntitySize > 0) CollectingIncomingData(frame, correlationAttributes, ByteString.empty, extraInitialWindow = 0) else - dispatchStream(streamId, frame, ByteString.empty, correlationAttributes, nextStateStream) + dispatchStream(streamId, frame, correlationAttributes, nextStateStream) case x => receivedUnexpectedFrame(x) } protected def dispatchStream( + streamId: Int, + headers: ParsedHeadersFrame, + correlationAttributes: Map[AttributeKey[?], ?], + nextStateStream: IncomingStreamBuffer => StreamState): StreamState = + dispatchCollectedStream(streamId, headers, ByteString.empty, Http2Protocol.InitialWindowSize, + correlationAttributes, + nextStateStream) + + protected def dispatchCollectedStream( streamId: Int, headers: ParsedHeadersFrame, initialData: ByteString, + initialStreamWindow: Int, correlationAttributes: Map[AttributeKey[?], ?], nextStateStream: IncomingStreamBuffer => StreamState): StreamState = { val subSource = new SubSourceOutlet[Any](s"substream-out-$streamId") val buffer = new IncomingStreamBuffer(streamId, subSource) - if (initialData.nonEmpty) buffer.onDataFrame(DataFrame(streamId, endStream = false, initialData)) // fabricate frame + if (initialData.nonEmpty || initialStreamWindow != Http2Protocol.InitialWindowSize) + buffer.initWithCollectedData(initialData, initialStreamWindow) dispatchSubstream(headers, Right(Source.fromGraph(subSource.source)), correlationAttributes) nextStateStream(buffer) } @@ -489,20 +500,29 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper headers: ParsedHeadersFrame, correlationAttributes: Map[AttributeKey[?], ?], collectedData: ByteString, - extraInitialWindow: Int) extends ReceivingData { - - override protected def onDataFrame(dataFrame: DataFrame): StreamState = { - val newData = collectedData ++ dataFrame.payload - - if (dataFrame.endStream) { - totalBufferedData -= newData.length - dispatchSubstream(headers, Left(newData), correlationAttributes) - HalfClosedRemoteWaitingForOutgoingStream(extraInitialWindow) - } else if (newData.length >= settings.minCollectStrictEntitySize) - dispatchStream(dataFrame.streamId, headers, newData, correlationAttributes, - OpenReceivingDataFirst(_, extraInitialWindow)) - else - copy(collectedData = newData) + extraInitialWindow: Int, + outstandingStreamWindow: Int = Http2Protocol.InitialWindowSize) extends ReceivingData { + + override protected def onDataFrame(dataFrame: DataFrameEvent): StreamState = { + val remainingWindow = outstandingStreamWindow - dataFrame.sizeInWindow + if (remainingWindow < 0) { + totalBufferedData -= collectedData.length + dataFrame.payload.length + rejectStreamWindow(dataFrame.streamId) + } else { + val newData = collectedData ++ dataFrame.payload + if (dataFrame.endStream) { + totalBufferedData -= newData.length + dispatchSubstream(headers, Left(newData), correlationAttributes) + HalfClosedRemoteWaitingForOutgoingStream(extraInitialWindow) + } else { + val nextWindow = replenishDiscardedPadding(dataFrame, remainingWindow, newData.length) + if (newData.length >= settings.minCollectStrictEntitySize) + dispatchCollectedStream(dataFrame.streamId, headers, newData, nextWindow, correlationAttributes, + OpenReceivingDataFirst(_, extraInitialWindow)) + else + copy(collectedData = newData, outstandingStreamWindow = nextWindow) + } + } } override protected def onTrailer(parsedHeadersFrame: ParsedHeadersFrame): StreamState = this // trailing headers not supported for requests right now @@ -607,6 +627,8 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper sealed abstract class ReceivingNoContent extends ReceivingData { self: Product => protected def streamId: Int protected def afterRemoteEnd: StreamState + protected def outstandingStreamWindow: Int + protected def withStreamWindow(window: Int): StreamState private def rejectContent(): StreamState = { shutdown() @@ -614,35 +636,47 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper Closed } - override protected def onDataFrame(frame: DataFrame): StreamState = { + override protected def onDataFrame(frame: DataFrameEvent): StreamState = { // ReceivingData accounted for these bytes; this state does not retain a body buffer. totalBufferedData -= frame.payload.length if (frame.payload.nonEmpty) rejectContent() - else if (frame.endStream) afterRemoteEnd - else this + else { + val remainingWindow = outstandingStreamWindow - frame.sizeInWindow + if (remainingWindow < 0) rejectStreamWindow(frame.streamId) + else if (frame.endStream) afterRemoteEnd + else if (frame.paddingSize == 0) this + else withStreamWindow(replenishDiscardedPadding(frame, remainingWindow, bufferedData = 0)) + } } override protected def onTrailer(frame: ParsedHeadersFrame): StreamState = rejectContent() override protected def onRstStreamFrame(frame: RstStreamFrame): Unit = shutdown() } - case class HalfClosedLocalReceivingNoContent(streamId: Int) extends ReceivingNoContent { + case class HalfClosedLocalReceivingNoContent( + streamId: Int, + outstandingStreamWindow: Int = Http2Protocol.InitialWindowSize) extends ReceivingNoContent { override protected def afterRemoteEnd: StreamState = Closed + override protected def withStreamWindow(window: Int): StreamState = copy(outstandingStreamWindow = window) override protected def incrementWindow(delta: Int): StreamState = this } - case class OpenReceivingNoContent(outStream: OutStream) extends ReceivingNoContent with Sending { + case class OpenReceivingNoContent( + outStream: OutStream, + outstandingStreamWindow: Int = Http2Protocol.InitialWindowSize) extends ReceivingNoContent with Sending { override protected def streamId: Int = outStream.streamId override protected def afterRemoteEnd: StreamState = HalfClosedRemoteSendingData(outStream) + override protected def withStreamWindow(window: Int): StreamState = copy(outstandingStreamWindow = window) override protected def incrementWindow(delta: Int): StreamState = increaseWindow(delta) - override def handleOutgoingEnded(): StreamState = HalfClosedLocalReceivingNoContent(streamId) + override def handleOutgoingEnded(): StreamState = + HalfClosedLocalReceivingNoContent(streamId, outstandingStreamWindow) } sealed abstract class ReceivingData extends StreamState { self: Product => def handle(event: StreamFrameEvent): StreamState = event match { - case d: DataFrame => + case d: DataFrameEvent => outstandingConnectionLevelWindow -= d.sizeInWindow - totalBufferedData += d.payload.length // padding can be seen as instantly discarded + totalBufferedData += d.payload.length // padding is not retained in the entity buffer if (outstandingConnectionLevelWindow < 0) { shutdown() @@ -694,10 +728,28 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper Closed } + /** Replenishes receive credit for discarded padding without waiting for application demand. */ + protected final def replenishDiscardedPadding(frame: DataFrameEvent, window: Int, bufferedData: Int): Int = + if (frame.paddingSize == 0) window + else { + // The connection part is updated after handling DATA, whether or not an entity has been dispatched. + val increment = flowController.onStreamDataDispatched( + outstandingConnectionLevelWindow, totalBufferedData, window, bufferedData).streamLevel + if (increment > 0) multiplexer.pushControlFrame(WindowUpdateFrame(frame.streamId, increment)) + window + increment + } + + protected final def rejectStreamWindow(streamId: Int): StreamState = { + shutdown() + multiplexer.pushControlFrame(RstStreamFrame(streamId, ErrorCode.FLOW_CONTROL_ERROR)) + multiplexer.dequeueOutStream(streamId) + Closed + } + /** Fails what the application sees of the incoming data with `cause`, and releases what is buffered of it */ protected def failIncoming(cause: Throwable): Unit = () - protected def onDataFrame(dataFrame: DataFrame): StreamState + protected def onDataFrame(dataFrame: DataFrameEvent): StreamState protected def onTrailer(parsedHeadersFrame: ParsedHeadersFrame): StreamState protected def incrementWindow(delta: Int): StreamState protected def onRstStreamFrame(rstStreamFrame: RstStreamFrame): Unit @@ -708,7 +760,7 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper final def failOpenIncomingEntity(): Unit = if (!buffer.isDone) buffer.shutdown() - override protected def onDataFrame(dataFrame: DataFrame): StreamState = { + override protected def onDataFrame(dataFrame: DataFrameEvent): StreamState = { buffer.onDataFrame(dataFrame) afterBufferEvent } @@ -804,7 +856,7 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper def handle(event: StreamFrameEvent): StreamState = event match { // https://http2.github.io/http2-spec/#StreamStates // Endpoints MUST ignore WINDOW_UPDATE or RST_STREAM frames received in this state, - case _: RstStreamFrame | _: WindowUpdateFrame | _: DataFrame => + case _: RstStreamFrame | _: WindowUpdateFrame | _: DataFrameEvent => // FIXME: do we need to adjust connection level window here as described in https://httpwg.org/specs/rfc7540.html#StreamStates: // > Flow-controlled frames (i.e., DATA) received after sending RST_STREAM are counted toward the connection // > flow-control window. Even though these frames might be ignored, because they are sent before the sender @@ -847,7 +899,13 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper def isDone: Boolean = outlet.isClosed - def onDataFrame(data: DataFrame): Unit = + /** Transfer collected entity bytes and their already-accounted receive window without a second debit. */ + def initWithCollectedData(data: ByteString, window: Int): Unit = { + buffer = data + outstandingStreamWindow = window + } + + def onDataFrame(data: DataFrameEvent): Unit = if (wasClosed) { shutdown() pushGOAWAY(ErrorCode.PROTOCOL_ERROR, s"Received unexpected DATA frame after stream was already (half-)closed") @@ -866,7 +924,7 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper buffer ++= data.payload debug( s"Received DATA ${data.sizeInWindow} for stream [$streamId], remaining window space now $outstandingStreamWindow, buffered: ${buffer.length}") - dispatchNextChunk() + dispatchNextChunk(replenishPadding = data.paddingSize != 0) } } def onTrailingHeaders(headers: ParsedHeadersFrame): Unit = { @@ -884,7 +942,9 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper wasClosed = true } - def dispatchNextChunk(): Unit = { + def dispatchNextChunk(): Unit = dispatchNextChunk(replenishPadding = false) + + private def dispatchNextChunk(replenishPadding: Boolean): Unit = { if (buffer.nonEmpty && outlet.isAvailable) { val dataSize = buffer.length min settings.requestEntityChunkSize outlet.push(buffer.take(dataSize)) @@ -895,6 +955,8 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper debug( s"Dispatched chunk of $dataSize for stream [$streamId], remaining window space now $outstandingStreamWindow, buffered: ${buffer.length}") updateWindows() + } else if (replenishPadding && !wasClosed) { + updateWindows() } if (buffer.isEmpty && wasClosed) { trailingHeaders match { diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/framing/FrameRenderer.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/framing/FrameRenderer.scala index e844b30b0a..54b6adf647 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/framing/FrameRenderer.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/framing/FrameRenderer.scala @@ -43,14 +43,14 @@ private[http2] object FrameRenderer { .put(debug) .build() - case DataFrame(streamId, endStream, payload) => - // TODO: should padding be emitted? In which cases? + case data: DataFrameEvent => + // Outbound DATA is unpadded; the received padding size is only accounting metadata. Frame( - payload.length, + data.payload.length, Http2Protocol.FrameType.DATA, - Http2Protocol.Flags.END_STREAM.ifSet(endStream), - streamId) - .put(payload) + Http2Protocol.Flags.END_STREAM.ifSet(data.endStream), + data.streamId) + .put(data.payload) .build() case HeadersFrame(streamId, endStream, endHeaders, headerBlockFragment, prioInfo) => Frame( diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/framing/Http2FrameParsing.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/framing/Http2FrameParsing.scala index a53d01a9e0..58c57db302 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/framing/Http2FrameParsing.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/framing/Http2FrameParsing.scala @@ -83,14 +83,11 @@ private[http] object Http2FrameParsing { HeadersFrame(streamId, endStream, endHeaders, payload.take(payload.remainingSize - paddingLength), priorityInfo) case FrameType.DATA => - val pad = Flags.PADDED.isSet(flags) val endStream = Flags.END_STREAM.isSet(flags) - - val paddingLength = - if (pad) payload.readByte() & 0xFF - else 0 - - DataFrame(streamId, endStream, payload.take(payload.remainingSize - paddingLength)) + if (Flags.PADDED.isSet(flags)) { + val paddingLength = payload.readByte() & 0xFF + PaddedDataFrame(streamId, endStream, payload.take(payload.remainingSize - paddingLength), paddingLength + 1) + } else DataFrame(streamId, endStream, payload.takeAll()) case FrameType.SETTINGS => val ack = Flags.ACK.isSet(flags) diff --git a/http-core/src/test/scala/org/apache/pekko/http/impl/engine/http2/IncomingFlowControllerSpec.scala b/http-core/src/test/scala/org/apache/pekko/http/impl/engine/http2/IncomingFlowControllerSpec.scala index 6d01d0a0d7..aa19a38909 100644 --- a/http-core/src/test/scala/org/apache/pekko/http/impl/engine/http2/IncomingFlowControllerSpec.scala +++ b/http-core/src/test/scala/org/apache/pekko/http/impl/engine/http2/IncomingFlowControllerSpec.scala @@ -17,11 +17,49 @@ package org.apache.pekko.http.impl.engine.http2 +import org.apache.pekko +import pekko.util.ByteString + import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec class IncomingFlowControllerSpec extends AnyWordSpec with Matchers { "The default incoming flow controller" should { + "credit discarded padding while keeping the entity bytes reserved" in { + val body = ByteString("data") + val frame = FrameEvent.PaddedDataFrame(1, endStream = false, body, paddingSize = 3) + frame.payload shouldBe body + frame.sizeInWindow shouldBe 7 + + val targetWindow = 32 + val controller = IncomingFlowController.default(targetWindow, targetWindow) + val remainingWindow = 18 - frame.sizeInWindow + + controller.onStreamDataDispatched( + outstandingConnectionLevelWindow = remainingWindow, + totalBufferedData = frame.payload.length, + outstandingStreamLevelWindow = remainingWindow, + streamBufferedData = frame.payload.length) shouldBe IncomingFlowController.WindowIncrements(17, 17) + + // The same state after the batch is applied must not advertise the bytes a second time. + controller.onStreamDataDispatched( + remainingWindow + 17, body.length, remainingWindow + 17, body.length) shouldBe + IncomingFlowController.WindowIncrements.NoIncrements + } + + "account for padding-only DATA without inventing any entity bytes" in { + val controller = IncomingFlowController.default(32, 32) + for (endStream <- Seq(false, true)) { + val frame = FrameEvent.PaddedDataFrame(1, endStream, ByteString.empty, paddingSize = 3) + frame.payload shouldBe ByteString.empty + frame.sizeInWindow shouldBe 3 + val remainingWindow = 18 - frame.sizeInWindow + controller.onConnectionDataReceived(remainingWindow, frame.payload.length) shouldBe 17 + controller.onStreamDataDispatched(remainingWindow, 0, remainingWindow, 0) shouldBe + IncomingFlowController.WindowIncrements(17, 17) + } + } + "restore shared receive credit after two streams consume data without restoring either stream window" in { val windowSize = Http2Protocol.InitialWindowSize val controller = IncomingFlowController.default(windowSize, windowSize) 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..40b183e193 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 @@ -26,6 +26,7 @@ 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.Flags import pekko.http.impl.engine.http2.Http2Protocol.FrameType import pekko.http.impl.engine.http2.Http2Protocol.SettingIdentifier import pekko.http.impl.engine.http2.framing.FrameRenderer @@ -166,6 +167,39 @@ class Http2ClientSpec extends PekkoSpecWithMaterializer(""" } } + for (endStream <- Seq(false, true)) { + s"account for padding-only DATA on a zero-length 200 response (END_STREAM = $endStream)".inAssertAllStagesStopped( + new TestSetup(Setting(SettingIdentifier.SETTINGS_MAX_CONCURRENT_STREAMS, 1)) with NetProbes { + private def initialWindow = Http2Protocol.InitialWindowSize + private def targetWindow = 2 * initialWindow + 32 + override def settings: ClientConnectionSettings = + super.settings.mapHttp2Settings(_.withIncomingConnectionLevelBufferSize(targetWindow) + .withIncomingStreamLevelBufferSize(targetWindow)) + + user.emitRequest(Get("https://www.example.com/")) + network.expect[HeadersFrame]().streamId shouldBe 1 + network.sendHEADERS(1, endStream = false, Seq(RawHeader(":status", "200"), RawHeader("content-length", "0"))) + val response = user.expectResponse() + response.status shouldBe StatusCodes.OK + response.entity shouldBe HttpEntity.Empty + + network.sendFrame(FrameType.DATA, Flags.PADDED | Flags.END_STREAM.ifSet(endStream), 1, ByteString(2, 0, 0)) + val returnedCredit = targetWindow - initialWindow + 3 + if (endStream) network.expect[WindowUpdateFrame]() shouldBe WindowUpdateFrame(0, returnedCredit) + else { + val updates = Seq(network.expect[WindowUpdateFrame](), network.expect[WindowUpdateFrame]()) + updates should contain theSameElementsAs Seq(WindowUpdateFrame(0, returnedCredit), + WindowUpdateFrame(1, returnedCredit)) + network.sendDATA(1, endStream = true, ByteString.empty) + } + + user.emitRequest(Get("https://www.example.com/next")) + network.expect[HeadersFrame]().streamId shouldBe 3 + network.sendHEADERS(3, endStream = true, Seq(RawHeader(":status", "200"))) + user.expectResponse().status shouldBe StatusCodes.OK + }) + } + "accept content-free status responses" should { def conditionalGet(uri: String): HttpRequest = Get(uri).withHeaders(RawHeader("if-none-match", "\"cached\"")) diff --git a/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ServerSpec.scala b/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ServerSpec.scala index facc8c37b7..0a22c2ee09 100644 --- a/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ServerSpec.scala +++ b/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ServerSpec.scala @@ -795,6 +795,82 @@ class Http2ServerSpec extends Http2SpecWithMaterializer(""" }) } + for (strictSize <- Seq(0, 8)) { + s"restore flow credit for discarded DATA padding before consuming an entity (strict limit $strictSize)" + .inAssertAllStagesStopped(new TestSetup with RequestResponseProbes { + // Set a target just above twice the initial window so the existing batch policy runs on the first frame. + private val initialWindow = Http2Protocol.InitialWindowSize + private val targetWindow = 2 * initialWindow + 32 + override def settings: ServerSettings = + super.settings.mapHttp2Settings(_.withMinCollectStrictEntitySize(strictSize) + .withIncomingConnectionLevelBufferSize(2 * Http2Protocol.InitialWindowSize + 32) + .withIncomingStreamLevelBufferSize(2 * Http2Protocol.InitialWindowSize + 32)) + + val body = ByteString("data") + val headers = Seq( + ":method" -> "POST", ":scheme" -> "https", ":authority" -> "example.com", ":path" -> "/upload") + network.sendHEADERS(1, endStream = false, endHeaders = true, network.encodeHeaderPairs(headers)) + if (strictSize == 0) user.expectRequest().entity.isStrict shouldBe false + + // One legal, small padded frame; its four body bytes are still retained in either receive path. + network.sendFrame(FrameType.DATA, Flags.PADDED, 1, ByteString(2) ++ body ++ ByteString(0, 0)) + + val updates = Seq(network.expect[WindowUpdateFrame](), network.expect[WindowUpdateFrame]()) + val returnedCredit = targetWindow - initialWindow + 3 // Pad Length field and the two padding bytes. + updates should contain theSameElementsAs Seq(WindowUpdateFrame(0, returnedCredit), + WindowUpdateFrame(1, returnedCredit)) + }) + + s"deliver only entity bytes from final padded DATA with Content-Length (strict limit $strictSize)" + .inAssertAllStagesStopped(new TestSetup with RequestResponseProbes { + override def settings: ServerSettings = + super.settings.mapHttp2Settings(_.withMinCollectStrictEntitySize(strictSize)) + + val body = ByteString("data") + val headers = Seq( + ":method" -> "POST", ":scheme" -> "https", ":authority" -> "example.com", ":path" -> "/upload", + "content-length" -> body.length.toString) + network.sendHEADERS(1, endStream = false, endHeaders = true, network.encodeHeaderPairs(headers)) + network.sendFrame(FrameType.DATA, Flags.PADDED | Flags.END_STREAM, 1, + ByteString(2) ++ body ++ ByteString(0, 0)) + + val received = user.expectRequest() + received.entity.isStrict shouldBe (strictSize > 0) + Await.result(received.entity.toStrict(3.seconds.dilated), 3.seconds.dilated).data shouldBe body + }) + } + + "preserve received DATA credit across the strict-to-streamed entity handoff".inAssertAllStagesStopped( + new TestSetup with RequestResponseProbes { + private def initialWindow = Http2Protocol.InitialWindowSize + // Buffered content keeps both windows above the batching threshold. Consuming it crosses the threshold. + private def targetWindow = 2 * (initialWindow - 4) + override def settings: ServerSettings = + super.settings.mapHttp2Settings(_.withMinCollectStrictEntitySize(4) + .withIncomingConnectionLevelBufferSize(targetWindow) + .withIncomingStreamLevelBufferSize(targetWindow)) + + val headers = Seq( + ":method" -> "POST", ":scheme" -> "https", ":authority" -> "example.com", ":path" -> "/upload", + "content-length" -> "4") + network.sendHEADERS(1, endStream = false, endHeaders = true, network.encodeHeaderPairs(headers)) + network.sendFrame(FrameType.DATA, Flags.PADDED, 1, ByteString(2) ++ ByteString("ab") ++ ByteString(0, 0)) + network.sendDATA(1, endStream = false, ByteString("cd")) + + val request = user.expectRequest() + request.entity.isStrict shouldBe false + val entity = ByteStringSinkProbe() + request.entity.dataBytes.runWith(entity.sink) + entity.expectBytes(ByteString("abcd")) + + val restored = targetWindow - initialWindow + 7 // Four content bytes, plus three bytes of padding overhead. + val updates = Seq(network.expect[WindowUpdateFrame](), network.expect[WindowUpdateFrame]()) + updates should contain theSameElementsAs Seq(WindowUpdateFrame(0, restored), WindowUpdateFrame(1, restored)) + + network.sendDATA(1, endStream = true, ByteString.empty) + entity.expectComplete() + }) + "complete an empty request entity after consecutive empty DATA frames".inAssertAllStagesStopped( new TestSetup with RequestResponseProbes { val streamId = 1 diff --git a/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/framing/Http2FramingSpec.scala b/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/framing/Http2FramingSpec.scala index f40e8327f5..716431ae41 100644 --- a/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/framing/Http2FramingSpec.scala +++ b/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/framing/Http2FramingSpec.scala @@ -56,7 +56,7 @@ class Http2FramingSpec extends PekkoSpecWithMaterializer { "with padding" in { b"""xxxxxxxx xxxxxxxx - xxxxxxxx=c # length = 11 = 1 byte padding size + 5 bytes padding + 6 bytes data + xxxxxxxx=c # length = 12 = 1 byte padding size + 5 bytes padding + 6 bytes data 00000000 # type = 0x0 = DATA 00001000 # flags = PADDED xxxxxxxx @@ -75,7 +75,19 @@ class Http2FramingSpec extends PekkoSpecWithMaterializer { 00000000 00000000 00000000 - """ should parseTo(DataFrame(0x234223AB, endStream = false, ByteString("bcdefg")), checkRendering = false) + """ should parseTo( + PaddedDataFrame(0x234223AB, endStream = false, ByteString("bcdefg"), paddingSize = 6), + checkRendering = false) + } + + "count the Pad Length field even when the length is zero" in { + val body = ByteString("ok") + val frame = FrameRenderer.renderFrame( + Http2Protocol.FrameType.DATA, + Http2Protocol.Flags.PADDED | Http2Protocol.Flags.END_STREAM, + 1, + ByteString(0) ++ body) + frame should parseTo(PaddedDataFrame(1, endStream = true, body, paddingSize = 1), checkRendering = false) } } "HEADER frames" should { From 77dbbe80919fcd7c452df52255f4100af79d56f5 Mon Sep 17 00:00:00 2001 From: "He-Pin(kerr)" Date: Fri, 27 Nov 2026 01:11:50 +0800 Subject: [PATCH 2/2] fix: account for discarded HTTP/2 DATA at connection level Motivation HTTP/2 DATA received for a closed stream can still consume the connection-level receive window even when the stream discards it. Modification Debit the full flow-controlled size without retaining entity bytes or updating the closed stream. Keep other streams' buffered bytes reserved and replenish connection credit through the existing batching policy. Use the existing connection-error path when credit is insufficient. Check the connection-only credit in the existing cancellation test before checking that a subsequent exchange still succeeds. Result Discarding DATA no longer leaves the connection's receive accounting out of sync with the peer. The stream remains closed. References RFC 9113 sections 5.1, 6.4 and 6.9. --- .../engine/http2/Http2StreamHandling.scala | 71 ++++++++++--------- .../engine/http2/IncomingFlowController.scala | 15 ++++ .../http2/IncomingFlowControllerSpec.scala | 27 +++++++ .../impl/engine/http2/Http2ClientSpec.scala | 8 ++- .../impl/engine/http2/Http2ServerSpec.scala | 7 +- 5 files changed, 93 insertions(+), 35 deletions(-) diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2StreamHandling.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2StreamHandling.scala index 547bd7822f..5adc726c00 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2StreamHandling.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/Http2StreamHandling.scala @@ -111,6 +111,12 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper private var outstandingConnectionLevelWindow = Http2Protocol.InitialWindowSize private var totalBufferedData = 0 + private def advertiseConnectionReceiveCredit(increment: Int): Unit = + if (increment > 0) { + multiplexer.pushControlFrame(WindowUpdateFrame(Http2Protocol.NoStreamId, increment)) + outstandingConnectionLevelWindow += increment + } + /** * The "last peer-initiated stream that was or might be processed on the sending endpoint in this connection" * @@ -266,28 +272,30 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper require(!stateMachineRunning, "State machine already running") stateMachineRunning = true - val oldState = streamFor(streamId) + val result = try { + val oldState = streamFor(streamId) - val (newState, ret) = handle(oldState) - newState match { - case Closed => streamClosed(streamId) - case newState => streamStates.put(streamId, newState) - } + val (newState, ret) = handle(oldState) + newState match { + case Closed => streamClosed(streamId) + case newState => streamStates.put(streamId, newState) + } - debug( - s"Incoming side of stream [$streamId] changed state: ${oldState.stateName} -> ${newState.stateName} after handling [$event${if (eventArg ne - null) - s"($eventArg)" - else ""}]") + debug( + s"Incoming side of stream [$streamId] changed state: ${oldState.stateName} -> ${newState.stateName} after handling [$event${if (eventArg ne + null) + s"($eventArg)" + else ""}]") + ret + } finally stateMachineRunning = false - stateMachineRunning = false if (deferredStreamToEnqueue != -1) { val streamId = deferredStreamToEnqueue deferredStreamToEnqueue = -1 if (streamStates.contains(streamId)) multiplexer.enqueueOutStream(streamId) } - ret + result } /** Called to cleanup any state when the connection is torn down */ @@ -690,12 +698,8 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper rejectContentLength(d.streamId) } else onDataFrame(d) - val windowSizeIncrement = - flowController.onConnectionDataReceived(outstandingConnectionLevelWindow, totalBufferedData) - if (windowSizeIncrement > 0) { - multiplexer.pushControlFrame(WindowUpdateFrame(Http2Protocol.NoStreamId, windowSizeIncrement)) - outstandingConnectionLevelWindow += windowSizeIncrement - } + advertiseConnectionReceiveCredit( + flowController.onConnectionDataReceived(outstandingConnectionLevelWindow, totalBufferedData)) nextState } case r: RstStreamFrame => @@ -854,15 +858,21 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper override def handleOutgoingFailed(cause: Throwable): StreamState = this def handle(event: StreamFrameEvent): StreamState = event match { - // https://http2.github.io/http2-spec/#StreamStates - // Endpoints MUST ignore WINDOW_UPDATE or RST_STREAM frames received in this state, - case _: RstStreamFrame | _: WindowUpdateFrame | _: DataFrameEvent => - // FIXME: do we need to adjust connection level window here as described in https://httpwg.org/specs/rfc7540.html#StreamStates: - // > Flow-controlled frames (i.e., DATA) received after sending RST_STREAM are counted toward the connection - // > flow-control window. Even though these frames might be ignored, because they are sent before the sender - // > receives the RST_STREAM, the sender will consider the frames to count against the flow-control window. - // - // or should connection window adjustments be done in Http2ServerDemux directly? + case data: DataFrameEvent => + // RFC 9113 sections 5.1 and 6.9: discarded DATA still consumes connection credit. + val receipt = IncomingFlowController.onDiscardedData( + data, outstandingConnectionLevelWindow, totalBufferedData, flowController) + if (receipt.remainingConnectionWindow < 0) + throw new Http2Compliance.Http2ProtocolException(ErrorCode.FLOW_CONTROL_ERROR, + "Received more data than connection-level window would allow", + if (isServer) lastStreamId() else Http2Protocol.NoStreamId) + else { + outstandingConnectionLevelWindow = receipt.remainingConnectionWindow + advertiseConnectionReceiveCredit(receipt.connectionWindowIncrement) + } + this + // Ignore these frames in the closed state (RFC 9113 section 5.1). + case _: RstStreamFrame | _: WindowUpdateFrame => this case _ => receivedUnexpectedFrame(event) @@ -978,10 +988,7 @@ private[http2] trait Http2StreamHandling extends GraphStageLogic with LogHelper outstandingConnectionLevelWindow, totalBufferedData, outstandingStreamWindow, buffer.length) - if (connectionLevel > 0) { - multiplexer.pushControlFrame(WindowUpdateFrame(Http2Protocol.NoStreamId, connectionLevel)) - outstandingConnectionLevelWindow += connectionLevel - } + advertiseConnectionReceiveCredit(connectionLevel) if (streamLevel > 0 && !wasClosed /* No reason to update window on closed streams */ ) { multiplexer.pushControlFrame(WindowUpdateFrame(streamId, streamLevel)) outstandingStreamWindow += streamLevel diff --git a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/IncomingFlowController.scala b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/IncomingFlowController.scala index b4913439b7..7bd94e59c1 100644 --- a/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/IncomingFlowController.scala +++ b/http-core/src/main/scala/org/apache/pekko/http/impl/engine/http2/IncomingFlowController.scala @@ -37,6 +37,21 @@ private[http2] object IncomingFlowController { val NoIncrements = WindowIncrements(0, 0) } + final case class DiscardedDataReceipt(remainingConnectionWindow: Int, connectionWindowIncrement: Int) + + /** Accounts for discarded DATA without reserving body bytes or changing any stream-level window. */ + def onDiscardedData( + data: FrameEvent.DataFrameEvent, + outstandingConnectionLevelWindow: Int, + totalBufferedData: Int, + flowController: IncomingFlowController): DiscardedDataReceipt = { + val remainingWindow = outstandingConnectionLevelWindow - data.sizeInWindow + val increment = + if (remainingWindow < 0) 0 + else flowController.onConnectionDataReceived(remainingWindow, totalBufferedData) + DiscardedDataReceipt(remainingWindow, increment) + } + def default(settings: Http2CommonSettings): IncomingFlowController = default(settings.incomingConnectionLevelBufferSize, settings.incomingStreamLevelBufferSize) diff --git a/http-core/src/test/scala/org/apache/pekko/http/impl/engine/http2/IncomingFlowControllerSpec.scala b/http-core/src/test/scala/org/apache/pekko/http/impl/engine/http2/IncomingFlowControllerSpec.scala index aa19a38909..44e969940b 100644 --- a/http-core/src/test/scala/org/apache/pekko/http/impl/engine/http2/IncomingFlowControllerSpec.scala +++ b/http-core/src/test/scala/org/apache/pekko/http/impl/engine/http2/IncomingFlowControllerSpec.scala @@ -60,6 +60,33 @@ class IncomingFlowControllerSpec extends AnyWordSpec with Matchers { } } + "account for discarded DATA at connection level without reserving its entity bytes" in { + val controller = IncomingFlowController.default(32, 32) + val data = FrameEvent.PaddedDataFrame(1, endStream = false, ByteString("data"), paddingSize = 3) + + // Other streams' buffered bytes are still reserved. Neither the discarded body nor padding is added to them. + val receipt = IncomingFlowController.onDiscardedData(data, 18, totalBufferedData = 3, controller) + receipt shouldBe IncomingFlowController.DiscardedDataReceipt(11, 18) + controller.onConnectionDataReceived( + receipt.remainingConnectionWindow + receipt.connectionWindowIncrement, totalBufferedData = 3) shouldBe 0 + } + + "debit discarded unpadded DATA even when available capacity does not trigger a window update" in { + val controller = IncomingFlowController.default(32, 32) + val data = FrameEvent.DataFrame(1, endStream = true, ByteString("data")) + + IncomingFlowController.onDiscardedData(data, 20, totalBufferedData = 0, controller) shouldBe + IncomingFlowController.DiscardedDataReceipt(16, 0) + } + + "not grant credit when a discarded DATA receipt exceeds the available connection window" in { + val controller = IncomingFlowController.default(32, 32) + val data = FrameEvent.DataFrame(1, endStream = true, ByteString("data")) + + IncomingFlowController.onDiscardedData(data, 3, totalBufferedData = 0, controller) shouldBe + IncomingFlowController.DiscardedDataReceipt(-1, 0) + } + "restore shared receive credit after two streams consume data without restoring either stream window" in { val windowSize = Http2Protocol.InitialWindowSize val controller = IncomingFlowController.default(windowSize, windowSize) 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 40b183e193..fcb7c8db6a 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 @@ -660,7 +660,13 @@ class Http2ClientSpec extends PekkoSpecWithMaterializer(""" entityDataIn.cancel() network.expectRST_STREAM(TheStreamId) - network.sendDATA(TheStreamId, endStream = false, ByteString("test")) + val data = ByteString("test") + network.sendDATA(TheStreamId, endStream = false, data) + + // DATA already in flight does not reopen the stream, but still consumes connection credit. + val returnedCredit = + settings.http2Settings.incomingConnectionLevelBufferSize - Http2Protocol.InitialWindowSize + data.length + network.expect[WindowUpdateFrame]() shouldBe WindowUpdateFrame(Http2Protocol.NoStreamId, returnedCredit) connectionShouldStillBeUsable() }) diff --git a/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ServerSpec.scala b/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ServerSpec.scala index 0a22c2ee09..d52aee2d54 100644 --- a/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ServerSpec.scala +++ b/http2-tests/src/test/scala/org/apache/pekko/http/impl/engine/http2/Http2ServerSpec.scala @@ -1064,14 +1064,17 @@ class Http2ServerSpec extends Http2SpecWithMaterializer(""" val data1 = ByteString("abcdef") network.sendDATA(TheStreamId, endStream = false, data1) entityDataIn.expectBytes(data1) - network.pollForWindowUpdates(10.millis) + // Consume the initial connection and stream credit before checking the cancellation frames. + network.expectWindowUpdate() + network.expectWindowUpdate() + network.remainingWindowForIncomingData(TheStreamId) should be > Http2Protocol.InitialWindowSize // cancel stream entityDataIn.cancel() network.expectRST_STREAM(TheStreamId) network.sendDATA(TheStreamId, endStream = false, ByteString("test")) - // should just be ignored, especially no GOAWAY frame should be sent in response + // The earlier window update left enough connection credit, so no control frame is needed here. network.expectNoBytes(100.millis) }) "send RST_STREAM if entity stream is canceled".inAssertAllStagesStopped(new WaitingForRequestData {