class Async::HTTP::Body::Hijack

A body which is designed for hijacked server responses - a response which uses a block to read and write the request and response bodies respectively.

def self.response(request, status, headers, &block)

@returns [Protocol::HTTP::Response] The response with the hijacked body.
@parameter headers [Hash] The response headers.
@parameter status [Integer] The HTTP status code.
@parameter request [Protocol::HTTP::Request] The request to hijack.
Create a response with this hijacked body.
def self.response(request, status, headers, &block)
	::Protocol::HTTP::Response[status, headers, self.wrap(request, &block)]
end

def self.wrap(request = nil, &block)

@returns [Hijack] The hijacked body instance.
@parameter request [Protocol::HTTP::Request | Nil] The request to hijack.
Wrap a request body with a hijacked body.
def self.wrap(request = nil, &block)
	self.new(block, request&.body)
end

def call(stream)

@parameter stream [Protocol::HTTP::Body::Stream] The stream to pass to the block.
Invoke the block with the given stream for bidirectional communication.
def call(stream)
	@block.call(stream)
end

def empty?

Has the producer called #finish and has the reader consumed the nil token?
def empty?
	@output&.empty?
end

def initialize(block, input = nil)

@parameter input [Protocol::HTTP::Body::Readable | Nil] The input body to read from.
@parameter block [Proc] The block to call with the stream.
Initialize the hijacked body.
def initialize(block, input = nil)
	@block = block
	@input = input
	
	@task = nil
	@stream = nil
	@output = nil
end

def inspect

@returns [String] A detailed representation of this body.
def inspect
	"\#<#{self.class} #{@block.inspect}>"
end

def read

Read the next available chunk.
def read
	unless @output
		@output = Writable.new
		@stream = ::Protocol::HTTP::Body::Stream.new(@input, @output)
		
		@task = Task.current.async do |task|
			task.annotate "Streaming hijacked body."
			
			@block.call(@stream)
		end
	end
	
	return @output.read
end

def ready?

@returns [Boolean | Nil]
Whether the body has output ready to be read.
def ready?
	@output&.ready?
end

def stream?

We prefer streaming directly as it's the lowest overhead.
def stream?
	true
end

def to_s

@returns [String] A short summary of this body.
def to_s
	"<Hijack #{@block.class}>"
end