Skip to content

Commit

Permalink
[Hackathon] Add ExampleMatcher (#11622)
Browse files Browse the repository at this point in the history
* Add ExampleMatcher

Add an example matcher that just counts events and outputs how many it saw.

[skip changelog]

* Remove excess whitespace

* Add frozen_string_literal: true
  • Loading branch information
matthinz authored Dec 11, 2024
1 parent 4bc5435 commit 19e6afe
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 2 deletions.
63 changes: 61 additions & 2 deletions bin/summarize-user-events
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ $LOAD_PATH.unshift(File.expand_path(File.join(__dir__, '../lib')))
require 'reporting/cloudwatch_client'
require 'reporting/cloudwatch_query_quoting'

require 'event_summarizer/example_matcher'

class SummarizeUserEvents
attr_reader :uuid, :from_date, :to_date
Expand All @@ -27,12 +28,44 @@ class SummarizeUserEvents
@to_date = argv[2].present? ? Time.strptime(argv[2], '%m/%d/%Y') : DateTime.now
end

def matchers
@matchers ||= [
EventSummarizer::ExampleMatcher.new
]
end

def run
find_cloudwatch_events do |cloudwatch_event|
pp cloudwatch_event
find_cloudwatch_events do |event|
event['@message'] = JSON.parse(event['@message']) if event['@message'].is_a?(String)

matchers.each do |matcher|
matcher.handle_cloudwatch_event(event)
end
end

overall_results = []

matchers.each do |matcher|
results_for_matcher = matcher.finish
overall_results.append(*results_for_matcher)
end

puts format_results(overall_results)
end

def format_results(results)
results.map do |r|
title = r[:title]

[
"## #{title}",
*r[:attributes]&.map do |attr|
"* #{attr[:description]}"
end,
""
]
end.join("\n")
end

def query
format(<<~QUERY)
Expand All @@ -47,6 +80,32 @@ class SummarizeUserEvents
QUERY
end

def find_events(&block)
warn "$stdin.tty? = #{$stdin.tty?}"
if $stdin.tty?
cloudwatch_source(&block)
else
stdin_source(&block)
end
end

def stdin_source(&block)
$stdin.each_line do |line|
next if line.blank?
event = JSON.parse(line)
block.call(event)
end
end

def cloudwatch_source(&block)
cloudwatch_client.fetch(
query: query,
from: from_date,
to: to_date,
&block
)
end


def cloudwatch_client
@cloudwatch_client ||= Reporting::CloudwatchClient.new(
Expand Down
28 changes: 28 additions & 0 deletions lib/event_summarizer/example_matcher.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# frozen_string_literal: true

module EventSummarizer
class ExampleMatcher
attr_reader :event_count

def initialize
@event_count = 0
end

def handle_cloudwatch_event(_event)
@event_count += 1
end

def finish
[
{
title: 'Processed some events',
attributes: [
{ type: :event_count, description: "Processed #{event_count} event(s)" },
],
}.tap do
@event_count = 0
end,
]
end
end
end

0 comments on commit 19e6afe

Please sign in to comment.