From 131dbc01f7e155df7998352007488dda313c88ac Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Tue, 3 Sep 2024 17:55:05 +1200 Subject: [PATCH] Ensure chunks are flushed if required, when streaming. --- lib/protocol/http/body/readable.rb | 5 +++++ releases.md | 4 ++++ test/protocol/http/body/readable.rb | 21 ++++++++++++++++++++- 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/lib/protocol/http/body/readable.rb b/lib/protocol/http/body/readable.rb index a4bcd87..48b4469 100644 --- a/lib/protocol/http/body/readable.rb +++ b/lib/protocol/http/body/readable.rb @@ -57,6 +57,11 @@ def stream? def call(stream) while chunk = self.read stream.write(chunk) + + # Flush the stream unless we are immediately expecting more data: + unless self.ready? + stream.flush + end end ensure stream.close diff --git a/releases.md b/releases.md index 43eba2e..3cbe9ca 100644 --- a/releases.md +++ b/releases.md @@ -1,5 +1,9 @@ # Releases +## Unreleased + +- Ensure chunks are flushed if required, when streaming. + ## v0.30.0 ### `Request[]` and `Response[]` Keyword Arguments diff --git a/test/protocol/http/body/readable.rb b/test/protocol/http/body/readable.rb index 65ec4e6..35d5022 100644 --- a/test/protocol/http/body/readable.rb +++ b/test/protocol/http/body/readable.rb @@ -3,6 +3,7 @@ # Released under the MIT License. # Copyright, 2023-2024, by Samuel Williams. +require 'protocol/http/body/stream' require 'protocol/http/body/readable' describe Protocol::HTTP::Body::Readable do @@ -30,11 +31,29 @@ let(:output) {Protocol::HTTP::Body::Buffered.new} let(:stream) {Protocol::HTTP::Body::Stream.new(nil, output)} - it "can stream data" do + it "can stream (empty) data" do body.call(stream) expect(output).to be(:empty?) end + + it "flushes the stream if it is not ready" do + chunks = ["Hello World"] + + mock(body) do |mock| + mock.replace(:read) do + chunks.pop + end + + mock.replace(:ready?) do + false + end + end + + expect(stream).to receive(:flush) + + body.call(stream) + end end with '#join' do