Class: RubyAsterisk::AGI::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-asterisk/agi/server.rb

Overview

FastAGI TCP server backed by an Async Fiber scheduler.

Each incoming Asterisk connection is handled in its own Fiber, so all concurrent sessions share a single OS thread and their socket IO yields the Fiber rather than blocking.

Usage:

server = RubyAsterisk::AGI::Server.new('0.0.0.0', 4573)
server.handle { |session| session.answer }
server.run         # blocks until server.stop is called

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port, logger: Logger.new($stdout)) ⇒ Server

Returns a new instance of Server.



27
28
29
30
31
32
33
34
# File 'lib/ruby-asterisk/agi/server.rb', line 27

def initialize(host, port, logger: Logger.new($stdout))
  @host    = host
  @port    = port.to_i
  @logger  = logger
  @handler = nil
  @running = false
  @server  = nil
end

Instance Attribute Details

#hostObject (readonly)

Returns the value of attribute host.



23
24
25
# File 'lib/ruby-asterisk/agi/server.rb', line 23

def host
  @host
end

#portObject (readonly)

Returns the value of attribute port.



23
24
25
# File 'lib/ruby-asterisk/agi/server.rb', line 23

def port
  @port
end

#runningObject (readonly) Also known as: running?

Returns the value of attribute running.



23
24
25
# File 'lib/ruby-asterisk/agi/server.rb', line 23

def running
  @running
end

Instance Method Details

#handle {|RubyAsterisk::AGI::Session| ... } ⇒ self

Register the per-connection handler block.

Yields:

Returns:

  • (self)


40
41
42
43
# File 'lib/ruby-asterisk/agi/server.rb', line 40

def handle(&block)
  @handler = block
  self
end

#runObject

Start accepting connections (blocks until #stop is called).

Raises:



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/ruby-asterisk/agi/server.rb', line 48

def run
  raise Error, 'No handler registered' unless @handler

  Sync do |parent|
    @server  = TCPServer.new(@host, @port)
    @port    = @server.addr[1]
    @running = true
    @logger.info("AGI server listening on #{@host}:#{@port}")
    accept_loop(parent)
  end
ensure
  @running = false
  close_server
end

#stopObject

Signal the server to stop accepting new connections. Active sessions continue until they finish naturally.



65
66
67
68
69
70
# File 'lib/ruby-asterisk/agi/server.rb', line 65

def stop
  return unless @running

  @running = false
  close_server
end