Class: Async::HTTY::Server

Inherits:
Protocol::HTTP::Middleware
  • Object
show all
Defined in:
lib/async/htty/server.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, protocol: Protocol::HTTY) ⇒ Server

Returns a new instance of Server.



49
50
51
52
# File 'lib/async/htty/server.rb', line 49

def initialize(app, protocol: Protocol::HTTY)
	super(app)
	@protocol = protocol
end

Instance Attribute Details

#protocolObject (readonly)

Returns the value of attribute protocol.



54
55
56
# File 'lib/async/htty/server.rb', line 54

def protocol
  @protocol
end

Class Method Details

.for(**options, &block) ⇒ Object



16
17
18
# File 'lib/async/htty/server.rb', line 16

def self.for(**options, &block)
	self.new(block, **options)
end

.open(app = nil, input: $stdin, output: $stdout, env: ENV, **options, &block) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/async/htty/server.rb', line 29

def self.open(app = nil, input: $stdin, output: $stdout, env: ENV, **options, &block)
	app ||= block
	server = self.new(app, **options)

	case env["HTTY"]
	when "0"
		raise DisabledError, "HTTY is disabled!"
	when nil
		$stderr.puts "HTTY is not supported by this environment, visit https://htty.dev for more information."
		raise UnsupportedError, "HTTY is not supported by this environment"
	end
	
	Sync do |task|
		with_raw_terminal(input) do
			stream = ::IO::Stream::Duplex(input, output)
			server.accept(stream, task: task)
		end
	end
end

.with_raw_terminal(input, &block) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/async/htty/server.rb', line 20

def self.with_raw_terminal(input, &block)
	if input.respond_to?(:tty?) && input.tty? && input.respond_to?(:raw)
		input.raw(&block)
	else
		block.call
	end
end

Instance Method Details

#accept(stream, task: ::Async::Task.current) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/async/htty/server.rb', line 56

def accept(stream, task: ::Async::Task.current)
	connection = @protocol.server(stream)
	
	connection.each do |request|
		self.call(request)
	end
	
	Array(task.children).each(&:wait)
ensure
	if connection and !connection.closed?
		connection.send_goaway
		connection.close
	end
end