class FDK::Listener

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

Attributes

fn_logframe_hdr[R]
fn_logframe_name[R]
private_socket[R]
url[R]

Public Class Methods

new(url:) click to toggle source
# File lib/fdk/listener.rb, line 32
def initialize(url:)
  if url.nil? || !url.start_with?("unix:/")
    raise "Missing or invalid socket URL in FN_LISTENER."
  end

  @fn_logframe_name = ENV["FN_LOGFRAME_NAME"]
  @fn_logframe_hdr = ENV["FN_LOGFRAME_HDR"]

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

Public Instance Methods

handle_request(fn_block:) click to toggle source
# File lib/fdk/listener.rb, line 68
def handle_request(fn_block:)
  local_socket = socket.accept
  req, resp = new_req_resp
  req.parse(local_socket)
  FDK.debug "got request #{req}"
  log_frame_header(req.header)
  fn_block.call(req, resp)
  resp["Connection"] = "close" # we're not using keep alives sadly
  resp.send_response(local_socket)
  FDK.debug "sending resp  #{resp.status}, #{resp.header}"
  local_socket.close
end
listen(&block) click to toggle source
# File lib/fdk/listener.rb, line 55
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
log_frame_header(headers) click to toggle source
# File lib/fdk/listener.rb, line 95
def log_frame_header(headers)
  return unless logframe_vars_exist

  k = @fn_logframe_hdr.downcase
  v = headers[k]
  return if v.nil? || v.empty?

  frm = "\n#{@fn_logframe_name}=#{v[0]}\n"
  $stderr.print frm
  $stderr.flush
  $stdout.print frm
  $stdout.flush
end
logframe_vars_exist() click to toggle source
# File lib/fdk/listener.rb, line 109
def logframe_vars_exist
  return false if @fn_logframe_name.nil? || @fn_logframe_name.empty? ||
                  @fn_logframe_hdr.nil? || @fn_logframe_hdr.empty?

  true
end
new_req_resp() click to toggle source
# File lib/fdk/listener.rb, line 81
def new_req_resp
  req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
  resp = WEBrick::HTTPResponse.new(WEBrick::Config::HTTP)
  [req, resp]
end
private_socket_path() click to toggle source
# File lib/fdk/listener.rb, line 91
def private_socket_path
  socket_path + ".private"
end
socket() click to toggle source
# File lib/fdk/listener.rb, line 44
def socket
  link_socket_file unless @socket
  @socket ||= private_socket
end
socket_path() click to toggle source
# File lib/fdk/listener.rb, line 87
def socket_path
  @socket_path ||= url[5..url.length]
end