-
Notifications
You must be signed in to change notification settings - Fork 64
/
kinesis.ex
248 lines (203 loc) · 6.19 KB
/
kinesis.ex
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
defmodule RigInboundGateway.ApiProxy.Handler.Kinesis do
@moduledoc """
Handles requests for Kinesis targets.
"""
use Rig.Config, :custom_validation
alias ExAws
alias Plug.Conn
alias Rig.Connection.Codec
alias RIG.Tracing
alias RigInboundGateway.ApiProxy.Handler
alias RigMetrics.EventsMetrics
alias RigMetrics.ProxyMetrics
alias UUID
require Logger
@metrics_target_label "kinesis"
@behaviour Handler
@help_text """
Produce the request to a Kinesis topic and optionally wait for the (correlated) response.
Expects a JSON encoded CloudEvent in the HTTP body.
Optionally set a partition key via this field:
`rig`: {\"target_partition\":\"the-partition-key\"}
"""
# ---
# Confex callback
defp validate_config!(config) do
kinesis_endpoint = Keyword.fetch!(config, :kinesis_endpoint)
kinesis_request_region = Keyword.fetch!(config, :kinesis_request_region)
# try to construct local configuration for Kinesis
kinesis_options =
if byte_size(kinesis_endpoint) > 0 do
%{port: port, host: host, scheme: scheme} = URI.parse(kinesis_endpoint)
%{port: port, host: host, scheme: "#{scheme}://"}
else
%{}
end
%{
kinesis_request_region: kinesis_request_region,
response_timeout: Keyword.fetch!(config, :response_timeout),
cors: Keyword.fetch!(config, :cors),
kinesis_endpoint: Keyword.fetch!(config, :kinesis_endpoint),
kinesis_options: Map.merge(%{region: kinesis_request_region}, kinesis_options)
}
end
# ---
@doc @help_text
@impl Handler
def handle_http_request(conn, api, endpoint, request_path)
# CORS response for preflight request.
def handle_http_request(
%{method: "OPTIONS"} = conn,
_,
%{"target" => "kinesis"} = endpoint,
_
) do
ProxyMetrics.count_proxy_request(
conn.method,
conn.request_path,
"kinesis",
Map.get(endpoint, "response_from", "http"),
"ok"
)
conn
|> with_cors()
|> Conn.send_resp(:no_content, "")
end
def handle_http_request(
conn,
_,
%{"target" => "kinesis", "topic" => topic} = endpoint,
request_path
)
when byte_size(topic) > 0 do
response_from = Map.get(endpoint, "response_from", "http")
conn.assigns[:body]
|> Jason.decode()
|> case do
{:ok, %{"specversion" => _, "rig" => %{"target_partition" => partition}} = event} ->
do_handle_http_request(conn, request_path, partition, event, response_from, topic)
{:ok, %{"specversion" => _} = event} ->
do_handle_http_request(conn, request_path, UUID.uuid4(), event, response_from, topic)
{:ok, _} ->
respond_with_bad_request(conn, response_from, "the body does not look like a CloudEvent")
{:error, _} ->
respond_with_bad_request(conn, response_from, "expected a JSON encoded request body")
end
end
# ---
def do_handle_http_request(
conn,
request_path,
partition,
event,
response_from,
topic \\ nil
) do
kinesis_message =
event
|> Map.put("rig", %{
correlation: Codec.serialize(self()),
remoteip: to_string(:inet_parse.ntoa(conn.remote_ip)),
host: conn.host,
port: conn.port,
scheme: conn.scheme,
headers: Enum.map(conn.req_headers, &Tuple.to_list(&1)),
method: conn.method,
path: request_path,
query: conn.query_string
})
|> Tracing.append_context(Tracing.context())
|> Jason.encode!()
produce(partition, kinesis_message, topic)
wait_for_response? =
case response_from do
# TODO: "kinesis" -> true
_ -> false
end
conn = with_cors(conn)
if wait_for_response? do
wait_for_response(conn, response_from)
else
ProxyMetrics.count_proxy_request(
conn.method,
conn.request_path,
"kinesis",
response_from,
"ok"
)
Conn.send_resp(conn, :accepted, "Accepted.")
end
end
def respond_with_bad_request(conn, response_from, description) do
response = """
Bad request: #{description}.
# Usage
#{@help_text}
"""
ProxyMetrics.count_proxy_request(
conn.method,
conn.request_path,
"kinesis",
response_from,
"bad_request"
)
Conn.send_resp(conn, :bad_request, response)
end
# --- Not used at the moment
defp wait_for_response(conn, response_from) do
conf = config()
receive do
{:response_received, response} ->
ProxyMetrics.count_proxy_request(
conn.method,
conn.request_path,
"kinesis",
response_from,
"ok"
)
conn
|> Tracing.Plug.put_resp_header(Tracing.context())
|> Conn.put_resp_content_type("application/json")
|> Conn.send_resp(:ok, response)
after
conf.response_timeout ->
ProxyMetrics.count_proxy_request(
conn.method,
conn.request_path,
"kinesis",
response_from,
"response_timeout"
)
conn
|> Tracing.Plug.put_resp_header(Tracing.context())
|> Conn.send_resp(:gateway_timeout, "")
end
end
# ---
defp produce(partition_key, plaintext, topic) do
conf = config()
case ExAws.Kinesis.put_record(
_topic = topic,
_partition_key = partition_key,
_data = plaintext
)
|> ExAws.request(conf.kinesis_options) do
{:ok, _} ->
# increase Prometheus metric with a produced event
EventsMetrics.count_produced_event(@metrics_target_label, topic)
err ->
# increase Prometheus metric with an event failed to be produced
EventsMetrics.count_failed_produce_event(@metrics_target_label, topic)
Logger.error(fn ->
"Error occurred when producing Kinesis event to topic #{topic}, #{inspect(err)}"
end)
end
end
# ---
defp with_cors(conn) do
conn
|> Conn.put_resp_header("access-control-allow-origin", config().cors)
|> Conn.put_resp_header("access-control-allow-methods", "*")
|> Conn.put_resp_header("access-control-allow-headers", "content-type,authorization")
end
end