Class: Async::HTTP::Body::Hijack

Inherits:
Protocol::HTTP::Body::Readable
  • Object
show all
Defined in:
lib/async/http/body/hijack.rb

Overview

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.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(block, input = nil) ⇒ Hijack

Initialize the hijacked body.



35
36
37
38
39
40
41
42
# File 'lib/async/http/body/hijack.rb', line 35

def initialize(block, input = nil)
	@block = block
	@input = input
	
	@task = nil
	@stream = nil
	@output = nil
end

Instance Attribute Details

#inputObject (readonly)

Returns the value of attribute input.



55
56
57
# File 'lib/async/http/body/hijack.rb', line 55

def input
  @input
end

Class Method Details

.response(request, status, headers, &block) ⇒ Object

Create a response with this hijacked body.



21
22
23
# File 'lib/async/http/body/hijack.rb', line 21

def self.response(request, status, headers, &block)
	::Protocol::HTTP::Response[status, headers, self.wrap(request, &block)]
end

.wrap(request = nil, &block) ⇒ Object

Wrap a request body with a hijacked body.



28
29
30
# File 'lib/async/http/body/hijack.rb', line 28

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

Instance Method Details

#call(stream) ⇒ Object

Invoke the block with the given stream for bidirectional communication.



51
52
53
# File 'lib/async/http/body/hijack.rb', line 51

def call(stream)
	@block.call(stream)
end

#empty?Boolean

Has the producer called #finish and has the reader consumed the nil token?

Returns:

  • (Boolean)


58
59
60
# File 'lib/async/http/body/hijack.rb', line 58

def empty?
	@output&.empty?
end

#inspectObject



85
86
87
# File 'lib/async/http/body/hijack.rb', line 85

def inspect
	"\#<#{self.class} #{@block.inspect}>"
end

#readObject

Read the next available chunk.



69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/async/http/body/hijack.rb', line 69

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

#ready?Boolean

Whether the body has output ready to be read.

Returns:

  • (Boolean)


64
65
66
# File 'lib/async/http/body/hijack.rb', line 64

def ready?
	@output&.ready?
end

#stream?Boolean

We prefer streaming directly as it’s the lowest overhead.

Returns:

  • (Boolean)


45
46
47
# File 'lib/async/http/body/hijack.rb', line 45

def stream?
	true
end

#to_sObject



90
91
92
# File 'lib/async/http/body/hijack.rb', line 90

def to_s
	"<Hijack #{@block.class}>"
end