Sha256: 2fb081d1b53e9895fe1000bb7c1d4623a4d2f7ba8d276146224d661508d91f9b

Contents?: true

Size: 1.69 KB

Versions: 22

Compression:

Stored size: 1.69 KB

Contents

# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2019-2023, by Samuel Williams.

require 'protocol/http/body/readable'
require 'protocol/http/body/stream'

require_relative 'writable'

module Async
	module HTTP
		module Body
			# 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.
			class Hijack < ::Protocol::HTTP::Body::Readable
				def self.response(request, status, headers, &block)
					::Protocol::HTTP::Response[status, headers, self.wrap(request, &block)]
				end
				
				def self.wrap(request = nil, &block)
					self.new(block, request&.body)
				end
				
				def initialize(block, input = nil)
					@block = block
					@input = input
					
					@task = nil
					@stream = nil
					@output = nil
				end
				
				# We prefer streaming directly as it's the lowest overhead.
				def stream?
					true
				end
				
				def call(stream)
					return @block.call(stream)
				end
				
				attr :input
				
				# Has the producer called #finish and has the reader consumed the nil token?
				def empty?
					@output&.empty?
				end
				
				def ready?
					@output&.ready?
				end
				
				# 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 inspect
					"\#<#{self.class} #{@block.inspect}>"
				end
				
				def to_s
					"<Hijack #{@block.class}>"
				end
			end
		end
	end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
async-http-0.75.0 lib/async/http/body/hijack.rb
async-http-0.74.0 lib/async/http/body/hijack.rb
async-http-0.73.0 lib/async/http/body/hijack.rb
async-http-0.72.0 lib/async/http/body/hijack.rb
async-http-0.71.0 lib/async/http/body/hijack.rb
async-http-0.70.0 lib/async/http/body/hijack.rb
async-http-0.69.0 lib/async/http/body/hijack.rb
async-http-0.68.0 lib/async/http/body/hijack.rb
async-http-0.67.1 lib/async/http/body/hijack.rb
async-http-0.67.0 lib/async/http/body/hijack.rb
async-http-0.66.2 lib/async/http/body/hijack.rb
async-http-0.66.1 lib/async/http/body/hijack.rb
async-http-0.66.0 lib/async/http/body/hijack.rb
async-http-0.65.1 lib/async/http/body/hijack.rb
async-http-0.65.0 lib/async/http/body/hijack.rb
async-http-0.64.2 lib/async/http/body/hijack.rb
async-http-0.64.1 lib/async/http/body/hijack.rb
async-http-0.64.0 lib/async/http/body/hijack.rb
async-http-0.63.0 lib/async/http/body/hijack.rb
async-http-0.62.0 lib/async/http/body/hijack.rb