Skip to content

Instantly share code, notes, and snippets.

@geeksilva97
Last active August 16, 2024 13:40
Show Gist options
  • Save geeksilva97/0b04814375e96cc587c67cb14edfae45 to your computer and use it in GitHub Desktop.
Save geeksilva97/0b04814375e96cc587c67cb14edfae45 to your computer and use it in GitHub Desktop.
This Gist contains an implementation of a poller inside of the Enumerator block. This program is supposed to poll log messages in CRI pattern and print them agregated
require 'fiber'
require 'time'
class String
# colorization
def colorize(color_code)
"\e[#{color_code}m#{self}\e[0m"
end
def red
colorize(31)
end
def green
colorize(32)
end
def yellow
colorize(33)
end
def blue
colorize(34)
end
def pink
colorize(35)
end
def light_blue
colorize(36)
end
end
class LogBucket
def initialize
@log_generator = log_generator_fiber
end
def fetch
@log_generator.resume
end
private
def log_generator_fiber
Fiber.new do
loop do
logs = []
num_logs = rand(0..5)
num_logs.times do
type = ['P', 'F'].sample
logs << generate_log_message(type)
if type == 'P' && rand < 0.5
logs << generate_log_message('P')
end
end
Fiber.yield logs
end
end
end
def generate_log_message(type)
timestamp = Time.now.utc.iso8601(9) + "Z"
message = case type
when 'P'
[
"Winx quando damos nossas mãos, ",
"Nos tornamos poderosas. "
].sample
when 'F'
[
"Porque juntas somos invencíveis.",
"Bloom é a melhor."
].sample
end
"#{timestamp} stdout #{type} #{message}"
end
end
class CRIParserEnumerator
include Enumerable
def each
e = Enumerator.new do |yielder|
current_log = ''
loop do
logs = bucket_service.fetch
print_entries(logs)
logs.each do |log|
parsed = log.split(/stdout (F|P) /).last
current_log += parsed
if log.match?(/stdout F/)
yielder << current_log
current_log = ''
end
end
end
end
return e unless block_given?
e.each { |log| yield log }
end
private
def print_entries(logs)
puts "\nFetched #{logs.size} log entries from external service\n".light_blue
logs.each { |log| puts log.light_blue }
puts "\n\n"
end
def bucket_service
@bucket_service ||= LogBucket.new
end
end
parser = CRIParserEnumerator.new()
parser.each_with_index do |log, index|
puts "\n" if index > 0
puts "======= Log #{index + 1} =======\n\n#{log}\n"
sleep 2
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment