| 1 | package ForgeOps::Tracker::PerformanceFlusher; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use threads; | ||
| 6 | use threads::shared; | ||
| 7 | use Time::HiRes (); | ||
| 8 | use POSIX qw(strftime); | ||
| 9 | use ForgeOps::Tracker::DeliveryStatus; | ||
| 10 | use ForgeOps::Tracker::HistogramBucketer; | ||
| 11 | use ForgeOps::Tracker::StrictPrivacy (); | ||
| 12 | |||
| 13 | # Times requests in-process, bucketed by transaction name (see the PSGI/Dancer2 performance | ||
| 14 | # integrations), and periodically flushes each distinct bucket as one small aggregate report, | ||
| 15 | # rather than one network call per request. Ported directly from | ||
| 16 | # gems/forge_ops_tracker/lib/forge_ops_tracker/performance_flusher.rb: like Go's own | ||
| 17 | # PerformanceFlusher, there's no existing session-tracking/aggregate-flusher precedent in this | ||
| 18 | # client to mirror the shape of (this SDK has never had a session tracking feature), so this | ||
| 19 | # borrows DeliveryQueue's own lazy-thread-start idiom instead (see that module's own comment), | ||
| 20 | # just clock-triggered (a periodic sleep-then-flush loop) rather than push-triggered (a | ||
| 21 | # Thread::Queue consumer). | ||
| 22 | # | ||
| 23 | # Perl's ithreads share nothing by default, so the buckets this flusher aggregates into have to | ||
| 24 | # be threads::shared explicitly to stay visible to (and safely mutable from) both the thread(s) | ||
| 25 | # calling record() and the background thread that flushes them. Kept as four parallel flat | ||
| 26 | # shared hashes (counts / duration sums / max durations / histogram counts), rather than one shared | ||
| 27 | # hash of hashrefs, since threads::shared has to share nested structures explicitly and flat shared | ||
| 28 | # hashes sidestep that entirely (the histogram hash is keyed "transaction_name<US>bucket_label", | ||
| 29 | # where <US> is the ASCII unit separator, see HISTOGRAM_KEY_SEPARATOR); a single shared scalar | ||
| 30 | # ($self->{lock}) guards every read-modify-write of all four together. | ||
| 31 | use constant HISTOGRAM_KEY_SEPARATOR => "\x1F"; | ||
| 32 | |||
| 33 | sub new { | ||
| 34 | my ($class, $configuration, $client) = @_; | ||
| 35 | |||
| 36 | my %counts :shared; | ||
| 37 | my %duration_sums :shared; | ||
| 38 | my %max_durations :shared; | ||
| 39 | my %histogram_counts :shared; | ||
| 40 | my $lock = 1; | ||
| 41 | share($lock); | ||
| 42 | my $period_started_at; | ||
| 43 | share($period_started_at); | ||
| 44 | $period_started_at = Time::HiRes::time; | ||
| 45 | # Shared like everything above: a flush runs on the background thread or on the caller's. | ||
| 46 | my $failed_flushes = 0; | ||
| 47 | share($failed_flushes); | ||
| 48 | |||
| 49 | return bless { | ||
| 50 | configuration => $configuration, | ||
| 51 | client => $client, | ||
| 52 | counts => \%counts, | ||
| 53 | duration_sums => \%duration_sums, | ||
| 54 | max_durations => \%max_durations, | ||
| 55 | histogram_counts => \%histogram_counts, | ||
| 56 | lock => \$lock, | ||
| 57 | period_started_at => \$period_started_at, | ||
| 58 | failed_flushes => \$failed_flushes, | ||
| 59 | worker => undef, | ||
| 60 | }, $class; | ||
| 61 | } | ||
| 62 | |||
| 63 | # Buckets one request's own duration under transaction_name. | ||
| 64 | sub record { | ||
| 65 | my ($self, $transaction_name, $duration_ms) = @_; | ||
| 66 | my $config = $self->{configuration}; | ||
| 67 | return unless $config->{track_performance} && $config->is_enabled; | ||
| 68 | # Under strict privacy a raw-path name (the PSGI integration's "GET /patients/42") loses its | ||
| 69 | # ids; a route is kept. | ||
| 70 | $transaction_name = ForgeOps::Tracker::StrictPrivacy::transaction_name($transaction_name) if $config->{strict_privacy}; | ||
| 71 | |||
| 72 | $self->_ensure_worker; | ||
| 73 | |||
| 74 | lock(${ $self->{lock} }); | ||
| 75 | $self->{counts}{$transaction_name}++; | ||
| 76 | $self->{duration_sums}{$transaction_name} += $duration_ms; | ||
| 77 | if (!defined($self->{max_durations}{$transaction_name}) | ||
| 78 | || $duration_ms > $self->{max_durations}{$transaction_name}) { | ||
| 79 | $self->{max_durations}{$transaction_name} = $duration_ms; | ||
| 80 | } | ||
| 81 | # The distribution count/sum/max can't reconstruct: see HistogramBucketer for why the server | ||
| 82 | # approximates a percentile from these bucket counts. | ||
| 83 | my $histogram_key = join(HISTOGRAM_KEY_SEPARATOR, $transaction_name, | ||
| 84 | ForgeOps::Tracker::HistogramBucketer::bucket_for($duration_ms)); | ||
| 85 | $self->{histogram_counts}{$histogram_key}++; | ||
| 86 | } | ||
| 87 | |||
| 88 | # Snapshots the buffered buckets, then delivers them as one batch. A failed delivery keeps every | ||
| 89 | # bucket where it is rather than resetting, so the next flush's batch just grows instead of losing | ||
| 90 | # what was already tallied; there's no other copy of this data anywhere. That only holds for a | ||
| 91 | # delivery that failed for now, and only DeliveryStatus::MAX_FAILED_FLUSHES times in a row: a batch | ||
| 92 | # the server rejected, or one that keeps failing, is removed exactly the way a delivered one is, | ||
| 93 | # since re-sending it could never succeed. | ||
| 94 | # | ||
| 95 | # Only exactly what this snapshot delivered is removed afterward, subtracted from whatever is in | ||
| 96 | # each bucket by then, never everything cleared: record() can run on another thread while delivery | ||
| 97 | # is in flight (the lock is released around the network call), so a record for a transaction already | ||
| 98 | # in the snapshot, or a brand-new one, can land between the snapshot and delivery succeeding, and | ||
| 99 | # clearing afterward would silently discard it. max_durations is left as whatever is currently on | ||
| 100 | # the bucket, sent or not: a max can't be "subtracted" back out, and leaving it never overstates | ||
| 101 | # the next period's own max. | ||
| 102 | sub flush { | ||
| 103 | my ($self) = @_; | ||
| 104 | |||
| 105 | my (@names, %counts_snapshot, %sums_snapshot, %max_snapshot, %histogram_snapshot, $period_started_at, $period_ended_at); | ||
| 106 | { | ||
| 107 | lock(${ $self->{lock} }); | ||
| 108 | @names = keys %{ $self->{counts} }; | ||
| 109 | return unless @names; | ||
| 110 | |||
| 111 | $period_started_at = ${ $self->{period_started_at} }; | ||
| 112 | $period_ended_at = Time::HiRes::time; | ||
| 113 | %counts_snapshot = %{ $self->{counts} }; | ||
| 114 | %sums_snapshot = %{ $self->{duration_sums} }; | ||
| 115 | %max_snapshot = %{ $self->{max_durations} }; | ||
| 116 | %histogram_snapshot = %{ $self->{histogram_counts} }; | ||
| 117 | } | ||
| 118 | |||
| 119 | my %histogram_by_name; | ||
| 120 | for my $key (keys %histogram_snapshot) { | ||
| 121 | my ($name, $label) = split /\x1F/, $key, 2; | ||
| 122 | $histogram_by_name{$name}{$label} = $histogram_snapshot{$key} + 0; | ||
| 123 | } | ||
| 124 | |||
| 125 | my $config = $self->{configuration}; | ||
| 126 | my @samples = map { | ||
| 127 | { | ||
| 128 | transaction_name => $_, | ||
| 129 | environment => $config->{environment}, | ||
| 130 | release => $config->{release}, | ||
| 131 | period_started_at => _format_time($period_started_at), | ||
| 132 | period_ended_at => _format_time($period_ended_at), | ||
| 133 | request_count => $counts_snapshot{$_} + 0, | ||
| 134 | duration_sum_ms => $sums_snapshot{$_} + 0, | ||
| 135 | max_duration_ms => $max_snapshot{$_} + 0, | ||
| 136 | histogram => $histogram_by_name{$_} || {}, | ||
| 137 | } | ||
| 138 | } @names; | ||
| 139 | |||
| 140 | my $delivered = $self->{client}->deliver_performance_samples(\@samples); | ||
| 141 | my $status = ForgeOps::Tracker::DeliveryStatus::of_client($self->{client}, $delivered); | ||
| 142 | |||
| 143 | lock(${ $self->{lock} }); | ||
| 144 | my ($release, $why) = ForgeOps::Tracker::DeliveryStatus::settle($self->{failed_flushes}, $status); | ||
| 145 | return unless $release; | ||
| 146 | if ($why) { | ||
| 147 | eval { $config->log('[forge-ops-tracker] dropping ' . scalar(@names) . " buffered performance samples: $why") }; | ||
| 148 | } | ||
| 149 | |||
| 150 | for my $key (keys %histogram_snapshot) { | ||
| 151 | next unless exists $self->{histogram_counts}{$key}; | ||
| 152 | my $remaining = $self->{histogram_counts}{$key} - $histogram_snapshot{$key}; | ||
| 153 | if ($remaining > 0) { | ||
| 154 | $self->{histogram_counts}{$key} = $remaining; | ||
| 155 | } else { | ||
| 156 | delete $self->{histogram_counts}{$key}; | ||
| 157 | } | ||
| 158 | } | ||
| 159 | for my $name (@names) { | ||
| 160 | next unless exists $self->{counts}{$name}; | ||
| 161 | $self->{counts}{$name} -= $counts_snapshot{$name}; | ||
| 162 | my $remaining_sum = $self->{duration_sums}{$name} - $sums_snapshot{$name}; | ||
| 163 | $self->{duration_sums}{$name} = $remaining_sum > 0 ? $remaining_sum : 0; | ||
| 164 | if ($self->{counts}{$name} <= 0) { | ||
| 165 | delete $self->{counts}{$name}; | ||
| 166 | delete $self->{duration_sums}{$name}; | ||
| 167 | delete $self->{max_durations}{$name}; | ||
| 168 | } | ||
| 169 | } | ||
| 170 | ${ $self->{period_started_at} } = $period_ended_at; | ||
| 171 | } | ||
| 172 | |||
| 173 | sub _ensure_worker { | ||
| 174 | my ($self) = @_; | ||
| 175 | return if $self->{worker}; | ||
| 176 | |||
| 177 | my $flusher = $self; | ||
| 178 | $self->{worker} = threads->create(sub { | ||
| 179 | while (1) { | ||
| 180 | my $interval = $flusher->{configuration}{performance_flush_interval}; | ||
| 181 | $interval = 60 unless $interval && $interval > 0; | ||
| 182 | sleep($interval); | ||
| 183 | |||
| 184 | # Per-tick, not left to kill the loop: one bad flush must not stop every flush after | ||
| 185 | # it. Also guards against a logger callback that didn't clone cleanly into this thread | ||
| 186 | # (the same known ithreads sharp edge DeliveryQueue's own worker already documents). | ||
| 187 | eval { $flusher->flush }; | ||
| 188 | if ($@) { | ||
| 189 | eval { $flusher->{configuration}->log("[forge-ops-tracker] performance flush error: $@") }; | ||
| 190 | } | ||
| 191 | } | ||
| 192 | }); | ||
| 193 | $self->{worker}->detach; | ||
| 194 | } | ||
| 195 | |||
| 196 | # ISO 8601 in UTC, matching every other SDK's own period_started_at/period_ended_at format. | ||
| 197 | sub _format_time { | ||
| 198 | my ($epoch_seconds) = @_; | ||
| 199 | my $whole = int($epoch_seconds); | ||
| 200 | my $fraction = $epoch_seconds - $whole; | ||
| 201 | return strftime('%Y-%m-%dT%H:%M:%S', gmtime($whole)) . sprintf('.%03dZ', int($fraction * 1000)); | ||
| 202 | } | ||
| 203 | |||
| 204 | 1; |