1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/actionmailbox/lib/action_mailbox/relayer.rb

76 lines
2 KiB
Ruby
Raw Normal View History

2018-11-25 14:30:05 -05:00
# frozen_string_literal: true
require "action_mailbox/version"
2018-11-25 14:30:05 -05:00
require "net/http"
require "uri"
module ActionMailbox
class Relayer
class Result < Struct.new(:status_code, :message)
2018-11-25 14:30:05 -05:00
def success?
!failure?
end
def failure?
transient_failure? || permanent_failure?
end
def transient_failure?
status_code.start_with?("4.")
end
def permanent_failure?
status_code.start_with?("5.")
2018-11-25 14:30:05 -05:00
end
end
2018-11-25 21:35:27 -05:00
CONTENT_TYPE = "message/rfc822"
USER_AGENT = "Action Mailbox relayer v#{ActionMailbox.version}"
2018-11-25 14:30:05 -05:00
2018-11-25 21:35:27 -05:00
attr_reader :uri, :username, :password
def initialize(url:, username: "actionmailbox", password:)
@uri, @username, @password = URI(url), username, password
2018-11-25 14:30:05 -05:00
end
def relay(source)
case response = post(source)
when Net::HTTPSuccess
Result.new "2.0.0", "Successfully relayed message to ingress"
2018-11-25 14:30:05 -05:00
when Net::HTTPUnauthorized
Result.new "4.7.0", "Invalid credentials for ingress"
2018-11-25 14:30:05 -05:00
else
Result.new "4.0.0", "HTTP #{response.code}"
2018-11-25 14:30:05 -05:00
end
rescue IOError, SocketError, SystemCallError => error
Result.new "4.4.2", "Network error relaying to ingress: #{error.message}"
2018-11-25 14:30:05 -05:00
rescue Timeout::Error
Result.new "4.4.2", "Timed out relaying to ingress"
2018-11-25 14:30:05 -05:00
rescue => error
Result.new "4.0.0", "Error relaying to ingress: #{error.message}"
2018-11-25 14:30:05 -05:00
end
private
def post(source)
2018-11-25 21:35:27 -05:00
client.post uri, source,
"Content-Type" => CONTENT_TYPE,
"User-Agent" => USER_AGENT,
2018-11-25 14:30:05 -05:00
"Authorization" => "Basic #{Base64.strict_encode64(username + ":" + password)}"
end
def client
@client ||= Net::HTTP.new(uri.host, uri.port).tap do |connection|
2018-11-25 18:31:36 -05:00
if uri.scheme == "https"
require "openssl"
connection.use_ssl = true
connection.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
2018-11-25 14:30:05 -05:00
connection.open_timeout = 1
connection.read_timeout = 10
end
end
end
end