class Sinatra::Helpers::Stream

Scheduler has to respond to defer and schedule.
handler is using.
the scheduler, integrating with whatever concurrency feature the Rack
block generating content, front the one sending it to the client) and
Three things really matter: The front and back block (back being the
Class of the response body in case you use #stream.

def self.defer(*) yield end

def self.defer(*)    yield end

def self.schedule(*) yield end

def self.schedule(*) yield end

def <<(data)

def <<(data)
  @scheduler.schedule { @front.call(data.to_s) }
  self
end

def callback(&block)

def callback(&block)
  return yield if closed?
  @callbacks << block
end

def close

def close
  return if closed?
  @closed = true
  @scheduler.schedule { @callbacks.each { |c| c.call } }
end

def closed?

def closed?
  @closed
end

def each(&front)

def each(&front)
  @front = front
  @scheduler.defer do
    begin
      @back.call(self)
    rescue Exception => e
      @scheduler.schedule { raise e }
    ensure
      close unless @keep_open
    end
  end
end

def initialize(scheduler = self.class, keep_open = false, &back)

def initialize(scheduler = self.class, keep_open = false, &back)
  @back = back.to_proc
  @scheduler = scheduler
  @keep_open = keep_open
  @callbacks = []
  @closed = false
end