Class: Async::HTTP::Body::Writable

Inherits:
Readable
  • Object
show all
Defined in:
lib/async/http/body/writable.rb

Overview

A dynamic body which you can write to and read from.

Direct Known Subclasses

Slowloris

Defined Under Namespace

Classes: Closed

Instance Method Summary collapse

Constructor Details

#initialize(length = nil, queue: Async::Queue.new) ⇒ Writable

Returns a new instance of Writable.

Parameters:

  • length (Integer) (defaults to: nil)

    The length of the response body if known.

  • queue (Async::Queue) (defaults to: Async::Queue.new)

    Specify a different queue implementation, e.g. ‘Async::LimitedQueue.new(8)` to enable back-pressure streaming.



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/async/http/body/writable.rb', line 36

def initialize(length = nil, queue: Async::Queue.new)
	@queue = queue
	
	@length = length
	
	@count = 0
	
	@finished = false
	
	@closed = false
	@error = nil
end

Instance Method Details

#close(error = nil) ⇒ Object

Stop generating output; cause the next call to write to fail with the given error.



54
55
56
57
58
59
60
61
62
63
# File 'lib/async/http/body/writable.rb', line 54

def close(error = nil)
	unless @closed
		@queue.enqueue(nil)
		
		@closed = true
		@error = error
	end
	
	super
end

#closed?Boolean

Returns:

  • (Boolean)


65
66
67
# File 'lib/async/http/body/writable.rb', line 65

def closed?
	@closed
end

#empty?Boolean

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

Returns:

  • (Boolean)


70
71
72
# File 'lib/async/http/body/writable.rb', line 70

def empty?
	@finished
end

#inspectObject



99
100
101
# File 'lib/async/http/body/writable.rb', line 99

def inspect
	"\#<#{self.class} #{@count} chunks written#{@finished ? ', finished' : ', waiting'}>"
end

#lengthObject



49
50
51
# File 'lib/async/http/body/writable.rb', line 49

def length
	@length
end

#readObject

Read the next available chunk.



75
76
77
78
79
80
81
82
83
# File 'lib/async/http/body/writable.rb', line 75

def read
	return if @finished
	
	unless chunk = @queue.dequeue
		@finished = true
	end
	
	return chunk
end

#write(chunk) ⇒ Object Also known as: <<

Write a single chunk to the body. Signal completion by calling ‘#finish`.



86
87
88
89
90
91
92
93
94
95
# File 'lib/async/http/body/writable.rb', line 86

def write(chunk)
	# If the reader breaks, the writer will break.
	# The inverse of this is less obvious (*)
	if @closed
		raise(@error || Closed)
	end
	
	@count += 1
	@queue.enqueue(chunk)
end