Skip to content

Commit

Permalink
Introduce support for discard.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed Sep 17, 2024
1 parent ddcb2df commit d5de7ae
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 2 deletions.
4 changes: 3 additions & 1 deletion lib/protocol/http/body/buffered.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ def finish
# Ensure that future reads return nil, but allow for rewinding.
def close(error = nil)
@index = @chunks.length

return nil
end

def clear
Expand Down Expand Up @@ -91,7 +93,7 @@ def read
end

def discard
clear
self.close
end

def write(chunk)
Expand Down
6 changes: 5 additions & 1 deletion lib/protocol/http/body/readable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,13 @@ def finish
Buffered.read(self)
end

# Discard the body as efficiently as possible.
#
# The default implementation simply reads all chunks until the body is empty.
#
# Useful for discarding the body when it is not needed, but preserving the underlying connection.
def discard
while chunk = self.read
chunk.clear
end
end

Expand Down
8 changes: 8 additions & 0 deletions test/protocol/http/body/buffered.rb
Original file line number Diff line number Diff line change
Expand Up @@ -175,4 +175,12 @@
expect(body.inspect).to be =~ /\d+ chunks, \d+ bytes/
end
end

with "#discard" do
it "closes the body" do
expect(body).to receive(:close)

expect(body.discard).to be == nil
end
end
end
7 changes: 7 additions & 0 deletions test/protocol/http/body/readable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@
end
end

with "#discard" do
it "should read all chunks" do
expect(body).to receive(:read).and_return(nil)
expect(body.discard).to be_nil
end
end

with "#as_json" do
it "generates a JSON representation" do
expect(body.as_json).to have_keys(
Expand Down
7 changes: 7 additions & 0 deletions test/protocol/http/body/reader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ def initialize(body)
end
end

with "#discard" do
it 'discards the body' do
expect(body).to receive(:discard)
expect(reader.discard).to be_nil
end
end

with '#buffered!' do
it 'buffers the body' do
expect(reader.buffered!).to be_equal(reader)
Expand Down
7 changes: 7 additions & 0 deletions test/protocol/http/body/wrapper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -104,4 +104,11 @@
body.call(stream)
end
end

with "#discard" do
it "should proxy discard" do
expect(source).to receive(:discard).and_return(nil)
expect(body.discard).to be_nil
end
end
end

0 comments on commit d5de7ae

Please sign in to comment.