Rack::Response#body vs ActionDispatch::Response#body

146 views
Skip to first unread message

John Firebaugh

unread,
Nov 30, 2010, 5:52:17 PM11/30/10
to rubyonra...@googlegroups.com, rack-...@googlegroups.com
The definitions of #body in Rack::Response and
ActionDispatch::Response are competing and causing performance
problems with streaming responses. Rack::Response provides
attr_accessor :body, while ActionDispatch::Response overrides that as
follows:

def body
str = ''
each { |part| str << part.to_s }
str
end

This is problematic in instances where a streaming body is used, due
to the definition of Rack::Response#close:

def close
body.close if body.respond_to?(:close)
end

Given these definitions, executing the Rack protocol on an
ActionDispatch::Response instance (calling '#each', then '#close')
causes the body to be enumerated twice -- once via the expected call
to #each, and a second time via the call chain #close -> #body ->
#each. See https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/4554
for a user report of this problem.

This could be fixed by using the instance variable directly:

def close
@body.close if @body.respond_to?(:close)
end

However, I think ActionDispatch::Response's #body override is
dangerous and violates the principle of least surprise by removing the
symmetry between #body and #body=. IMHO, it would be better to remove
the override. If the concatenating behavior is necessary, supply a
method named #body_text or a similar name that makes it clear that it
disables streaming. This option causes numerous Rails test failures,
however, as many tests are written to expect #body to return a string.

Thoughts?

Konstantin Haase

unread,
Nov 30, 2010, 6:27:38 PM11/30/10
to rack-...@googlegroups.com
I agree this is a Rails issue, accessing @body directly would be a step backwards since being able to override #body is part of the API imo.
Why not override #close in ActionDispatch::Response to avoid this issue?

Konstantin

John Firebaugh

unread,
Nov 30, 2010, 7:52:11 PM11/30/10
to rack-...@googlegroups.com, rubyonra...@googlegroups.com
On Tue, Nov 30, 2010 at 3:27 PM, Konstantin Haase <k.h...@finn.de> wrote:
> Why not override #close in ActionDispatch::Response to avoid this issue?

I agree that would fix this particular issue. My reluctance with that
is that AD::Response#body would remain a dangerous method on its own,
because it does not obey the semantics established by the base class.
It's a Liskov Substitution Principle violation -- AD::Response cannot
be safely substituted where Rack::Response is expected.

Reply all
Reply to author
Forward
0 new messages