Class: FDK::Listener

Inherits:
Object
  • Object
show all
Defined in:
lib/fdk/listener.rb

Overview

Represents the socket that Fn uses to communicate with the FDK (and thence the function) To avoid Fn trying to connect to the socket before it’s ready, the Listener creates a socket on (private_socket_path).

When the socket is ready to accept connections, the FDK links the private_socket_path to the socket_path.

Fn waits for the socket_path to be created and then connects

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url:) ⇒ Listener

Returns a new instance of Listener.



14
15
16
17
18
19
20
21
# File 'lib/fdk/listener.rb', line 14

def initialize(url:)
  if url.nil? || !url.start_with?("unix:/")
    raise "Missing or invalid socket URL in FN_LISTENER."
  end

  @url = url
  @private_socket = UNIXServer.open(private_socket_path)
end

Instance Attribute Details

#private_socketObject (readonly)

Returns the value of attribute private_socket.



12
13
14
# File 'lib/fdk/listener.rb', line 12

def private_socket
  @private_socket
end

#urlObject (readonly)

Returns the value of attribute url.



12
13
14
# File 'lib/fdk/listener.rb', line 12

def url
  @url
end

Instance Method Details

#handle_request(fn_block:) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/fdk/listener.rb', line 47

def handle_request(fn_block:)
  local_socket = socket.accept
  req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
  resp = WEBrick::HTTPResponse.new(WEBrick::Config::HTTP)
  req.parse(local_socket)
  FDK.debug "got request #{req}"
  fn_block.call(req, resp)
  resp.send_response(local_socket)
  FDK.debug "sending resp  #{resp.status}, #{resp.header}"
  local_socket.close
end


28
29
30
31
32
# File 'lib/fdk/listener.rb', line 28

def link_socket_file
  File.chmod(0o666, private_socket_path)
  FileUtils.ln_s(File.basename(private_socket_path), socket_path)
  FDK.debug "listening on #{private_socket_path}->#{socket_path}"
end

#listen(&block) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/fdk/listener.rb', line 34

def listen(&block)
  raise StandardError("No block given") unless block_given?

  begin
    loop do
      handle_request(fn_block: block)
    end
  rescue StandardError => e
    FDK.log(entry: "Error in request handling #{e}")
    FDK.log(entry: e.backtrace)
  end
end

#private_socket_pathObject



63
64
65
# File 'lib/fdk/listener.rb', line 63

def private_socket_path
  socket_path + ".private"
end

#socketObject



23
24
25
26
# File 'lib/fdk/listener.rb', line 23

def socket
  link_socket_file unless @socket
  @socket ||= private_socket
end

#socket_pathObject



59
60
61
# File 'lib/fdk/listener.rb', line 59

def socket_path
  @socket_path ||= url[5..url.length]
end