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.



73
74
75
76
# File 'lib/async/htty/server.rb', line 73

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

Instance Attribute Details

#protocolObject (readonly)

Returns the value of attribute protocol.



78
79
80
# File 'lib/async/htty/server.rb', line 78

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, error: $stderr, env: ENV, **options, &block) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/async/htty/server.rb', line 28

def self.open(app = nil, input: $stdin, output: $stdout, error: $stderr, 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

	unless input.respond_to?(:tty?) && input.tty?
		raise UnsupportedError, "HTTY requires a TTY input stream"
	end
	
	original_input = input.dup
	original_output = output.dup
	original_error = error.dup
	
	stream = ::Protocol::HTTY::Stream.new(original_input, original_output)
	input.reopen(File::NULL)
	output.reopen(File::NULL)
	error.reopen(File::NULL)
	
	Sync do |task|
		with_raw_terminal(original_input) do
			server.accept(stream, task: task)
		end
	end
	
ensure
	if original_input
		input.reopen(original_input)
	end
	
	if original_output
		output.reopen(original_output)
	end
	
	if original_error
		error.reopen(original_error)
	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



80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/async/htty/server.rb', line 80

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