-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtelepoison.ex
281 lines (228 loc) · 9.56 KB
/
telepoison.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
defmodule Telepoison do
@moduledoc """
OpenTelemetry-instrumented wrapper around HTTPoison.Base
A client request span is created on request creation, and ended once we get the response.
http.status and other standard http span attributes are set automatically.
"""
use HTTPoison.Base
require OpenTelemetry
require OpenTelemetry.SemanticConventions.Trace, as: Conventions
require OpenTelemetry.Span
require OpenTelemetry.Tracer
require Record
require Logger
alias HTTPoison.Request
alias OpenTelemetry.Tracer
alias Telepoison.Configuration
@http_method Atom.to_string(Conventions.http_method())
@http_request_method "http.request.method"
@http_response_status_code "http.response.status_code"
@http_route Atom.to_string(Conventions.http_route())
@http_status_code Atom.to_string(Conventions.http_status_code())
@http_url Atom.to_string(Conventions.http_url())
@net_peer_name Atom.to_string(Conventions.net_peer_name())
@server_address "server.address"
@server_port "server.port"
@url_full "url.full"
@url_scheme "url.scheme"
@url_template "url.template"
@doc ~S"""
Configures Telepoison using the provided `opts` `Keyword list`.
You should call this function within your application startup, before Telepoison is used.
Using the `:ot_attributes` option, you can set default Open Telemetry metadata attributes
to be added to each Telepoison request in the format of a list of two element tuples, with both elements
being strings.
Attributes can be overridden per each call to `Telepoison.request/1`.
Using the `:infer_route` option, you can customise the URL resource route inference procedure
that is used to set the `http.route` Open Telemetry metadata attribute.
If a function with an arity of 1 (the `t:HTTPoison.Request/0` `request`) is provided
then that function is used to determine the inference.
If no value is provided then the out of the box, conservative inference provided by
`Telepoison.URI.infer_route_from_request/1` is used to determine the inference.
This can be overridden per each call to `Telepoison.request/1`.
## Examples
iex> Telepoison.setup()
:ok
iex> infer_fn = fn
...> %HTTPoison.Request{} = request -> URI.parse(request.url).path
...> end
iex> Telepoison.setup(infer_route: infer_fn)
:ok
iex> Telepoison.setup(ot_attributes: [{"service.name", "..."}, {"service.namespace", "..."}])
:ok
iex> infer_fn = fn
...> %HTTPoison.Request{} = request -> URI.parse(request.url).path
...> end
iex> ot_attributes = [{"service.name", "..."}, {"service.namespace", "..."}]
iex> Telepoison.setup(infer_route: infer_fn, ot_attributes: ot_attributes)
:ok
"""
@deprecated "setup/1 is deprecated, use `config :telepoison, ...` instead"
def setup(opts \\ []) do
Configuration.setup(opts)
:ok
end
def process_request_headers(headers) when is_map(headers) do
headers
|> Enum.into([])
|> process_request_headers()
end
def process_request_headers(headers) when is_list(headers) do
headers
# Convert atom header keys.
# otel_propagator_text_map only accepts string keys, while Request.headers() keys can be atoms or strings.
# The value in Request.headers() has to be a binary() so we don't need to convert it
#
# Note that this causes the header keys from HTTPoison.Response{request: %{headers: headers}} to also become strings
# while with plain HTTPoison they would remain atoms.
|> Enum.map(fn {k, v} -> {to_string(k), v} end)
|> :otel_propagator_text_map.inject()
end
@doc ~S"""
Performs a request using Telepoison with the provided `t:HTTPoison.Request/0` `request`.
Depending how `Telepoison` is configured and whether or not the `:ot_resource_route`
option is set to `:infer` (provided as a part of the `t:HTTPoison.Request/0` `options` `Keyword list`)
this may attempt to automatically set the `http.route` Open Telemetry metadata attribute by obtaining
the first segment of the `t:HTTPoison.Request/0` `url` (since this part typically does not contain dynamic data)
If this behavior is not desirable, it can be set directly as a string or a function
with an arity of 1 (the `t:HTTPoison.Request/0` `request`) by using the aforementioned `:ot_resource_route` option.
It can also be circumvented entirely by suppling `:ignore` instead.
## Examples
iex> request = %HTTPoison.Request{
...> method: :post,
...> url: "https://www.example.com/users/edit/2",
...> body: ~s({"foo": 3}),
...> headers: [{"Accept", "application/json"}]}
iex> Telepoison.request(request)
iex> request = %HTTPoison.Request{
...> method: :post,
...> url: "https://www.example.com/users/edit/2",
...> body: ~s({"foo": 3}),
...> headers: [{"Accept", "application/json"}],
...> options: [ot_resource_route: :infer]}
iex> Telepoison.request(request)
iex> resource_route = "/users/edit/"
iex> request = %HTTPoison.Request{
...> method: :post,
...> url: "https://www.example.com/users/edit/2",
...> body: ~s({"foo": 3}),
...> headers: [{"Accept", "application/json"}],
...> options: [ot_resource_route: resource_route]}
iex> Telepoison.request(request)
iex> infer_fn = fn
...> %HTTPoison.Request{} = request -> URI.parse(request.url).path
...> end
iex> request = %HTTPoison.Request{
...> method: :post,
...> url: "https://www.example.com/users/edit/2",
...> body: ~s({"foo": 3}),
...> headers: [{"Accept", "application/json"}],
...> options: [ot_resource_route: infer_fn]}
iex> Telepoison.request(request)
iex> request = %HTTPoison.Request{
...> method: :post,
...> url: "https://www.example.com/users/edit/2",
...> body: ~s({"foo": 3}),
...> headers: [{"Accept", "application/json"}],
...> options: [ot_resource_route: :ignore]}
iex> Telepoison.request(request)
"""
def request(%Request{options: opts} = request) do
save_parent_ctx()
span_name = Keyword.get_lazy(opts, :ot_span_name, fn -> default_span_name(request) end)
%URI{scheme: scheme, host: host, port: port} = request.url |> process_request_url() |> URI.parse()
resource_route_attribute =
opts
|> Keyword.get(:ot_resource_route, :unset)
|> get_resource_route(request)
|> case do
resource_route when is_binary(resource_route) ->
[{@http_route, resource_route}, {@url_template, resource_route}]
nil ->
[]
end
ot_attributes =
get_standard_ot_attributes(request, scheme, host, port) ++
get_ot_attributes(opts) ++
resource_route_attribute
request_ctx = Tracer.start_span(span_name, %{kind: :client, attributes: ot_attributes})
Tracer.set_current_span(request_ctx)
result = super(request)
if Tracer.current_span_ctx() == request_ctx do
case result do
{:error, %{reason: reason}} ->
Tracer.set_status(:error, inspect(reason))
end_span()
_ ->
:ok
end
end
result
end
def process_response_status_code(status_code) do
# https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/http.md#status
if status_code >= 400 do
Tracer.set_status(:error, "")
end
Tracer.set_attribute(@http_response_status_code, status_code)
Tracer.set_attribute(@http_status_code, status_code)
end_span()
status_code
end
defp end_span do
Tracer.end_span()
restore_parent_ctx()
end
# see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#name
defp default_span_name(request), do: request.method |> Atom.to_string() |> String.upcase()
@ctx_key {__MODULE__, :parent_ctx}
defp save_parent_ctx do
ctx = Tracer.current_span_ctx()
Process.put(@ctx_key, ctx)
end
defp restore_parent_ctx do
ctx = Process.get(@ctx_key, :undefined)
Process.delete(@ctx_key)
Tracer.set_current_span(ctx)
end
defp get_standard_ot_attributes(request, scheme, host, port) do
[
{@http_method,
request.method
|> Atom.to_string()
|> String.upcase()},
{@http_request_method,
request.method
|> Atom.to_string()
|> String.upcase()},
{@http_url, strip_uri_credentials(request.url)},
{@net_peer_name, host},
{@server_address, host},
{@server_port, port},
{@url_full, strip_uri_credentials(request.url)},
{@url_scheme, scheme}
]
end
defp get_ot_attributes(opts) do
default_ot_attributes = Configuration.get(:ot_attributes)
default_ot_attributes
|> Enum.concat(Keyword.get(opts, :ot_attributes, []))
|> Enum.reduce(%{}, fn {key, value}, acc -> Map.put(acc, key, value) end)
|> Enum.into([], fn {key, value} -> {key, value} end)
end
defp get_resource_route(option, request)
defp get_resource_route(route, _) when is_binary(route), do: route
defp get_resource_route(infer_fn, request) when is_function(infer_fn, 1), do: infer_fn.(request)
defp get_resource_route(:infer, request), do: Configuration.get(:infer_route).(request)
defp get_resource_route(:ignore, _), do: nil
defp get_resource_route(:unset, _), do: nil
defp get_resource_route(_unknown_option, _),
do:
raise(
ArgumentError,
"The :ot_resource_route keyword option value must either be a binary, a function with an arity of 1 or the :infer or :ignore atom"
)
defp strip_uri_credentials(uri) do
uri |> URI.parse() |> Map.put(:userinfo, nil) |> Map.put(:authority, nil) |> URI.to_string()
end
end