UserAgent.pm

filter: Statementstmt 88.8% 16 / 18 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.6% 22 / 24 CC 1 SCAR 0.5
CC
1
Cov
89%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« UserAgent/TestSuiteInjection.pm ↑ Summary
1 package OpenTelemetry::Instrumentation::Mojo::UserAgent;
2 # ABSTRACT: OpenTelemetry instrumentation for Mojo::UserAgent
3  
4 our $VERSION = '0.01';
5  
6 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use experimental 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 1 ▶use Class::Inspector;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Class::Method::Modifiers 'install_modifier';
Subroutine BEGIN: called CC=1 SCAR=0.0
12 0 ▶use Feature::Compat::Try;
Subroutine BEGIN: called CC=1 SCAR=2.6
13 use List::Util 'none';
14 use Syntax::Keyword::Dynamically;
15 use OpenTelemetry::Constants qw(SPAN_KIND_CLIENT SPAN_STATUS_ERROR);
16 use OpenTelemetry::Context;
17 use OpenTelemetry::Trace;
18 use OpenTelemetry;
19  
20 use parent 'OpenTelemetry::Instrumentation';
21  
22 sub dependencies {'Mojo::UserAgent'}
23  
24 my sub get_headers($headers, $want, $prefix) {
25 return unless @$want;
26  
27 my %attributes;
28 for my $name (@{$headers->names}) {
29 (my $key = $name) =~ tr/-/_/;
30 next if none {$key =~ $_} @$want;
31 push @{$attributes{ $prefix . '.' . lc $key } //= []},
32 @{$headers->every_header($name)};
33 }
34  
35 %attributes;
36 }
37  
38 my ($original, $loaded);
39  
40 sub uninstall($class) {
41 return unless $loaded;
42 no strict 'refs';
43 no warnings 'redefine';
44 delete $Class::Method::Modifiers::MODIFIER_CACHE{'Mojo::UserAgent'}{start};
45 *{'Mojo::UserAgent::start'} = $original;
46 undef $loaded;
47 return;
48 }
49  
50 sub install($class, %config) {
51 return if $loaded;
52 return unless Class::Inspector->loaded('Mojo::UserAgent');
53  
54 my @wanted_request_headers = map qr/^\Q$_\E$/i, map tr/-/_/r,
55 @{delete $config{request_headers} // []};
56  
57 my @wanted_response_headers = map qr/^\Q$_\E$/i, map tr/-/_/r,
58 @{delete $config{response_headers} // []};
59  
60 $original = \&Mojo::UserAgent::start;
61 install_modifier 'Mojo::UserAgent' => around => start => sub {
62 my ($code, $self, $tx, $cb, @rest) = @_;
63  
64 my $request = $tx->req;
65 my $url = $request->url->clone;
66 my $method = $request->method;
67 my $length = $request->body_size;
68  
69 $url->userinfo('REDACTED:REDACTED') if $url->userinfo;
70  
71 my $agent = $self->transactor->name;
72  
73 my $span = OpenTelemetry->tracer_provider->tracer(
74 name => __PACKAGE__,
75 version => $VERSION,
76 )->create_span(
77 name => $method,
78 kind => SPAN_KIND_CLIENT,
79 attributes => {
80 # As per https://github.com/open-telemetry/semantic-conventions/blob/main/docs/http/http-spans.md
81 'http.request.method' => $method,
82 'network.protocol.name' => 'http',
83 'network.protocol.version' => $request->version,
84 'network.transport' => 'tcp',
85 'server.address' => $url->host,
86 'server.port' => $url->port
87 // ($url->protocol eq 'https' ? 443 : 80),
88 'url.full' => "$url", # redacted
89  
90 get_headers(
91 $request->headers,
92 \@wanted_request_headers,
93 'http.request.header',
94 ),
95  
96 $agent ? ('user_agent.original' => $agent) : (),
97 $length ? ('http.request.body.size' => $length) : (),
98 },
99 );
100  
101 my $context = OpenTelemetry::Trace->context_with_span($span);
102  
103 OpenTelemetry->propagator->inject(
104 $request->headers,
105 $context,
106 sub {shift->header(@_)},
107 );
108  
109 # Blocking requests run the entire exchange within this call,
110 # so we can localize the context around it. Mojo's own finish
111 # callbacks fire inside this scope, so they see our span.
112 # Note that the transaction returned by start() is the final
113 # one: if any redirects were followed, the transaction we
114 # were given has been replaced by then
115 unless ($cb) {
116 dynamically OpenTelemetry::Context->current = $context;
117  
118 try {
119 my $result = $self->$code($tx, @rest);
120 record_response($span, $result // $tx, \@wanted_response_headers);
121 return $result;
122 } catch ($error) {
123 report_error($span, $error);
124 die $error;
125 } finally {
126 $span->end;
127 };
128 }
129  
130 # Non-blocking requests (including promise-based ones, which
131 # call start with an internal callback) report and end the
132 # span inside a wrapper around the given callback, restoring
133 # the context in case it wants to do more work (eg. more
134 # requests, which would then be children of our span)
135 my $result;
136 try {
137 $result = $self->$code($tx, @rest, sub($ua, $finished_tx) {
138 dynamically OpenTelemetry::Context->current = $context;
139  
140 try {
141 record_response($span, $finished_tx, \@wanted_response_headers);
142 $cb->($ua, $finished_tx);
143 } catch ($error) {
144 report_error($span, $error);
145 die $error;
146 } finally {
147 $span->end;
148 }
149 });
150 } catch ($error) {
151 report_error($span, $error);
152  
153 # start died before it could register our wrapper, so
154 # nothing else will end this span
155 $span->end;
156 die $error;
157 }
158 return $result;
159 };
160  
161 return $loaded = 1;
162 }
163  
164 sub record_response($span, $tx, $wanted) {
165 my $response = $tx->res;
166 my $code = $response->code;
167  
168 my $error = $tx->error;
169 if ($error && !defined($error->{code})) {
170 my $message = $error->{message} // 'Unknown error';
171 $span->record_exception($message);
172 $span->set_status(SPAN_STATUS_ERROR, $message);
173 return;
174 }
175  
176 return unless $code;
177  
178 $span->set_attribute('http.response.status_code' => $code);
179  
180 # Only HTTP transactions can have redirects; WebSocket ones cannot
181 if ($tx->can('redirects') && (my $count = scalar @{$tx->redirects // []})) {
182 $span->set_attribute('http.resend_count' => $count)
183 }
184  
185 my $length = $response->body_size;
186 $span->set_attribute('http.response.body.size' => $length)
187 if $length;
188  
189 $span->set_status(SPAN_STATUS_ERROR, $code)
190 if $code >= 400;
191  
192 $span->set_attribute(
193 get_headers(
194 $response->headers,
195 $wanted,
196 'http.response.header',
197 ),
198 );
199 }
200  
201 sub report_error($span, $error) {
202 my ($description) = split /\n/, $error =~ s/^\s+|\s+$//gr, 2;
203 $description =~ s/ at \S+ line \d+\.$//a;
204  
205 $span->record_exception($error);
206 $span->set_status(SPAN_STATUS_ERROR, $description);
207 }
208  
209 1;
« UserAgent/TestSuiteInjection.pm ↑ Summary