This repository has been archived by the owner on Dec 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebhook_multiplexer.rb
136 lines (111 loc) · 4.03 KB
/
webhook_multiplexer.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
require 'httpclient/include_client'
require 'net/http'
module WebhookMultiplexer
extend HTTPClient::IncludeClient
include_http_client do |http|
if ENV['DEBUG']
(http.debug_dev = $stdout).sync = true
end
http.connect_timeout = ENV.fetch('CONNECT_TIMEOUT', '5').to_i
http.send_timeout = ENV.fetch('SEND_TIMEOUT', '5').to_i
http.receive_timeout = ENV.fetch('RECEIVEt_TIMEOUT', '15').to_i
end
module_function
module NormalizeHeaders
module_function
def normalize_headers(headers)
array = headers.map { |name, value|
next unless value
[name.to_s.split(/_|-/).map { |segment| segment.capitalize }.join("-"),
case value
when Regexp then value
when Array then (value.size == 1) ? value.first : value.map {|v| v.to_s}.sort
else value.to_s
end
]
}
Hash[*array.inject([]) {|r,x| r + x}]
end
end
module RequestHeaders
include NormalizeHeaders
def headers
http_keys = env.keys.grep(/^HTTP_/)
values = env.values_at(*http_keys)
http_keys.map!{|key| key.sub(/^HTTP_/, '') }
normalize_headers Hash[http_keys.zip(values)].merge(
'CONTENT_LENGTH' => env['CONTENT_LENGTH'],
'CONTENT_TYPE' => env['CONTENT_TYPE']
)
end
end
def call(env)
request = ::Rack::Request.new(env)
request.extend(RequestHeaders)
results = multiplex(request, multiplexed_locations)
success, failure = results.partition{|r| r.is_a?(HTTP::Message) && HTTP::Status.successful?(r.status) }
errors = ", #{failure.size} errors (#{failure.map(&method(:failure_reason)).join(', ')})" unless failure.empty?
[ 200, {}, ["payload delivered to #{success.size} locations", errors].compact ]
end
# @param request [Rack::Request]
# @param locations [Array<String>]
def multiplex(request, locations)
body = request.body.read
headers = request.headers
headers.delete('Host')
query = request.query_string.split('&')
query = nil if query.empty?
connections = locations.map do |location|
request_method = location.request_method || request.request_method
uri = URI("#{location}#{request.fullpath == '/' ? '' : request.fullpath}")
has_body = request_has_body?(request_method)
http_client.request_async(request_method,
uri,
query,
(has_body.nil? || has_body) ? body : nil,
headers.merge('Host' => uri.host).merge(location.headers))
end
responses = connections.each(&:join).map do |connection|
begin
connection.pop
rescue => error
error
end
end
responses
end
def request_has_body?(method)
request_method = method.downcase
request = Net::HTTP.const_get(request_method.capitalize) if Net::HTTP.instance_method(request_method)
request::REQUEST_HAS_BODY
rescue NameError
nil
end
def failure_reason(message)
case message
when HTTP::Message
message.status
when ::HTTPClient::TimeoutError, ::HTTPClient::BadResponseError # convert HTTPClient::ConnectTimeoutError to connect_timeout
message.message.split('::').last.gsub(/([a-z\d])([A-Z])/,'\1_\2').sub(/_error$/i, '').downcase
end
end
class Location
include NormalizeHeaders
attr_reader :request_method, :url, :headers
alias_method :to_s, :url
def initialize(url, request_method: nil, headers: nil)
@url = url
@request_method = request_method
@headers = normalize_headers(headers || {})
end
def self.parse(definition)
method, url, *headers = definition.split(',')
url, method = method, url if method && !url # swap if there is no method defined
headers = Hash[headers.map{|line| k,v = line.split(/\s*:\s*/); [k.tr('-','_').upcase, v] }]
new(url, request_method: method, headers: headers)
end
end
def multiplexed_locations
ENV.fetch('WEBHOOK_MULTIPLEXER_URLS'){ return [] }.split(';').map(&Location.method(:parse))
end
end