lib/ForgeOps/Tracker/DeliveryQueue.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« lib/ForgeOps/Tracker/HistogramBucketer.pm ↑ Summary lib/ForgeOps/Tracker.pm »
1 package ForgeOps::Tracker::DeliveryQueue;
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 0 ▶use threads;
Subroutine BEGIN: called CC=1 SCAR=2.6
6 use threads::shared;
7 use Thread::Queue;
8 use Time::HiRes ();
9  
10 # A small bounded queue drained by a background thread, so delivery never blocks the caller that
11 # raised the error. Uses Perl's own ithreads + Thread::Queue: the closest real equivalent to the
12 # Ruby/Java clients' own background-thread DeliveryQueue (see
13 # gems/forge_ops_tracker/lib/forge_ops_tracker/delivery_queue.rb), and, unlike a manual
14 # fork()-per-event approach, Thread::Queue is purpose-built by the Perl core itself as a
15 # thread-safe hand-off between a producer and a consumer thread, so no separate locking is needed
16 # here.
17 #
18 # The worker thread is started lazily, on first push, not at construction time: the same
19 # fork-safety reasoning the Ruby/Python clients' own DeliveryQueue documents for themselves: a
20 # prefork Perl app server (Starman running in prefork mode, or mod_perl2's own prefork MPM) forks
21 # worker processes *after* the application (and this module) has already loaded, so a thread
22 # started eagerly at load time would simply not exist in a forked child; starting fresh on first
23 # push means each forked worker gets its own live thread regardless of when it was forked relative
24 # to when the module loaded.
25 #
26 # `queue_size` bounds pending items via Thread::Queue's own `pending` count, checked before every
27 # enqueue: Thread::Queue has no native "drop instead of block when full" mode, so that behavior
28 # is implemented explicitly here to match every other SDK's own bounded-queue contract.
29 #
30 # The worker is detached, and Perl kills detached threads when the program ends, so a plain script
31 # that reports an error and falls off the end used to lose it. The END block below drains every
32 # queue that has ever had something pushed onto it: it delivers whatever is still queued on the
33 # main thread, then waits for a delivery the worker already has under way, within DRAIN_TIMEOUT
34 # seconds in total. A program that never reports anything never waits. Same contract as the Ruby
35 # gem's DeliveryQueue#drain.
36 use constant DRAIN_TIMEOUT => 5;
37  
38 my @live_queues;
39  
40 sub new {
41 my ($class, $configuration, $client) = @_;
42 my $in_flight = 0;
43 share($in_flight);
44 return bless {
45 configuration => $configuration,
46 client => $client,
47 queue => Thread::Queue->new,
48 worker => undef,
49 in_flight => \$in_flight,
50 registered => 0,
51 }, $class;
52 }
53  
54 sub push {
55 my ($self, $payload) = @_;
56 my $max_size = $self->{configuration}{queue_size} > 0 ? $self->{configuration}{queue_size} : 1;
57  
58 if ($self->{queue}->pending >= $max_size) {
59 $self->{configuration}->log('[forge-ops-tracker] delivery queue full, dropping event');
60 return 0;
61 }
62  
63 {
64 lock(${ $self->{in_flight} });
65 $self->{queue}->enqueue($payload);
66 cond_signal(${ $self->{in_flight} });
67 }
68 $self->_register_drain;
69 $self->_ensure_worker;
70 return 1;
71 }
72  
73 # drain($timeout): delivers whatever is still queued on the calling thread, then waits for a
74 # delivery the worker thread already has under way, giving up after $timeout seconds (DRAIN_TIMEOUT
75 # by default). Returns 1 if everything went out in time, 0 otherwise. Never dies.
76 sub drain {
77 my ($self, $timeout) = @_;
78 $timeout = DRAIN_TIMEOUT unless defined $timeout;
79 my $deadline = Time::HiRes::time() + $timeout;
80 my $in_flight = $self->{in_flight};
81  
82 while (Time::HiRes::time() < $deadline) {
83 my $payload = $self->{queue}->dequeue_nb;
84 if (defined $payload) {
85 eval { $self->{client}->deliver($payload) };
86 if ($@) {
87 eval { $self->{configuration}->log("[forge-ops-tracker] delivery error during drain: $@") };
88 }
89 next;
90 }
91 {
92 lock(${$in_flight});
93 return 1 if ${$in_flight} == 0 && !$self->{queue}->pending;
94 }
95 Time::HiRes::sleep(0.01);
96 }
97  
98 lock(${$in_flight});
99 return (${$in_flight} == 0 && !$self->{queue}->pending) ? 1 : 0;
100 }
101  
102 # drain_all($timeout, @queues): drains @queues (by default every queue that has had something
103 # pushed onto it), sharing one $timeout between them. Used by ForgeOps::Tracker::flush and the END
104 # block below.
105 sub drain_all {
106 my ($class, $timeout, @queues) = @_;
107 @queues = @live_queues unless @queues;
108 $timeout = DRAIN_TIMEOUT unless defined $timeout;
109 my $deadline = Time::HiRes::time() + $timeout;
110 my $all_sent = 1;
111  
112 for my $queue (grep { defined } @queues) {
113 my $remaining = $deadline - Time::HiRes::time();
114 $remaining = 0 if $remaining < 0;
115 $all_sent = 0 unless $queue->drain($remaining);
116 }
117 return $all_sent;
118 }
119  
120 # Registered on the first push, not at construction, so a program that never reports anything
121 # never waits at exit at all. A strong reference, not a weak one like MetricBuffer's: `exit` frees a
122 # script's own file-scoped lexicals before END blocks run, and a queue held only there would be gone
123 # by the time its items need sending.
124 sub _register_drain {
125 my ($self) = @_;
126 return if $self->{registered};
127 $self->{registered} = 1;
128 CORE::push(@live_queues, $self);
129 return;
130 }
131  
132 sub _ensure_worker {
133 my ($self) = @_;
134 return if $self->{worker};
135  
136 my $queue = $self->{queue};
137 my $client = $self->{client};
138 my $configuration = $self->{configuration};
139 my $in_flight = $self->{in_flight};
140  
141 $self->{worker} = threads->create(sub {
142 while (1) {
143 # Taking an item off the queue and counting it as in flight happen under one lock, so
144 # drain() never sees the queue empty and nothing in flight while this thread holds an
145 # item it hasn't delivered yet. push() signals the same lock when it enqueues.
146 my $payload;
147 {
148 lock(${$in_flight});
149 $payload = $queue->dequeue_nb;
150 if (defined $payload) {
151 ${$in_flight}++;
152 } else {
153 cond_timedwait(${$in_flight}, time + 1);
154 }
155 }
156 next unless defined $payload;
157  
158 # Per-item, not wrapping the whole loop: one bad delivery must not stop every event
159 # queued after it. Also guards against a logger callback that didn't clone cleanly
160 # into this thread (a known ithreads sharp edge for CODE ref-holding objects):
161 # dropping the log message in that unlikely case is still strictly better than this
162 # worker thread dying and silently stopping all future deliveries.
163 eval { $client->deliver($payload) };
164 if ($@) {
165 eval { $configuration->log("[forge-ops-tracker] delivery worker error: $@") };
166 }
167 { lock(${$in_flight}); ${$in_flight}--; }
168 }
169 });
170 $self->{worker}->detach;
171 }
172  
173 # A normal program end: drain every queue that was used (in the main thread only: a detached worker
174 # also runs END blocks in some Perl builds, and must not deliver twice). Keeps the program's own
175 # exit status, which a delivery's HTTP call must not change.
176 END {
177 if (threads->tid == 0 && @live_queues) {
178 local $?;
179 eval { __PACKAGE__->drain_all(DRAIN_TIMEOUT) };
180 }
181 }
182  
183 1;
« lib/ForgeOps/Tracker/HistogramBucketer.pm ↑ Summary lib/ForgeOps/Tracker.pm »