Class: SignalWire::Serverless::LambdaHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/signalwire/serverless/lambda_handler.rb

Overview

Adapter that lets an AWS Lambda function invoke a Rack application.

Typical usage from a Lambda entrypoint file:

require 'signalwire'

AGENT = SignalWire::AgentBase.new(name: 'my-agent', route: '/')
# ...configure AGENT...

HANDLER = SignalWire::Serverless::LambdaHandler.new(AGENT.rack_app)

def handler(event:, context:)
  HANDLER.call(event, context)
end

The adapter accepts events from either Lambda Function URLs / API Gateway HTTP API (payload format v2) or the classic API Gateway REST API (payload format v1) and returns a response in the matching shape. Any triple returned by the Rack app (status, headers, body) is translated into the {statusCode:, headers:, body:} shape expected by Lambda.

The adapter never reaches out to the network and has no gem dependencies beyond what the SignalWire SDK already requires, so it can be bundled directly into a Lambda zip.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ LambdaHandler

Returns a new instance of LambdaHandler.

Parameters:

  • app (#call)

    a Rack-compatible application

Raises:

  • (ArgumentError)


42
43
44
45
46
# File 'lib/signalwire/serverless/lambda_handler.rb', line 42

def initialize(app)
  raise ArgumentError, 'app must respond to #call' unless app.respond_to?(:call)

  @app = app
end

Class Method Details

.for(agent_or_app) ⇒ LambdaHandler

Class-level convenience so consumers can use SignalWire::Serverless::LambdaHandler.for(agent) without duplicating .rack_app at the call site.

Parameters:

  • agent_or_app (Object)

    either an AgentBase (responds to rack_app) or any Rack-compatible application

Returns:



71
72
73
74
75
76
77
78
# File 'lib/signalwire/serverless/lambda_handler.rb', line 71

def self.for(agent_or_app)
  app = if agent_or_app.respond_to?(:rack_app)
          agent_or_app.rack_app
        else
          agent_or_app
        end
  new(app)
end

Instance Method Details

#call(event, _context = nil) ⇒ Hash

Invoke the wrapped Rack application with a Lambda event.

Parameters:

  • event (Hash)

    the Lambda invocation event

  • _context (Object) (defaults to: nil)

    the Lambda context (ignored)

Returns:

  • (Hash)

    a Lambda-shaped response hash



53
54
55
56
57
58
59
60
61
62
# File 'lib/signalwire/serverless/lambda_handler.rb', line 53

def call(event, _context = nil)
  event ||= {}
  env = build_env(event)

  status, headers, body = @app.call(env)

  build_response(event, status, headers, body)
ensure
  body.close if body.respond_to?(:close)
end