| 1 | package ForgeOps::Tracker; | ||
| 2 | |||
| 3 | 10 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 10 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | 10 | ▶ | use POSIX qw(strftime); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | 10 | ▶ | use ForgeOps::Tracker::ChangeDelivery; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 7 | 10 | ▶ | use ForgeOps::Tracker::Changes; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 8 | 10 | ▶ | use ForgeOps::Tracker::Client; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 9 | 10 | ▶ | use ForgeOps::Tracker::Configuration; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 10 | 0 | ▶ | use ForgeOps::Tracker::DeliveryQueue; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 11 | use ForgeOps::Tracker::EventBuilder; | ||
| 12 | use ForgeOps::Tracker::MetricBuffer; | ||
| 13 | use ForgeOps::Tracker::PerformanceFlusher; | ||
| 14 | use ForgeOps::Tracker::Reporter; | ||
| 15 | use ForgeOps::Tracker::SpanBuffer; | ||
| 16 | use ForgeOps::Tracker::SpanDelivery; | ||
| 17 | use ForgeOps::Tracker::StrictPrivacy (); | ||
| 18 | use ForgeOps::Tracker::TraceParent; | ||
| 19 | use Scalar::Util (); | ||
| 20 | use Time::HiRes (); | ||
| 21 | |||
| 22 | # 0.2.0 was never bumped past: that exact tarball was uploaded to PAUSE once (2026-09-11) but | ||
| 23 | # never made it into the public CPAN index, and PAUSE permanently refuses a second upload of a | ||
| 24 | # distribution+version pair it already has on record, even one that never indexed (confirmed | ||
| 25 | # directly: retrying the identical 0.2.0 tarball came back 409 Conflict, not the original success | ||
| 26 | # response repeated). No functional change from 0.2.0; this bump exists solely to get a fresh, | ||
| 27 | # uploadable version number. | ||
| 28 | our $VERSION = '0.18.0'; | ||
| 29 | |||
| 30 | my $configuration; | ||
| 31 | my $reporter; | ||
| 32 | my $performance_flusher; | ||
| 33 | my $span_queue; | ||
| 34 | my $change_queue; | ||
| 35 | my $change_snapshot_sent = 0; | ||
| 36 | my $environment_warning_given = 0; | ||
| 37 | my $https_warning_given = 0; | ||
| 38 | my ($metric_buffer, $infrastructure_metric_buffer); | ||
| 39 | |||
| 40 | # The affected user set via set_user() below, if any: a plain package variable, the same | ||
| 41 | # "shared-nothing between requests" reasoning as sdks/php's own static property (see that | ||
| 42 | # client's own comment): a typical Perl PSGI deployment (Starman, uWSGI, mod_perl's own prefork | ||
| 43 | # workers) is one process per worker, forked fresh before serving any request, so this is safely | ||
| 44 | # request-scoped there without needing a thread-local. Request-handling code under a threaded or | ||
| 45 | # event-loop-based PSGI server should `local`-ize this instead of assigning to it directly, the | ||
| 46 | # same way Dancer2 itself already uses `local` for its own per-request state. | ||
| 47 | our $current_user; | ||
| 48 | |||
| 49 | # The breadcrumb trail add_breadcrumb() below appends to: a plain package array, the same | ||
| 50 | # one-process-per-worker reasoning as $current_user above. Unlike $current_user, it accumulates | ||
| 51 | # over a request's lifetime rather than being set once, so the PSGI/Dancer2 integrations clear it | ||
| 52 | # at the start of each request themselves (see clear_breadcrumbs); a prefork worker serves many | ||
| 53 | # requests in a row, and without that one request's trail would leak into the next. Request- | ||
| 54 | # handling code under a threaded or event-loop-based PSGI server should `local`-ize this array | ||
| 55 | # instead, exactly as $current_user's own comment describes. | ||
| 56 | our @current_breadcrumbs; | ||
| 57 | |||
| 58 | # The trace span() and record_span() below record into, if one is open: a plain package variable, | ||
| 59 | # same reasoning as @current_breadcrumbs above. The PSGI/Dancer2 performance integrations start | ||
| 60 | # and finish it around every request; finish_trace() always clears it, so nothing leaks into the | ||
| 61 | # next request a prefork worker serves. Request-handling code under a threaded or event-loop-based | ||
| 62 | # PSGI server should `local`-ize it instead. | ||
| 63 | our $current_trace; | ||
| 64 | |||
| 65 | # The current request's context, if one is running: { trace_id, parent_span_id, transaction_name, | ||
| 66 | # endpoint, errored }. Set by start_trace() whether or not span tracing is on (the trace id is also | ||
| 67 | # what links an error to errors in other services), cleared by finish_trace(), and a plain package | ||
| 68 | # variable for the same reason as $current_trace above (`local`-ize it the same way under a | ||
| 69 | # threaded or event-loop PSGI server). | ||
| 70 | our $current_request; | ||
| 71 | |||
| 72 | # Request context remembered for an error that escaped a request (see snapshot_onto), for when it | ||
| 73 | # is only reported after finish_trace() has already cleared $current_request: the PSGI error | ||
| 74 | # middleware sits outside the performance one, and Dancer2 runs its on_route_exception hooks in | ||
| 75 | # whatever order the plugins were loaded. A short list rather than something attached to the | ||
| 76 | # error itself, since a Perl error is as often a plain string as an object; newest first. | ||
| 77 | my @escaped; | ||
| 78 | my $MAX_ESCAPED = 8; | ||
| 79 | sub _configuration { | ||
| 80 | $configuration ||= ForgeOps::Tracker::Configuration->new; | ||
| 81 | return $configuration; | ||
| 82 | } | ||
| 83 | |||
| 84 | sub _reporter { | ||
| 85 | unless ($reporter) { | ||
| 86 | my $config = _configuration(); | ||
| 87 | my $client = ForgeOps::Tracker::Client->new($config); | ||
| 88 | my $delivery_queue = ForgeOps::Tracker::DeliveryQueue->new($config, $client); | ||
| 89 | $reporter = ForgeOps::Tracker::Reporter->new($config, ForgeOps::Tracker::EventBuilder->new($config), $delivery_queue); | ||
| 90 | } | ||
| 91 | return $reporter; | ||
| 92 | } | ||
| 93 | |||
| 94 | sub _performance_flusher { | ||
| 95 | unless ($performance_flusher) { | ||
| 96 | my $config = _configuration(); | ||
| 97 | my $client = ForgeOps::Tracker::Client->new($config); | ||
| 98 | $performance_flusher = ForgeOps::Tracker::PerformanceFlusher->new($config, $client); | ||
| 99 | } | ||
| 100 | return $performance_flusher; | ||
| 101 | } | ||
| 102 | |||
| 103 | sub _metric_buffers { | ||
| 104 | unless ($metric_buffer) { | ||
| 105 | my $config = _configuration(); | ||
| 106 | my $client = ForgeOps::Tracker::Client->new($config); | ||
| 107 | $metric_buffer = ForgeOps::Tracker::MetricBuffer->new( | ||
| 108 | $config, sub { $client->deliver_metrics($_[0]); $client->last_status }, sub { $config->{metric_flush_interval} }, | ||
| 109 | ); | ||
| 110 | $infrastructure_metric_buffer = ForgeOps::Tracker::MetricBuffer->new( | ||
| 111 | $config, sub { $client->deliver_infrastructure_metrics($_[0]); $client->last_status }, sub { $config->{infrastructure_metric_flush_interval} }, | ||
| 112 | ); | ||
| 113 | } | ||
| 114 | return ($metric_buffer, $infrastructure_metric_buffer); | ||
| 115 | } | ||
| 116 | |||
| 117 | sub _span_queue { | ||
| 118 | unless ($span_queue) { | ||
| 119 | my $config = _configuration(); | ||
| 120 | my $client = ForgeOps::Tracker::Client->new($config); | ||
| 121 | $span_queue = ForgeOps::Tracker::DeliveryQueue->new($config, ForgeOps::Tracker::SpanDelivery->new($client)); | ||
| 122 | } | ||
| 123 | return $span_queue; | ||
| 124 | } | ||
| 125 | |||
| 126 | sub _change_queue { | ||
| 127 | unless ($change_queue) { | ||
| 128 | my $config = _configuration(); | ||
| 129 | my $client = ForgeOps::Tracker::Client->new($config); | ||
| 130 | $change_queue = ForgeOps::Tracker::DeliveryQueue->new($config, ForgeOps::Tracker::ChangeDelivery->new($client)); | ||
| 131 | } | ||
| 132 | return $change_queue; | ||
| 133 | } | ||
| 134 | |||
| 135 | # record_change(kind => ..., title => ..., %optional): records one thing that changed in a running | ||
| 136 | # system, so ForgeOps can show it next to the errors and slowdowns that followed, e.g.: | ||
| 137 | # | ||
| 138 | # ForgeOps::Tracker::record_change( | ||
| 139 | # kind => 'feature_flag', | ||
| 140 | # title => 'Enabled new_checkout for 10%', | ||
| 141 | # details => { rollout => 10 }, | ||
| 142 | # ); | ||
| 143 | # | ||
| 144 | # kind is one of feature_flag, config, migration, dependency, infrastructure, or other (anything | ||
| 145 | # else is sent as "other"). Optional: details (a hashref), environment (defaults to the configured | ||
| 146 | # one), service, actor, url, id (an idempotency key), and occurred_at (an ISO 8601 string or epoch | ||
| 147 | # seconds, defaulting to now). Delivered from the same kind of background thread as error events, | ||
| 148 | # so it never blocks the caller. Does nothing when the client isn't enabled. Never dies: returns 0 | ||
| 149 | # when nothing was queued. | ||
| 150 | sub record_change { | ||
| 151 | my (%change) = @_; | ||
| 152 | my $queued = eval { | ||
| 153 | my $config = _configuration(); | ||
| 154 | return 0 unless $config->is_enabled; | ||
| 155 | |||
| 156 | my $payload = ForgeOps::Tracker::Changes::build_change($config, %change); | ||
| 157 | return 0 unless $payload; | ||
| 158 | |||
| 159 | return _change_queue()->push([ change => $payload ]); | ||
| 160 | }; | ||
| 161 | if ($@) { | ||
| 162 | eval { _configuration()->log("[forge-ops-tracker] record_change failed: $@") }; | ||
| 163 | return 0; | ||
| 164 | } | ||
| 165 | return $queued; | ||
| 166 | } | ||
| 167 | |||
| 168 | # Queues the one startup snapshot this process sends (see ForgeOps::Tracker::Changes) for the | ||
| 169 | # change queue's background thread, so init() never waits on the network. A second call is a no-op, | ||
| 170 | # and so is a call while the client isn't enabled or detect_changes is off (without using up the | ||
| 171 | # once). Never dies. | ||
| 172 | sub _start_change_snapshot { | ||
| 173 | my ($config) = @_; | ||
| 174 | eval { | ||
| 175 | return if $change_snapshot_sent || !$config->is_enabled || !$config->{detect_changes}; | ||
| 176 | $change_snapshot_sent = 1; | ||
| 177 | _change_queue()->push([ snapshot => ForgeOps::Tracker::Changes::build_snapshot($config) ]); | ||
| 178 | }; | ||
| 179 | return; | ||
| 180 | } | ||
| 181 | |||
| 182 | # init(%overrides): configure the client. Call once at startup, e.g.: | ||
| 183 | # | ||
| 184 | # ForgeOps::Tracker::init(dsn => 'https://<api_key>@getforgeops.net/api/v1/events'); | ||
| 185 | # | ||
| 186 | # Any Configuration field can be overridden by name. | ||
| 187 | sub init { | ||
| 188 | my (%overrides) = @_; | ||
| 189 | my $config = _configuration(); | ||
| 190 | |||
| 191 | for my $key (keys %overrides) { | ||
| 192 | die "Configuration has no property '$key'" unless exists $config->{$key}; | ||
| 193 | $config->{$key} = $overrides{$key}; | ||
| 194 | } | ||
| 195 | |||
| 196 | _warn_once_if_environment_is_not_enabled($config); | ||
| 197 | _warn_once_if_https_is_unavailable($config); | ||
| 198 | _start_change_snapshot($config); | ||
| 199 | |||
| 200 | return $config; | ||
| 201 | } | ||
| 202 | |||
| 203 | # With a DSN set and an environment that doesn't send, every report is silently dropped, which | ||
| 204 | # otherwise looks exactly like a broken setup. Said once per process, through the configured logger, | ||
| 205 | # or as a plain warn (stderr) when there is none. Never without a DSN. | ||
| 206 | sub _warn_once_if_environment_is_not_enabled { | ||
| 207 | my ($config) = @_; | ||
| 208 | return if $environment_warning_given; | ||
| 209 | return unless defined $config->{dsn} && length $config->{dsn}; | ||
| 210 | my $environment = $config->{environment} // ''; | ||
| 211 | my %enabled = %{ $config->{enabled_environments} || {} }; | ||
| 212 | return if $enabled{$environment}; | ||
| 213 | |||
| 214 | $environment_warning_given = 1; | ||
| 215 | my $list = join ', ', sort grep { $enabled{$_} } keys %enabled; | ||
| 216 | my $message = qq{[ForgeOps] Not sending: this environment is "$environment", and only $list are enabled. } | ||
| 217 | . qq{Set FORGE_OPS_ENVIRONMENT=production (or add "$environment" to the enabled environments) to send from here.}; | ||
| 218 | if ($config->{logger}) { | ||
| 219 | $config->log($message); | ||
| 220 | } else { | ||
| 221 | warn "$message\n"; | ||
| 222 | } | ||
| 223 | return; | ||
| 224 | } | ||
| 225 | |||
| 226 | # A ForgeOps DSN is https, and HTTP::Tiny can only speak https with IO::Socket::SSL and Net::SSLeay | ||
| 227 | # installed, which aren't core Perl. Without them every delivery fails quietly inside the client, | ||
| 228 | # which looks exactly like a broken setup. They're prerequisites from 0.12.3 on, so this is for a | ||
| 229 | # perl where they were removed, or the SDK was copied in rather than installed. Said once per | ||
| 230 | # process, the same way as the environment warning. Never without a DSN, or for an http one. | ||
| 231 | sub _warn_once_if_https_is_unavailable { | ||
| 232 | my ($config) = @_; | ||
| 233 | return if $https_warning_given; | ||
| 234 | return unless defined $config->{dsn} && $config->{dsn} =~ m{^https://}i; | ||
| 235 | return unless HTTP::Tiny->can('can_ssl'); | ||
| 236 | my ($ok) = HTTP::Tiny->can_ssl; | ||
| 237 | return if $ok; | ||
| 238 | |||
| 239 | $https_warning_given = 1; | ||
| 240 | my $message = q{[ForgeOps] Not sending: the DSN is https, and this perl can't make https requests. } | ||
| 241 | . q{Install IO::Socket::SSL and Net::SSLeay (cpanm IO::Socket::SSL Net::SSLeay) to send.}; | ||
| 242 | if ($config->{logger}) { | ||
| 243 | $config->log($message); | ||
| 244 | } else { | ||
| 245 | warn "$message\n"; | ||
| 246 | } | ||
| 247 | return; | ||
| 248 | } | ||
| 249 | |||
| 250 | # report($error, \%context, \%user): report an exception you've already caught, e.g.: | ||
| 251 | # | ||
| 252 | # eval { risky_operation() }; | ||
| 253 | # if ($@) { | ||
| 254 | # ForgeOps::Tracker::report($@, { order_id => $order->id }); | ||
| 255 | # } | ||
| 256 | # | ||
| 257 | # \%user defaults to whatever set_user() last set (undef if nothing did); pass one explicitly to | ||
| 258 | # override that for this one report. | ||
| 259 | # | ||
| 260 | # During a request (between start_trace and finish_trace), the event also carries the request's | ||
| 261 | # trace_id, transaction_name and endpoint, and the request is marked errored so its trace is sent | ||
| 262 | # however fast it was. An error one of the integrations saw escape a request falls back to what | ||
| 263 | # snapshot_onto remembered for it (along with the user and breadcrumb trail), for when it's | ||
| 264 | # reported only after the request's own state is gone. | ||
| 265 | sub report { | ||
| 266 | my ($error, $context, $user) = @_; | ||
| 267 | my $snapshot = $current_request ? undef : _snapshot_for($error); | ||
| 268 | $current_request->{errored} = 1 if $current_request; | ||
| 269 | |||
| 270 | my $source = $current_request || $snapshot || {}; | ||
| 271 | $user = $current_user unless defined $user; | ||
| 272 | $user = $snapshot->{user} if !defined $user && $snapshot; | ||
| 273 | my @breadcrumbs = @current_breadcrumbs; | ||
| 274 | @breadcrumbs = @{ $snapshot->{breadcrumbs} } if !@breadcrumbs && $snapshot; | ||
| 275 | |||
| 276 | _reporter()->report($error, $context, $user, \@breadcrumbs, { | ||
| 277 | map { $_ => $source->{$_} } qw(transaction_name endpoint trace_id) | ||
| 278 | }); | ||
| 279 | return; | ||
| 280 | } | ||
| 281 | |||
| 282 | # current_trace_id(): the current request's W3C trace id (32 lowercase hex characters), or undef | ||
| 283 | # outside a request. Handy for your own logs: it's the id ForgeOps links errors across services | ||
| 284 | # with. | ||
| 285 | sub current_trace_id { | ||
| 286 | return $current_request ? $current_request->{trace_id} : undef; | ||
| 287 | } | ||
| 288 | |||
| 289 | # set_request_route($transaction_name, $endpoint): names the current request once its route is | ||
| 290 | # known. $transaction_name is the same name its performance sample and root span use, $endpoint | ||
| 291 | # the HTTP method plus the route pattern ("GET /users/:id"), never the literal path. The Dancer2 | ||
| 292 | # performance plugin calls this as soon as Dancer2 has matched the route, so an error reported | ||
| 293 | # from inside the route already carries both; plain PSGI has no route pattern of its own, so a | ||
| 294 | # PSGI app that has one (from its own router) can call this itself. Does nothing outside a request. | ||
| 295 | sub set_request_route { | ||
| 296 | my ($transaction_name, $endpoint) = @_; | ||
| 297 | return unless $current_request; | ||
| 298 | $current_request->{transaction_name} = $transaction_name; | ||
| 299 | $current_request->{endpoint} = $endpoint; | ||
| 300 | return; | ||
| 301 | } | ||
| 302 | |||
| 303 | # snapshot_onto($error): remembers the current request's trace id, transaction name and endpoint, | ||
| 304 | # plus the affected user and breadcrumb trail, for $error, and marks the request errored. Called by | ||
| 305 | # the PSGI/Dancer2 performance integrations when an error escapes a request, just before they | ||
| 306 | # finish its trace, so a report made afterward (see report) still has all of it. The first snapshot | ||
| 307 | # for the same error wins: the innermost one saw the request closest to where it failed. Never | ||
| 308 | # dies. Not something app code normally calls directly. | ||
| 309 | sub snapshot_onto { | ||
| 310 | my ($error) = @_; | ||
| 311 | eval { | ||
| 312 | return unless $current_request && defined $error; | ||
| 313 | $current_request->{errored} = 1; | ||
| 314 | return if _snapshot_for($error); | ||
| 315 | |||
| 316 | my $entry = { | ||
| 317 | (ref $error ? (address => Scalar::Util::refaddr($error), error => $error) : (text => "$error")), | ||
| 318 | user => $current_user, | ||
| 319 | breadcrumbs => [ map { { %$_ } } @current_breadcrumbs ], | ||
| 320 | map { $_ => $current_request->{$_} } qw(transaction_name endpoint trace_id), | ||
| 321 | }; | ||
| 322 | Scalar::Util::weaken($entry->{error}) if ref $error; | ||
| 323 | unshift @escaped, $entry; | ||
| 324 | splice @escaped, $MAX_ESCAPED if @escaped > $MAX_ESCAPED; | ||
| 325 | 1; | ||
| 326 | }; | ||
| 327 | return; | ||
| 328 | } | ||
| 329 | |||
| 330 | sub _snapshot_for { | ||
| 331 | my ($error) = @_; | ||
| 332 | return undef unless defined $error; | ||
| 333 | for my $entry (@escaped) { | ||
| 334 | if (ref $error) { | ||
| 335 | return $entry if defined $entry->{error} && $entry->{address} == Scalar::Util::refaddr($error); | ||
| 336 | } elsif (defined $entry->{text} && $entry->{text} eq $error) { | ||
| 337 | return $entry; | ||
| 338 | } | ||
| 339 | } | ||
| 340 | return undef; | ||
| 341 | } | ||
| 342 | |||
| 343 | # set_user(%user): manually attaches an affected user to whatever gets reported for the rest of | ||
| 344 | # this process (or, under a threaded/event-loop PSGI server, `local`-ize $current_user directly | ||
| 345 | # instead: see that variable's own comment). id/email/username are all independently optional; | ||
| 346 | # call with no arguments to clear whatever was set, e.g.: | ||
| 347 | # | ||
| 348 | # ForgeOps::Tracker::set_user(id => $user->id, email => $user->email); | ||
| 349 | # ForgeOps::Tracker::set_user(); # clear it | ||
| 350 | sub set_user { | ||
| 351 | my (%user) = @_; | ||
| 352 | my %defined = map { $_ => $user{$_} } grep { defined $user{$_} } keys %user; | ||
| 353 | $current_user = %defined ? \%defined : undef; | ||
| 354 | return; | ||
| 355 | } | ||
| 356 | |||
| 357 | # add_breadcrumb($message, %options): records one entry in a small, bounded trail of recent | ||
| 358 | # events, attached to whatever report() sends next so an issue's detail page can show what led up | ||
| 359 | # to it. Options: category (default 'custom'), level (default 'info'), data (a hashref of extra | ||
| 360 | # detail, default {}). Only the max_breadcrumbs most recent are kept; does nothing when | ||
| 361 | # track_breadcrumbs is off, or strict_privacy is on (it never sends breadcrumbs), e.g.: | ||
| 362 | # | ||
| 363 | # ForgeOps::Tracker::add_breadcrumb('charging card', category => 'payment', data => { order_id => 42 }); | ||
| 364 | sub add_breadcrumb { | ||
| 365 | my ($message, %options) = @_; | ||
| 366 | my $config = _configuration(); | ||
| 367 | return unless $config->{track_breadcrumbs} && !$config->{strict_privacy}; | ||
| 368 | |||
| 369 | push @current_breadcrumbs, { | ||
| 370 | category => defined $options{category} ? $options{category} : 'custom', | ||
| 371 | message => $message, | ||
| 372 | level => defined $options{level} ? $options{level} : 'info', | ||
| 373 | timestamp => strftime('%Y-%m-%dT%H:%M:%SZ', gmtime), | ||
| 374 | data => defined $options{data} ? $options{data} : {}, | ||
| 375 | }; | ||
| 376 | |||
| 377 | my $max = $config->{max_breadcrumbs}; | ||
| 378 | shift @current_breadcrumbs while @current_breadcrumbs > $max; | ||
| 379 | return; | ||
| 380 | } | ||
| 381 | |||
| 382 | # clear_breadcrumbs(): empties the current trail. The PSGI/Dancer2 integrations call this at the | ||
| 383 | # start of every request themselves; call it by hand at the start of any other unit of work (a | ||
| 384 | # cron job's next iteration, say) that should begin with a fresh trail. | ||
| 385 | sub clear_breadcrumbs { | ||
| 386 | @current_breadcrumbs = (); | ||
| 387 | return; | ||
| 388 | } | ||
| 389 | |||
| 390 | # record_performance($transaction_name, $duration_ms): called by the PSGI/Dancer2 performance | ||
| 391 | # integrations, not typically called directly, e.g.: | ||
| 392 | # | ||
| 393 | # ForgeOps::Tracker::record_performance('GET /users/:id', $elapsed_ms); | ||
| 394 | sub record_performance { | ||
| 395 | my ($transaction_name, $duration_ms) = @_; | ||
| 396 | _performance_flusher()->record($transaction_name, $duration_ms); | ||
| 397 | return; | ||
| 398 | } | ||
| 399 | |||
| 400 | # start_trace($traceparent): starts a fresh trace on this process, discarding any earlier one. The | ||
| 401 | # PSGI/Dancer2 performance integrations call this at the start of every request with the request's | ||
| 402 | # own `traceparent` header: a usable W3C value continues the caller's trace (same trace id, and the | ||
| 403 | # root span's parent is the caller's span), anything else (undef, blank, malformed) starts a new | ||
| 404 | # one. Call it (with finish_trace) yourself to trace anything else, e.g. a queue job. | ||
| 405 | # | ||
| 406 | # The trace id exists whenever the client is enabled, even with track_tracing off, since errors | ||
| 407 | # reported before finish_trace carry it and http_span propagates it; only span recording is gated | ||
| 408 | # on track_tracing. Does nothing when the client isn't enabled. | ||
| 409 | sub start_trace { | ||
| 410 | my ($traceparent) = @_; | ||
| 411 | my $config = _configuration(); | ||
| 412 | $current_trace = undef; | ||
| 413 | $current_request = undef; | ||
| 414 | return unless $config->is_enabled; | ||
| 415 | |||
| 416 | my $incoming = ForgeOps::Tracker::TraceParent::parse($traceparent); | ||
| 417 | $current_request = { | ||
| 418 | trace_id => $incoming ? $incoming->{trace_id} : ForgeOps::Tracker::TraceParent::generate_trace_id(), | ||
| 419 | parent_span_id => $incoming ? $incoming->{parent_span_id} : undef, | ||
| 420 | errored => 0, | ||
| 421 | }; | ||
| 422 | $current_trace = ForgeOps::Tracker::SpanBuffer->new( | ||
| 423 | $config, | ||
| 424 | trace_id => $current_request->{trace_id}, | ||
| 425 | remote_parent_span_id => $current_request->{parent_span_id}, | ||
| 426 | ) if $config->{track_tracing}; | ||
| 427 | return; | ||
| 428 | } | ||
| 429 | |||
| 430 | # finish_trace($name, $started_at, $duration_ms): ends the current trace, queueing it for delivery | ||
| 431 | # when the root took at least trace_capture_threshold seconds or the request errored (an error was | ||
| 432 | # reported during it, or escaped it), and always clears it along with the request context. | ||
| 433 | # $started_at is an epoch-seconds float (Time::HiRes::time). | ||
| 434 | sub finish_trace { | ||
| 435 | my ($name, $started_at, $duration_ms) = @_; | ||
| 436 | my $trace = $current_trace; | ||
| 437 | my $errored = $current_request && $current_request->{errored}; | ||
| 438 | $current_trace = undef; | ||
| 439 | $current_request = undef; | ||
| 440 | return unless $trace; | ||
| 441 | |||
| 442 | my $payload = $trace->finish_trace($name, $started_at, $duration_ms, $errored); | ||
| 443 | # Under strict privacy every span goes through StrictPrivacy::span: an outbound call named by | ||
| 444 | # its method and host only, a root span named by its raw path (the PSGI integration's "GET | ||
| 445 | # /patients/42") cut down to its first segment, and no span data but the masked statement and | ||
| 446 | # db.system. | ||
| 447 | if ($payload && _configuration()->{strict_privacy}) { | ||
| 448 | $payload->{spans} = [ map { ForgeOps::Tracker::StrictPrivacy::span($_) } @{ $payload->{spans} } ]; | ||
| 449 | } | ||
| 450 | _span_queue()->push($payload) if $payload; | ||
| 451 | return; | ||
| 452 | } | ||
| 453 | |||
| 454 | # span($name, $code, kind => 'service', data => {}): runs $code as a child span of whatever span is | ||
| 455 | # open (or of the request's root), returning what it returned. Outside a trace it just runs $code. | ||
| 456 | # Recorded even if $code dies, which is re-raised unchanged. kind is one of controller, service, | ||
| 457 | # database, redis, http, job, other (anything else is sent as "other"), e.g.: | ||
| 458 | # | ||
| 459 | # my $order = ForgeOps::Tracker::span('charge card', sub { $gateway->charge($id) }, data => { order => $id }); | ||
| 460 | # | ||
| 461 | # A database span can also carry the SQL it ran, with statement => and db_system =>: | ||
| 462 | # | ||
| 463 | # my $rows = ForgeOps::Tracker::span('Load orders', sub { $dbh->selectall_arrayref($sql, {}, $id) }, | ||
| 464 | # kind => 'database', statement => $sql, db_system => 'postgresql'); | ||
| 465 | # | ||
| 466 | # The statement is masked (every string and number replaced by "?") and cut to 4000 characters | ||
| 467 | # before it's stored, then sent as "db.statement"; db_system goes out lowercased as "db.system". | ||
| 468 | # Bind values are never taken. Both options are ignored on any other kind of span. | ||
| 469 | sub span { | ||
| 470 | my ($name, $code, %options) = @_; | ||
| 471 | my $trace = $current_trace; | ||
| 472 | return $code->() unless $trace; | ||
| 473 | |||
| 474 | my $kind = defined $options{kind} ? $options{kind} : 'service'; | ||
| 475 | my $data = $kind eq 'database' | ||
| 476 | ? { %{ $options{data} || {} }, %{ database_span_data($options{statement}, $options{db_system}) } } | ||
| 477 | : $options{data}; | ||
| 478 | |||
| 479 | my $wantarray = wantarray; | ||
| 480 | my $id = $trace->open_span; | ||
| 481 | my $started_at = Time::HiRes::time; | ||
| 482 | my (@result, $failed, $error); | ||
| 483 | { | ||
| 484 | local $@; | ||
| 485 | $failed = !eval { | ||
| 486 | if ($wantarray) { @result = $code->() } | ||
| 487 | elsif (defined $wantarray) { $result[0] = $code->() } | ||
| 488 | else { $code->() } | ||
| 489 | 1; | ||
| 490 | }; | ||
| 491 | $error = $@; | ||
| 492 | } | ||
| 493 | $trace->finish($id, $name, $kind, $started_at, (Time::HiRes::time - $started_at) * 1000, $data); | ||
| 494 | die $error if $failed; | ||
| 495 | return $wantarray ? @result : $result[0]; | ||
| 496 | } | ||
| 497 | |||
| 498 | # http_span($method, $url, $code, data => {}): makes one outgoing HTTP call inside the current | ||
| 499 | # trace. Records it as an "http" span named "<METHOD> <host>" (never the path or query, which could | ||
| 500 | # carry an id or a token) and calls $code with a hashref of headers to add to the request, | ||
| 501 | # currently a W3C `traceparent` whose parent id is that span's own id, so the called service's | ||
| 502 | # root span nests under it. Returns what $code returned; the span is recorded even if $code dies, | ||
| 503 | # which is re-raised unchanged, e.g.: | ||
| 504 | # | ||
| 505 | # my $response = ForgeOps::Tracker::http_span(POST => $url, sub { | ||
| 506 | # my ($headers) = @_; | ||
| 507 | # $http->post($url, { headers => { %$headers, 'Content-Type' => 'application/json' }, content => $body }); | ||
| 508 | # }); | ||
| 509 | # | ||
| 510 | # The headers are empty outside a request, when propagate_traces is off, or when the host isn't in | ||
| 511 | # trace_propagation_targets; outside a request no span is recorded either. With track_tracing off | ||
| 512 | # the header is still sent (the trace id links errors across services) but no span is kept. | ||
| 513 | sub http_span { | ||
| 514 | my ($method, $url, $code, %options) = @_; | ||
| 515 | my $request = $current_request; | ||
| 516 | return $code->({}) unless $request; | ||
| 517 | |||
| 518 | my ($host) = (defined $url ? $url : '') =~ m{\A[A-Za-z][A-Za-z0-9+.-]*://(?:[^/?#\@]*\@)?(\[[^\]]*\]|[^:/?#]+)}; | ||
| 519 | $host = lc $host if defined $host; | ||
| 520 | my $span_id = ForgeOps::Tracker::TraceParent::generate_span_id(); | ||
| 521 | my %headers = _configuration()->should_propagate_trace($host) | ||
| 522 | ? (ForgeOps::Tracker::TraceParent::HEADER() => ForgeOps::Tracker::TraceParent::build($request->{trace_id}, $span_id)) | ||
| 523 | : (); | ||
| 524 | |||
| 525 | my $trace = $current_trace; | ||
| 526 | return $code->(\%headers) unless $trace; | ||
| 527 | |||
| 528 | my $wantarray = wantarray; | ||
| 529 | $trace->open_span($span_id); | ||
| 530 | my $started_at = Time::HiRes::time; | ||
| 531 | my (@result, $failed, $error); | ||
| 532 | { | ||
| 533 | local $@; | ||
| 534 | $failed = !eval { | ||
| 535 | if ($wantarray) { @result = $code->(\%headers) } | ||
| 536 | elsif (defined $wantarray) { $result[0] = $code->(\%headers) } | ||
| 537 | else { $code->(\%headers) } | ||
| 538 | 1; | ||
| 539 | }; | ||
| 540 | $error = $@; | ||
| 541 | } | ||
| 542 | $trace->finish( | ||
| 543 | $span_id, uc($method) . ' ' . (defined $host ? $host : 'unknown'), 'http', | ||
| 544 | $started_at, (Time::HiRes::time - $started_at) * 1000, $options{data}, | ||
| 545 | ); | ||
| 546 | die $error if $failed; | ||
| 547 | return $wantarray ? @result : $result[0]; | ||
| 548 | } | ||
| 549 | |||
| 550 | # record_span($name, $kind, $started_at, $duration_ms, $data): records a span you timed yourself | ||
| 551 | # under the current one; does nothing outside a trace. $started_at is an epoch-seconds float. | ||
| 552 | sub record_span { | ||
| 553 | my ($name, $kind, $started_at, $duration_ms, $data) = @_; | ||
| 554 | $current_trace->record_leaf($name, $kind, $started_at, $duration_ms, $data) if $current_trace; | ||
| 555 | return; | ||
| 556 | } | ||
| 557 | |||
| 558 | # record_database_span($name, $statement, $started_at, $duration_ms, db_system => ...): a query you | ||
| 559 | # timed yourself, recorded as a "database" span carrying its SQL, masked as span() masks it. Does | ||
| 560 | # nothing outside a trace. | ||
| 561 | sub record_database_span { | ||
| 562 | my ($name, $statement, $started_at, $duration_ms, %options) = @_; | ||
| 563 | record_span($name, 'database', $started_at, $duration_ms, database_span_data($statement, $options{db_system})); | ||
| 564 | return; | ||
| 565 | } | ||
| 566 | |||
| 567 | # database_span_data($statement, $db_system): the data a database span carries, "db.statement" | ||
| 568 | # and "db.system" (lowercased), each left out when undef or blank. A "db.statement" on any database | ||
| 569 | # span is masked when the span is recorded, however its data was built. | ||
| 570 | sub database_span_data { | ||
| 571 | my ($statement, $db_system) = @_; | ||
| 572 | my %data; | ||
| 573 | $data{'db.statement'} = $statement if defined $statement && !ref $statement && $statement =~ /\S/; | ||
| 574 | if (defined $db_system && !ref $db_system && $db_system =~ /\S/) { | ||
| 575 | (my $system = lc $db_system) =~ s/\A\s+|\s+\z//g; | ||
| 576 | $data{'db.system'} = $system; | ||
| 577 | } | ||
| 578 | return \%data; | ||
| 579 | } | ||
| 580 | |||
| 581 | # capture_metric($name, $value = 1): records a named business metric (a signup, a payment, anything | ||
| 582 | # you want to name), buffered and flushed periodically as one batch rather than one network call per | ||
| 583 | # capture. $value defaults to 1 so a bare counter-style call needs no argument; pass one for a real | ||
| 584 | # magnitude (capture_metric('payment', 49)); it may be negative (a refund). Does nothing when the | ||
| 585 | # client isn't enabled (no DSN, or this environment isn't in enabled_environments), and a | ||
| 586 | # non-numeric value is dropped. | ||
| 587 | sub capture_metric { | ||
| 588 | my ($name, $value) = @_; | ||
| 589 | $value = 1 unless defined $value; | ||
| 590 | my $config = _configuration(); | ||
| 591 | return unless $config->is_enabled; | ||
| 592 | |||
| 593 | my ($metrics) = _metric_buffers(); | ||
| 594 | $metrics->record({ metric_name => $name, value => $value, environment => $config->{environment}, release => $config->{release} }); | ||
| 595 | return; | ||
| 596 | } | ||
| 597 | |||
| 598 | # capture_infrastructure_metric($name, $value, hostname => $host): records one infrastructure reading | ||
| 599 | # (CPU, memory, disk, anything else a script of yours reads) from one of your own hosts. hostname | ||
| 600 | # defaults to server_name, so a script running on the box it reports about needs no argument. Same | ||
| 601 | # buffered-batch delivery and no-op-when-disabled contract as capture_metric. A program that ends | ||
| 602 | # normally flushes what is left from an END block, so a short-lived cron script needs nothing more; | ||
| 603 | # call flush_metrics() if it might exit another way (POSIX::_exit). | ||
| 604 | sub capture_infrastructure_metric { | ||
| 605 | my ($name, $value, %options) = @_; | ||
| 606 | my $config = _configuration(); | ||
| 607 | return unless $config->is_enabled; | ||
| 608 | |||
| 609 | my (undef, $infrastructure) = _metric_buffers(); | ||
| 610 | $infrastructure->record({ | ||
| 611 | metric_name => $name, | ||
| 612 | value => $value, | ||
| 613 | hostname => defined $options{hostname} ? $options{hostname} : $config->{server_name}, | ||
| 614 | }); | ||
| 615 | return; | ||
| 616 | } | ||
| 617 | |||
| 618 | # flush_metrics(): delivers every buffered metric and infrastructure reading right now, instead of | ||
| 619 | # waiting for the next flush interval. | ||
| 620 | sub flush_metrics { | ||
| 621 | $metric_buffer->flush if $metric_buffer; | ||
| 622 | $infrastructure_metric_buffer->flush if $infrastructure_metric_buffer; | ||
| 623 | return; | ||
| 624 | } | ||
| 625 | |||
| 626 | # flush($timeout): sends every error event, change and trace still waiting on the background thread | ||
| 627 | # right now, and waits for one it already has under way, giving up after $timeout seconds (default | ||
| 628 | # 5). Returns 1 if everything went out in time. A program that ends normally does this by itself | ||
| 629 | # from an END block, so a script that reports an error and exits needs nothing more; call flush() if | ||
| 630 | # it might exit another way (POSIX::_exit, exec) or you want delivery confirmed before moving on. | ||
| 631 | sub flush { | ||
| 632 | my ($timeout) = @_; | ||
| 633 | my @queues = grep { defined } ($reporter && $reporter->{delivery_queue}), $change_queue, $span_queue; | ||
| 634 | return 1 unless @queues; | ||
| 635 | return ForgeOps::Tracker::DeliveryQueue->drain_all($timeout, @queues); | ||
| 636 | } | ||
| 637 | |||
| 638 | # @internal not part of the public API: resets module state between test cases. The startup change | ||
| 639 | # snapshot is left marked as already sent, so the many tests that init() an enabled client against | ||
| 640 | # an echo server don't see an extra request; pass change_snapshot => 1 to let the next init() send | ||
| 641 | # it (see t/changes.t). | ||
| 642 | sub _reset_for_testing { | ||
| 643 | my (%options) = @_; | ||
| 644 | $change_queue = undef; | ||
| 645 | $change_snapshot_sent = $options{change_snapshot} ? 0 : 1; | ||
| 646 | $environment_warning_given = 0; | ||
| 647 | $https_warning_given = 0; | ||
| 648 | $configuration = undef; | ||
| 649 | $reporter = undef; | ||
| 650 | $performance_flusher = undef; | ||
| 651 | $span_queue = undef; | ||
| 652 | $metric_buffer->_clear if $metric_buffer; | ||
| 653 | $infrastructure_metric_buffer->_clear if $infrastructure_metric_buffer; | ||
| 654 | $metric_buffer = undef; | ||
| 655 | $infrastructure_metric_buffer = undef; | ||
| 656 | $current_trace = undef; | ||
| 657 | $current_request = undef; | ||
| 658 | @escaped = (); | ||
| 659 | $current_user = undef; | ||
| 660 | @current_breadcrumbs = (); | ||
| 661 | return; | ||
| 662 | } | ||
| 663 | |||
| 664 | 1; | ||
| 665 | |||
| 666 | __END__ | ||