Class: Jets::Commands::Call

Inherits:
Object
  • Object
show all
Includes:
AwsServices
Defined in:
lib/jets/commands/call/guesser.rb,
lib/jets/commands/call.rb,
lib/jets/commands/call/base_guesser.rb,
lib/jets/commands/call/autoload_guesser.rb,
lib/jets/commands/call/anonymous_guesser.rb

Overview

Subclasses of BaseGuessor must implement interface:

detect_class_name
method_name
error_message

Defined Under Namespace

Classes: AnonymousGuesser, AutoloadGuesser, BaseGuesser, Guesser

Instance Method Summary collapse

Methods included from AwsServices

#apigateway, #aws_lambda, #cfn, #dynamodb, #logs, #s3, #s3_resource, #sns, #sqs, #sts

Methods included from AwsServices::StackStatus

#lookup, #stack_exists?, #stack_in_progress?

Methods included from AwsServices::GlobalMemoist

included

Constructor Details

#initialize(provided_function_name, event, options = {}) ⇒ Call

Returns a new instance of Call.



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/jets/commands/call.rb', line 7

def initialize(provided_function_name, event, options={})
  @options = options
  @guess = @options[:guess].nil? ? true : @options[:guess]

  @provided_function_name = provided_function_name
  @event = event

  @invocation_type = options[:invocation_type] || "RequestResponse"
  @log_type = options[:log_type] || "Tail"
  @qualifier = @qualifier
end

Instance Method Details

So use can quickly paste this into their browser if they want to see the function via the Lambda console



133
134
135
136
137
138
139
140
141
142
# File 'lib/jets/commands/call.rb', line 133

def add_console_link_to_clipboard
  return unless RUBY_PLATFORM =~ /darwin/
  return unless system("type pbcopy > /dev/null")

  # TODO: for add_console_link_to_clipboard get the region from the ~/.aws/config and AWS_PROFILE setting
  region = Aws::S3::Client.new.config.region || ENV["AWS_REGION"] ||'us-east-1'
  link = "https://console.aws.amazon.com/lambda/home?region=#{region}#/functions/#{function_name}?tab=configuration"
  system("echo #{link} | pbcopy")
  puts "Pro tip: The Lambda Console Link to the #{function_name} function has been added to your clipboard." unless @options[:mute]
end

#check_valid_json!(text) ⇒ Object

Exits with friendly error message when user provides bad just



123
124
125
126
127
128
129
# File 'lib/jets/commands/call.rb', line 123

def check_valid_json!(text)
  JSON.load(text)
rescue JSON::ParserError => e
  puts "Invalid json provided:\n  '#{text}'"
  puts "Exiting... Please try again and provide valid json."
  exit 1
end

#client_contextObject

TODO: Hook client_context up and make sure it works. Think I’ve figure out how to sign client_context below. Client context must be a valid Base64-encoded JSON object Example: docs.aws.amazon.com/mobileanalytics/latest/ug/PutEvents.html



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/jets/commands/call.rb', line 147

def client_context
  context = {
    "client" => {
      "client_id" => "Jets",
      "app_title" => "jets call cli",
      "app_version_name" => Jets::VERSION,
    },
    "custom" => {},
    "env" =>{
      "platform" => RUBY_PLATFORM,
      "platform_version" => RUBY_VERSION,
    }
  }
  Base64.encode64(JSON.dump(context))
end

#ensure_guesses_found!Object



86
87
88
89
90
91
# File 'lib/jets/commands/call.rb', line 86

def ensure_guesses_found!
  unless guesser.class_name and guesser.method_name
    puts guesser.error_message
    exit
  end
end

#function_nameObject



19
20
21
22
23
24
25
26
# File 'lib/jets/commands/call.rb', line 19

def function_name
  if @guess
    ensure_guesses_found! # possibly exits here
    guesser.function_name # guesser adds namespace already
  else
    [Jets.config.project_namespace, @provided_function_name].join('-')
  end
end

#guesserObject



82
83
84
# File 'lib/jets/commands/call.rb', line 82

def guesser
  @guesser ||= Guesser.new(@provided_function_name)
end

#lambda_clientObject



170
171
172
173
174
175
176
177
178
179
180
# File 'lib/jets/commands/call.rb', line 170

def lambda_client
  opt = {}
  opt = opt.merge({retry_limit: @options[:retry_limit]}) if @options[:retry_limit].present?
  opt = opt.merge({http_read_timeout: @options[:read_timeout]}) if @options[:read_timeout].present?

  if opt.empty?
    aws_lambda
  else
    Aws::Lambda::Client.new(opt)
  end
end

#load_event_from_file(text) ⇒ Object



112
113
114
115
116
117
118
119
120
# File 'lib/jets/commands/call.rb', line 112

def load_event_from_file(text)
  path = text.gsub('file://','')
  path = "#{Jets.root}/#{path}" unless path[0..0] == '/'
  unless File.exist?(path)
    puts "File #{path} does not exist.  Are you sure the file exists?".color(:red)
    exit
  end
  text = IO.read(path)
end

#local_runObject

With local mode there is no way to bypass the guesser



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/jets/commands/call.rb', line 33

def local_run
  puts "Local mode enabled!"
  ensure_guesses_found! # possibly exits here
  klass = guesser.class_name.constantize
  # Example:
  #   PostsController.process(event, context, meth)
  event = JSON.load(transformed_event) || {} # transformed_event is JSON text String

  fun = Jets::PolyFun.new(klass, guesser.method_name)
  result = fun.run(event) # check the logs for polymorphic function errors
  # Note: even though data might not always be json, the JSON.dump does a
  # good job of not bombing, so always calling it to simplify code.

  text = Jets::Util.normalize_result(result)
  STDOUT.puts text
end

#puts(text) ⇒ Object

For this class redirect puts to stderr so user can pipe output to tools like jq. Example:

jets call posts_controller-index '{"test":1}' | jq .


166
167
168
# File 'lib/jets/commands/call.rb', line 166

def puts(text)
  $stderr.puts(text)
end

#remote_runObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/jets/commands/call.rb', line 50

def remote_run
  puts "Calling lambda function #{function_name} on AWS" unless @options[:mute]
  return if @options[:noop]

  options = {
    # client_context: client_context,
    function_name: function_name,
    invocation_type: @invocation_type, # "Event", # RequestResponse
    log_type: @log_type, # pretty sweet
    payload: transformed_event, # "fileb://file-path/input.json", <= JSON
    qualifier: @qualifier, # "1",
  }

  begin
    resp = lambda_client.invoke(options)
  rescue Aws::Lambda::Errors::ResourceNotFoundException
    puts "The function #{function_name} was not found.  Maybe check the spelling or the AWS_PROFILE?".color(:red)
    return
  end

  if @options[:show_log]
    puts "Last 4KB of log in the x-amz-log-result header:".color(:green)
    puts Base64.decode64(resp.log_result)
  end

  add_console_link_to_clipboard
  result = resp.payload.read # already been normalized/JSON.dump by AWS
  unless @options[:mute_output]
    STDOUT.puts result # only thing that goes to stdout
  end
end

#runObject



28
29
30
# File 'lib/jets/commands/call.rb', line 28

def run
  @options[:local] ? local_run : remote_run
end

#transformed_eventObject

Returns text String for the lambda.invoke payload.



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/jets/commands/call.rb', line 95

def transformed_event
  text = @event
  if text && text.include?("file://")
    text = load_event_from_file(text)
  end

  check_valid_json!(text)

  puts "Function name: #{function_name.color(:green)}" unless @options[:mute]
  return text unless function_name.include?("_controller-")
  return text if @options[:lambda_proxy] == false

  event = JSON.load(text)
  lambda_proxy = {"queryStringParameters" => event}
  JSON.dump(lambda_proxy)
end