89 lines
2.0 KiB
Ruby
89 lines
2.0 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
require 'dotenv/load'
|
|
require 'pg'
|
|
require 'mail'
|
|
require 'bunny'
|
|
|
|
# Server class
|
|
class BettermailConsumer
|
|
def initialize
|
|
@pg = PG::Connection.new(ENV['DATABASE_URL'])
|
|
end
|
|
|
|
def start
|
|
begin
|
|
puts ' [*] Waiting for messages. To exit press CTRL+C'
|
|
mail_queue = bunny_channel.queue(ENV['RABBIT_MAIL_QUEUE'])
|
|
mail_queue.subscribe(block: true) do |_delivery_info, _properties, body|
|
|
mail = Mail.read_from_string(body)
|
|
puts mail
|
|
end
|
|
sns_queue = bunny_channel.queue(ENV['RABBIT_SNS_QUEUE'])
|
|
sns_queue.subscribe(block: true) do |_delivery_info, _properties, body|
|
|
puts " [x] Received #{_delivery_info}"
|
|
end
|
|
rescue Interrupt => _
|
|
stop
|
|
end
|
|
|
|
end
|
|
|
|
def stop
|
|
@bunny_conn&.close
|
|
@pg&.close
|
|
end
|
|
|
|
def bunny_channel
|
|
if @bunny_channel.nil?
|
|
@bunny_conn = Bunny.new
|
|
@bunny_conn.start
|
|
@bunny_channel = @bunny_conn.create_channel
|
|
end
|
|
@bunny_channel
|
|
end
|
|
end
|
|
|
|
service_name='BetterMail::Consumer'
|
|
# Create a new server instance for listening at localhost interfaces 127.0.0.1:2525
|
|
# and accepting a maximum of 4 simultaneous connections per default
|
|
service = BettermailConsumer.new
|
|
|
|
# save flag for Ctrl-C pressed
|
|
flag_status_ctrl_c_pressed = false
|
|
|
|
# try to gracefully shutdown on Ctrl-C
|
|
trap('INT') do
|
|
# print an empty line right after ^C
|
|
puts
|
|
# notify flag about Ctrl-C was pressed
|
|
flag_status_ctrl_c_pressed = true
|
|
# signal exit to app
|
|
exit 0
|
|
end
|
|
|
|
# Output for debug
|
|
puts("Starting #{service_name}")
|
|
|
|
# setup exit code
|
|
at_exit do
|
|
# check to shutdown connection
|
|
if service
|
|
# Output for debug
|
|
puts('Ctrl-C interrupted, exit now...') if flag_status_ctrl_c_pressed
|
|
# info about shutdown
|
|
puts("Shutdown #{service_name}...")
|
|
# stop all threads and connections gracefully
|
|
service.stop
|
|
end
|
|
|
|
# Output for debug
|
|
puts "#{service_name} stopped!"
|
|
end
|
|
|
|
# Start the server
|
|
service.start
|
|
|
|
# Run on server forever
|
|
service.join
|