This still forces an inversion of control as far as who is in control of writes, i.e. the IO operation drives the generation of data to write, and not the other way around. I find this incredibly annoying.
FWIW I have implemented both patterns in my own web server Reel. I definitely think It's Just A Socket (duck type) is far and away the way to go.
def index
self.response_body = Enumerator.new do |socket|
100.times do
socket << "hello world"
end
end
end
Your API is a little less verbose, I'll give you that, but I don't see why you need Queues and Threads unless the problem actually calls for those things. It still looks like you are writing to a socket either way. headers['X-Accel-Buffering'] = 'no'That's what you do when you yield to the each's block. It's not like the caller calls each multiple times when it wants new data, he calls `each` once and you feed it data via the block it provides.
> Somehow data must be fed to the `each` function
Just as it "must be" fed to the `write` in your examples.
> That's what you do when you yield to the each's block.
No IO object in ruby uses the `each` method for writing.
Rack responses are IO objects, so they use #each to write data out. That's perfectly coherent.
Don't believe me? Let's undefine #each on the metaclass of an IO object and see what happens. Guess what: it still works!
I am rather surprised by this declaration, because Rack response bodies do indeed behave like "IO objects": they respond to `each`. That's the only requirement. Guess what responds to `each`? IO.
The problem seems entirely self-inflicted by Rails: if it builds an eager, non-streaming Response object, that means you can't stream with it. But it's got nothing whatsoever to do with Rack. By comparison, Rack's own Response helper object does provide easy streaming access: calls to `Response#write` within the `Response#finish` block are streamed directly. Your code would look roughly like this in e.g. Sinatra (note: entirely untested):
Alternatively, you could implement your own #each: this one is straight from the Sinatra docs[0], and aside from the `get` call it can trivially be converted to a raw Rack application: [0] Sinatra also provides a `stream` helper method which does most of the wrapping and tries to make non-streaming-aware middleware play nicely, that can be used in stead of these lower-level calls: http://www.sinatrarb.com/contrib/streaming.html