Kubernetes/Watcher.pm

filter: Statementstmt 99.0% 217 / 219 Branchbran 90.7% 127 / 140 Conditioncond 88.7% 71 / 80 MC/DCmcdc 80.0% 36 / 45 Subroutinesub 100% 41 / 41 Podpod 100% 21 / 21 totaltotal 93.9% 513 / 546 CC 104 SCAR 24.5
CC
104
Cov
95%
_dispatch_event
28.0
configure
20.0
_watch_failed
10.0
CRAP 11.6
↑ Summary Kubernetes.pm »
1 package Net::Async::Kubernetes::Watcher;
2 # ABSTRACT: Auto-reconnecting Kubernetes watch as IO::Async::Notifier
3 48 our $VERSION = '0.009';
4 48 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 48 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 48 ▶use parent 'IO::Async::Notifier';
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 48 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 48 ▶use Scalar::Util qw(blessed looks_like_number weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 48 ▶use Kubernetes::REST::HTTPResponse;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 113 ▶sub configure {
Subroutine configure: called CC=20 SCAR=30.0
Pod documented
13 113 my ($self, %params) = @_;
14  
15 113 ▶ if (exists $params{kube}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"kube"}) 95 18 113
16 95 $self->{kube} = delete $params{kube};
17 95 weaken($self->{kube});
18 }
19 # Checked here: anything else (a Controller-style arrayref of delays, a
20 # word) numifies to a delay nobody asked for and the retries go quiet.
21 113 for my $key (qw(reconnect_delay max_reconnect_delay min_watch_duration)) {
22 334 ▶ next unless exists $params{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $params{$key} 321 13 334
23 13 my $value = delete $params{$key};
24 13 ▶ croak "$key must be a non-negative number of seconds"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and not ref $value and &looks_like_number($value) and $value >= 0 7 6 13
Condition100%9/9
defined $value and not ref $value and &looks_like_number($value) and $value >= 0
!ll&&!rl&&r
526
defined $value and not ref $value and &looks_like_number($value)
!ll&&!rl&&r
328
defined $value and not ref $value
!ll&&!rl&&r
1210
MC/DC100%4/4
defined $value and not ref $value and &looks_like_number($value) and $value >= 0
defined $value not ref $value &looks_like_number($value) $value >= 0
Truth table100%5/5
A and not(B) and C and D
A= defined $valueB= not ref $valueC= &looks_like_number($value)D= $value >= 0
ABCDresult
0XXX0
10XX0
110X0
11100
11111
25 unless defined $value && !ref $value && looks_like_number($value) && $value >= 0;
26 6 $self->{$key} = $value;
27 }
28 106 ▶ if (exists $params{reconnect_jitter}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"reconnect_jitter"}) 31 75 106
29 31 my $value = delete $params{reconnect_jitter};
30 31 ▶ croak "reconnect_jitter must be a number from 0 to 1"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and not ref $value and &looks_like_number($value) and $value >= 0 and $value <= 1 5 26 31
Condition100%12/12
defined $value and not ref $value and &looks_like_number($value) and $value >= 0 and $value <= 1
!ll&&!rl&&r
4126
defined $value and not ref $value and &looks_like_number($value) and $value >= 0
!ll&&!rl&&r
3127
defined $value and not ref $value and &looks_like_number($value)
!ll&&!rl&&r
2128
defined $value and not ref $value
!ll&&!rl&&r
1129
MC/DC100%5/5
defined $value and not ref $value and &looks_like_number($value) and $value >= 0 and $value <= 1
defined $value not ref $value &looks_like_number($value) $value >= 0 $value <= 1
Truth table100%6/6
A and not(B) and C and D and E
A= defined $valueB= not ref $valueC= &looks_like_number($value)D= $value >= 0E= $value <= 1
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
31 unless defined $value && !ref $value && looks_like_number($value)
32 && $value >= 0 && $value <= 1;
33 26 $self->{reconnect_jitter} = $value;
34 }
35 101 ▶ if (exists $params{max_retries}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"max_retries"}) 6 95 101
36 6 my $value = delete $params{max_retries};
37 6 ▶ croak "max_retries must be a non-negative integer, or undef for no limit"
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and ref $value || !($value =~ /\A[0-9]+\z/) 2 4 6
Condition66%4/6
defined $value and ref $value || !($value =~ /\A[0-9]+\z/)
!ll&&!rl&&r
042
ref $value or not $value =~ /\A[0-9]+\z/
l!l&&r!l&&!r
024
MC/DC33%1/3
defined $value and ref $value || !($value =~ /\A[0-9]+\z/)
defined $value ref $value not $value =~ /\A[0-9]+\z/
Truth table50%2/4
A and B or not(C)
A= defined $valueB= ref $valueC= not $value =~ /\A[0-9]+\z/
ABCresult
0XX0
1000
11X1
1011
38 if defined $value && (ref $value || $value !~ /\A[0-9]+\z/);
39 4 $self->{max_retries} = $value;
40 }
41 99 for my $key (qw(resource namespace timeout label_selector field_selector
42 names event_types
43 on_added on_modified on_deleted on_error on_event)) {
44 1188 ▶ if (exists $params{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{$key}) 375 813 1188
45 375 $self->{$key} = delete $params{$key};
46 }
47 }
48  
49 99 $self->SUPER::configure(%params);
50 }
51  
52  
53 # Accessors
54 868 ▶sub kube { $_[0]->{kube} }
Subroutine kube: called CC=1 SCAR=0.0
Pod documented
55  
56  
57 545 ▶sub resource { $_[0]->{resource} }
Subroutine resource: called CC=1 SCAR=0.0
Pod documented
58  
59  
60 333 ▶sub namespace { $_[0]->{namespace} }
Subroutine namespace: called CC=1 SCAR=0.0
Pod documented
61  
62  
63 170 ▶sub timeout { $_[0]->{timeout} // 300 }
Subroutine timeout: called CC=2 SCAR=6.9
Pod documented
Condition100%2/2
$_[0]{"timeout"} // 300
l!l
3167
MC/DC100%1/1
$_[0]{"timeout"} // 300
$_[0]{"timeout"}
Truth table100%2/2
A
A= $_[0]{"timeout"}
Aresult
11
00
64  
65  
66 91 ▶sub reconnect_delay { $_[0]->{reconnect_delay} // 1 }
Subroutine reconnect_delay: called CC=2 SCAR=6.9
Pod documented
Condition100%2/2
$_[0]{"reconnect_delay"} // 1
l!l
685
MC/DC100%1/1
$_[0]{"reconnect_delay"} // 1
$_[0]{"reconnect_delay"}
Truth table100%2/2
A
A= $_[0]{"reconnect_delay"}
Aresult
11
00
67  
68  
69 117 ▶sub max_reconnect_delay { $_[0]->{max_reconnect_delay} // 30 }
Subroutine max_reconnect_delay: called CC=2 SCAR=6.9
Pod documented
Condition100%2/2
$_[0]{"max_reconnect_delay"} // 30
l!l
7110
MC/DC100%1/1
$_[0]{"max_reconnect_delay"} // 30
$_[0]{"max_reconnect_delay"}
Truth table100%2/2
A
A= $_[0]{"max_reconnect_delay"}
Aresult
11
00
70  
71  
72 92 ▶sub reconnect_jitter { $_[0]->{reconnect_jitter} // 0.2 }
Subroutine reconnect_jitter: called CC=2 SCAR=6.9
Pod documented
Condition100%2/2
$_[0]{"reconnect_jitter"} // "0.2"
l!l
848
MC/DC100%1/1
$_[0]{"reconnect_jitter"} // "0.2"
$_[0]{"reconnect_jitter"}
Truth table100%2/2
A
A= $_[0]{"reconnect_jitter"}
Aresult
11
00
73  
74  
75 94 ▶sub max_retries { $_[0]->{max_retries} }
Subroutine max_retries: called CC=1 SCAR=0.0
Pod documented
76  
77  
78 17 ▶sub min_watch_duration { $_[0]->{min_watch_duration} // 1 }
Subroutine min_watch_duration: called CC=2 SCAR=6.9
Pod documented
Condition100%2/2
$_[0]{"min_watch_duration"} // 1
l!l
710
MC/DC100%1/1
$_[0]{"min_watch_duration"} // 1
$_[0]{"min_watch_duration"}
Truth table100%2/2
A
A= $_[0]{"min_watch_duration"}
Aresult
11
00
79  
80  
81 171 ▶sub label_selector { $_[0]->{label_selector} }
Subroutine label_selector: called CC=1 SCAR=0.0
Pod documented
82  
83  
84 171 ▶sub field_selector { $_[0]->{field_selector} }
Subroutine field_selector: called CC=1 SCAR=0.0
Pod documented
85  
86  
87 121 ▶sub names { $_[0]->{names} }
Subroutine names: called CC=1 SCAR=0.0
Pod documented
88  
89  
90 139 ▶sub event_types { $_[0]->{event_types} }
Subroutine event_types: called CC=1 SCAR=0.0
Pod documented
91  
92  
93 310 ▶sub on_added { $_[0]->{on_added} }
Subroutine on_added: called CC=1 SCAR=0.0
Pod documented
94  
95  
96 113 ▶sub on_modified { $_[0]->{on_modified} }
Subroutine on_modified: called CC=1 SCAR=0.0
Pod documented
97  
98  
99 113 ▶sub on_deleted { $_[0]->{on_deleted} }
Subroutine on_deleted: called CC=1 SCAR=0.0
Pod documented
100  
101  
102 217 ▶sub on_error { $_[0]->{on_error} }
Subroutine on_error: called CC=1 SCAR=0.0
Pod documented
103  
104  
105 258 ▶sub on_event { $_[0]->{on_event} }
Subroutine on_event: called CC=1 SCAR=0.0
Pod documented
106  
107  
108 95 ▶sub _add_to_loop {
Subroutine _add_to_loop: called CC=3 SCAR=11.0
109 95 my ($self, $loop) = @_;
110 95 ▶ croak "kube is required" unless $self->{kube};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"kube"} 1 94 95
111 94 ▶ croak "resource is required" unless $self->{resource};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"resource"} 1 93 94
112 93 $self->start;
113 }
114  
115 20 ▶sub _remove_from_loop {
Subroutine _remove_from_loop: called CC=1 SCAR=0.0
116 20 my ($self, $loop) = @_;
117 20 $self->stop;
118 }
119  
120 95 ▶sub start {
Subroutine start: called CC=3 SCAR=11.0
Pod documented
121 95 my ($self) = @_;
122 # Waiting out a reconnect delay is running too: starting now as well
123 # would leave two watches once the pending reconnect fires.
124 95 ▶ return if $self->{_watching} || $self->{_retry_future};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_watching"} or $self->{"_retry_future"} 1 94 95
Condition66%2/3
$self->{"_watching"} or $self->{"_retry_future"}
l!l&&r!l&&!r
0194
MC/DC50%1/2
$self->{"_watching"} or $self->{"_retry_future"}
$self->{"_watching"} $self->{"_retry_future"}
Truth table66%2/3
A or B
A= $self->{"_watching"}B= $self->{"_retry_future"}
ABresult
1X1
011
000
125 94 $self->{_stopped} = 0;
126 94 $self->{_failures} = 0;
127 94 $self->_start_watch;
128 }
129  
130  
131 114 ▶sub stop {
Subroutine stop: called CC=5 SCAR=16.1
Pod documented
132 114 my ($self) = @_;
133 114 $self->{_stopped} = 1;
134 114 $self->{_watching} = 0;
135 114 ▶ if (my $retry = delete $self->{_retry_future}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $retry = delete $self->{"_retry_future"}) 24 90 114
136 24 $retry->cancel;
137 }
138 114 ▶ if (my $f = delete $self->{_watch_future}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $f = delete $self->{"_watch_future"}) 79 35 114
139 79 ▶ return if $f->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $f->is_ready 27 52 79
140 # Defer cancel to next loop iteration to avoid closing the HTTP
141 # connection from within its own on_read handler, which triggers
142 # Net::Async::HTTP's "Spurious on_read of connection while idle".
143 52 ▶ if (my $loop = $self->loop) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $loop = $self->loop) { } 52 0 52
144 39 ▶ $loop->later(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
145 39 ▶ $f->cancel if !$f->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if not $f->is_ready 31 8 39
146 52 });
147 } else {
148 0 $f->cancel;
149 }
150 }
151 }
152  
153  
154 181 ▶sub _start_watch {
Subroutine _start_watch: called CC=9 SCAR=22.0
155 181 my ($self) = @_;
156 181 ▶ return if $self->{_stopped};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_stopped"} 0 181 181
157 181 ▶ return unless $self->{kube};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"kube"} 0 181 181
158  
159 181 $self->{_watching} = 1;
160 181 $self->{_buffer} = '';
161  
162 181 my $rest = $self->kube->_rest;
163 181 my ($class, $error) = $self->kube->_resolve_class($self->resource);
164 181 ▶ croak $error unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 11 170 181
165 170 ▶ (my $path, $error) = $self->kube->_request_path($class, $self->resource,
Branch: 1 branch
BranchTrueFalseTotal
$self->namespace ? : 161 9 170
166 ($self->namespace ? (namespace => $self->namespace) : ()),
167 );
168 170 ▶ croak $error unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 2 168 170
169  
170 168 my %params = (
171 watch => 'true',
172 timeoutSeconds => $self->timeout,
173 );
174 $params{resourceVersion} = $self->{_resource_version}
175 168 ▶ if defined $self->{_resource_version};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"_resource_version"} 15 153 168
176 168 ▶ $params{labelSelector} = $self->label_selector
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->label_selector 2 166 168
177 if defined $self->label_selector;
178 168 ▶ $params{fieldSelector} = $self->field_selector
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->field_selector 2 166 168
179 if defined $self->field_selector;
180  
181 168 my $req = $rest->prepare_request('GET', $path, parameters => \%params);
182 # The resolved class, handed over exactly (see the client's _exact_class).
183 168 my $exact_class = $self->kube->_exact_class($class);
184  
185 # What tells a watch cycle that ran its course from a failed attempt
186 # when this stream ends: when it started, whether any event came, and
187 # the ERROR event it would end on.
188 168 $self->{_stream_started} = $self->_now;
189 168 $self->{_stream_events} = 0;
190 168 $self->{_stream_error} = undef;
191  
192 168 weaken(my $weak_self = $self);
193  
194 146 ▶ my $f = $self->kube->_do_streaming_request($req, sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
195 146 my ($chunk) = @_;
196 146 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 4 142 146
197  
198 142 my $buffer = $weak_self->{_buffer};
199 142 for my $result ($rest->process_watch_chunk($exact_class, \$buffer, $chunk)) {
200 142 $weak_self->{_buffer} = $buffer;
201  
202 142 ▶ if ($result->{resourceVersion}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result->{"resourceVersion"}) 126 16 142
203 126 $weak_self->{_resource_version} = $result->{resourceVersion};
204 }
205  
206 142 my $event = $result->{event};
207 142 $weak_self->{_stream_events}++;
208  
209 142 ▶ if ($result->{is_error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result->{'is_error'}) { } 14 128 142
210 14 ▶ if ($result->{error_code} == 410) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result->{"error_code"} == 410) 3 11 14
211 3 $weak_self->{_resource_version} = undef;
212 3 $weak_self->{_stream_error} = undef;
213 3 return;
214 }
215 # Not reset by an ERROR event: a server that sends one and
216 # closes, again and again, must meet a growing backoff.
217 11 $weak_self->{_stream_error} = $event->object;
218 } else {
219 # An event: this attempt got through, so a failure after it
220 # starts the backoff over.
221 128 $weak_self->{_failures} = 0;
222 128 $weak_self->{_stream_error} = undef;
223 }
224  
225 139 $weak_self->_dispatch_event($event);
226 }
227 139 $weak_self->{_buffer} = $buffer;
228 168 });
229  
230 45 ▶ $f->on_done(sub {
Subroutine __ANON__: called CC=9 SCAR=22.0
231 45 my ($response) = @_;
232 45 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 3 42 45
233 42 ▶ return if $weak_self->{_stopped};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"_stopped"} 3 39 42
234 39 $weak_self->{_watching} = 0;
235 # A rejected request (401, 403, 5xx) resolves like any response. It
236 # is a failed attempt, not a watch cycle that ran its course.
237 39 ▶ if ($response->status >= 400) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->status >= 400) 6 33 39
238 6 ▶ my $cause = eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $rest->check_response($response, 'watch ' . $weak_self->resource); 1 } } ? : 0 6 6
239 6 $rest->check_response($response, 'watch ' . $weak_self->resource);
240 0 1;
241 } ? 'HTTP ' . $response->status : $@;
242 6 return $weak_self->_watch_failed($cause, $response->status);
243 }
244 # So is a stream that ends on an ERROR event (other than 410 Gone,
245 # which lets the reconnect start over), or at once without any.
246 # Reconnecting at once would be a tight loop against the API server.
247 33 ▶ if (my $error = $weak_self->{_stream_error}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $weak_self->{"_stream_error"}) 3 30 33
248 return $weak_self->_watch_failed($weak_self->_error_event_cause($error),
249 3 ▶ ref $error eq 'HASH' ? $error->{code} : undef);
Branch: 1 branch
BranchTrueFalseTotal
ref $error eq 'HASH' ? : 3 0 3
250 }
251 30 my $elapsed = $weak_self->_now - $weak_self->{_stream_started};
252 30 ▶ if (!$weak_self->{_stream_events} && $elapsed < $weak_self->min_watch_duration) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $weak_self->{"_stream_events"} and $elapsed < $weak_self->min_watch_duration) 9 21 30
Condition100%3/3
not $weak_self->{"_stream_events"} and $elapsed < $weak_self->min_watch_duration
!ll&&!rl&&r
1569
MC/DC100%2/2
not $weak_self->{"_stream_events"} and $elapsed < $weak_self->min_watch_duration
not $weak_self->{"_stream_events"} $elapsed < $weak_self->min_watch_duration
Truth table100%3/3
not(A) and B
A= not $weak_self->{"_stream_events"}B= $elapsed < $weak_self->min_watch_duration
ABresult
0X0
100
111
253 9 return $weak_self->_watch_failed(
254 sprintf('stream closed after %.1fs without an event', $elapsed));
255 }
256 21 $weak_self->{_failures} = 0;
257 21 $weak_self->_start_watch;
258 168 });
259  
260 77 ▶ $f->on_fail(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
261 77 my ($error) = @_;
262 77 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 77 77
263 77 ▶ return if $weak_self->{_stopped};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"_stopped"} 2 75 77
264 75 $weak_self->{_watching} = 0;
265 75 $weak_self->_watch_failed($error);
266 168 });
267  
268 168 $self->{_watch_future} = $f;
269 }
270  
271 # The clock min_watch_duration is measured with: the loop's, which its
272 # timers use too. Tests replace it.
273 147 ▶sub _now { $_[0]->loop->time }
Subroutine _now: called CC=1 SCAR=0.0
274  
275 # The random share of reconnect_jitter a delay is shortened by, from 0 up to
276 # (not including) 1. Tests replace it.
277 27 ▶sub _random_fraction { rand() }
Subroutine _random_fraction: called CC=1 SCAR=0.0
278  
279 # The cause of a failure for a stream that ended on the ERROR event $error,
280 # the raw Status hashref: its code, reason and message.
281 3 ▶sub _error_event_cause {
Subroutine _error_event_cause: called CC=5 SCAR=17.8
282 3 my ($self, $error) = @_;
283 3 ▶ return 'stream closed after an ERROR event' unless ref $error eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $error eq "HASH" 0 3 3
284 3 ▶ my $what = join ' ', grep { defined && length } @{$error}{qw(code reason)};
Condition33%1/3
defined $_ && length $_
!ll&&!rl&&r
006
MC/DC0%0/2
defined $_ && length $_
defined $_ length $_
Truth table33%1/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
285 return 'stream closed after an ERROR event'
286 . (length $what ? " ($what)" : '')
287 3 ▶ . (defined $error->{message} ? ': ' . $error->{message} : '');
Branch: 2 branches
BranchTrueFalseTotal
length $what ? : 3 0 3
defined $error->{'message'} ? : 3 0 3
288 }
289  
290 # The cause of a failed watch attempt as its report words it, for humans: a
291 # Kubernetes::REST::APIError as "HTTP <code> <reason>: <message>" from its
292 # accessors (the body when it holds no Status), anything else as its text
293 # without the Perl location a croak or die ends in.
294 93 ▶sub _cause_text {
Subroutine _cause_text: called CC=7 SCAR=19.6
295 93 my ($self, $cause) = @_;
296 93 ▶ return 'unknown error' unless defined $cause;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cause 0 93 93
297 93 ▶ if (blessed $cause && $cause->isa('Kubernetes::REST::APIError')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($cause) and $cause->isa("Kubernetes::REST::APIError")) 6 87 93
Condition66%2/3
builtin::blessed($cause) and $cause->isa("Kubernetes::REST::APIError")
!ll&&!rl&&r
8706
MC/DC50%1/2
builtin::blessed($cause) and $cause->isa("Kubernetes::REST::APIError")
builtin::blessed($cause) $cause->isa("Kubernetes::REST::APIError")
Truth table66%2/3
A and B
A= builtin::blessed($cause)B= $cause->isa("Kubernetes::REST::APIError")
ABresult
0X0
100
111
298 6 ▶ my $text = join ' ', 'HTTP', $cause->code, grep { defined && length } $cause->reason;
Condition66%2/3
defined $_ && length $_
!ll&&!rl&&r
402
MC/DC50%1/2
defined $_ && length $_
defined $_ length $_
Truth table66%2/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
299 6 ▶ my $detail = $cause->message // $cause->body;
Condition100%3/3
$cause->message // $cause->body
l!l&&r!l&&!r
411
MC/DC100%2/2
$cause->message // $cause->body
$cause->message $cause->body
Truth table100%3/3
A // B
A= $cause->messageB= $cause->body
ABresult
1X1
011
000
300 6 $detail =~ s/\s+\z//;
301 6 ▶ return length $detail ? $text . ': ' . $detail : $text;
Branch: 1 branch
BranchTrueFalseTotal
length $detail ? : 5 1 6
302 }
303 87 my $text = "$cause";
304 87 $text =~ s/\s+\z//;
305 87 $text =~ s/ at \S+ line \d+\.\z//;
306 87 return $text;
307 }
308  
309 # A failed watch attempt: a request that failed outright, was rejected with
310 # HTTP status $code, or opened a stream that ended badly ($code then the
311 # ERROR event's, if any). Schedules the next attempt with exponential
312 # backoff - or, once max_retries consecutive failures have been retried,
313 # stops the watcher - and reports the failure either way: to on_error, else
314 # as a warning.
315 93 ▶sub _watch_failed {
Subroutine _watch_failed: called CC=10 SCAR=23.0
316 93 my ($self, $cause, $code) = @_;
317 93 my $failures = ++$self->{_failures};
318 93 my $max_retries = $self->max_retries;
319 93 $cause = $self->_cause_text($cause);
320  
321 93 my ($delay, $next);
322 93 ▶ if (defined $max_retries && $failures > $max_retries) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $max_retries and $failures > $max_retries) { } 3 90 93
Condition100%3/3
defined $max_retries and $failures > $max_retries
!ll&&!rl&&r
8553
MC/DC100%2/2
defined $max_retries and $failures > $max_retries
defined $max_retries $failures > $max_retries
Truth table100%3/3
A and B
A= defined $max_retriesB= $failures > $max_retries
ABresult
0X0
100
111
323 # Stopped before the report, so an on_error that restarts the watcher
324 # is not undone right after.
325 3 $self->stop;
326 3 ▶ $next = sprintf('giving up after %d %s',
Branch: 1 branch
BranchTrueFalseTotal
$max_retries == 1 ? : 1 2 3
327 $max_retries, $max_retries == 1 ? 'retry' : 'retries');
328 } else {
329 # The exponent is bounded so a long outage cannot overflow it to inf,
330 # which reconnect_delay => 0 would turn into a NaN delay.
331 90 my $exponent = $failures - 1;
332 90 ▶ $exponent = 64 if $exponent > 64;
Branch: 1 branch
BranchTrueFalseTotal
if $exponent > 64 0 90 90
333 90 $delay = $self->reconnect_delay * 2 ** $exponent;
334 90 ▶ $delay = $self->max_reconnect_delay if $delay > $self->max_reconnect_delay;
Branch: 1 branch
BranchTrueFalseTotal
if $delay > $self->max_reconnect_delay 26 64 90
335 # Shortened, never lengthened, so both delays stay upper bounds.
336 90 ▶ if (my $jitter = $self->reconnect_jitter) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $jitter = $self->reconnect_jitter) 48 42 90
337 48 $delay -= $delay * $jitter * $self->_random_fraction;
338 48 $delay = int($delay * 1000 + 0.5) / 1000;
339 }
340  
341 # Scheduled before the report, so an on_error that stops the watcher
342 # cancels it.
343 90 weaken(my $weak_self = $self);
344 66 ▶ $self->{_retry_future} = $self->loop->delay_future(after => $delay)->on_done(sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
345 66 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 66 66
346 66 delete $weak_self->{_retry_future};
347 66 $weak_self->_start_watch;
348 90 });
349 90 $next = 'retrying in ' . $delay . 's';
350 }
351  
352 93 ▶ my $status = {
Branch: 1 branch
BranchTrueFalseTotal
defined $delay ? : 90 3 93
Condition100%2/2
$code // 0
l!l
984
MC/DC100%1/1
$code // 0
$code
Truth table100%2/2
A
A= $code
Aresult
11
00
353 kind => 'Status',
354 apiVersion => 'v1',
355 status => 'Failure',
356 reason => 'WatchFailed',
357 code => $code // 0,
358 message => 'watch ' . $self->resource . ' failed, ' . $next . ': ' . $cause,
359 details => {
360 kind => $self->resource,
361 (defined $delay ? (retryAfterSeconds => $delay) : ()),
362 },
363 };
364  
365 93 ▶ if (my $cb = $self->on_error) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cb = $self->on_error) { } 87 6 93
366 87 $cb->($status);
367 } else {
368 6 warn $status->{message} . "\n";
369 }
370 }
371  
372 139 ▶sub _dispatch_event {
Subroutine _dispatch_event: called CC=28 SCAR=33.3
373 139 my ($self, $event) = @_;
374 139 my $type = $event->type;
375  
376 # Client-side event type filter
377 # Explicit event_types wins; otherwise auto-derive from callbacks
378 # (on_event is catch-all, so if set, all types pass)
379 139 ▶ if (my $types = $self->event_types) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $types = $self->event_types) { } 10 129 139
elsif (not $self->on_event) { } 102 27 129
380 10 my %allowed = map { uc($_) => 1 } @$types;
381 10 ▶ return unless $allowed{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless $allowed{$type} 4 6 10
382 } elsif (!$self->on_event) {
383 102 my %has;
384 102 ▶ $has{ADDED} = 1 if $self->on_added;
Branch: 1 branch
BranchTrueFalseTotal
if $self->on_added 102 0 102
385 102 ▶ $has{MODIFIED} = 1 if $self->on_modified;
Branch: 1 branch
BranchTrueFalseTotal
if $self->on_modified 66 36 102
386 102 ▶ $has{DELETED} = 1 if $self->on_deleted;
Branch: 1 branch
BranchTrueFalseTotal
if $self->on_deleted 69 33 102
387 102 ▶ $has{ERROR} = 1 if $self->on_error;
Branch: 1 branch
BranchTrueFalseTotal
if $self->on_error 23 79 102
388 102 ▶ return unless !%has || $has{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless not %has or $has{$type} 3 99 102
Condition66%2/3
not %has or $has{$type}
l!l&&r!l&&!r
0993
MC/DC50%1/2
not %has or $has{$type}
not %has $has{$type}
Truth table66%2/3
not(A) or B
A= not %hasB= $has{$type}
ABresult
1X1
011
000
389 }
390  
391 # Client-side name filter (skip for ERROR events which have no metadata)
392 132 ▶ if ($type ne 'ERROR' && (my $names = $self->names)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type ne "ERROR" and my $names = $self->names) 11 121 132
Condition100%3/3
$type ne "ERROR" and my $names = $self->names
!ll&&!rl&&r
1111011
MC/DC100%2/2
$type ne "ERROR" and my $names = $self->names
$type ne "ERROR" my $names = $self->names
Truth table100%3/3
A and B
A= $type ne "ERROR"B= my $names = $self->names
ABresult
0X0
100
111
393 11 ▶ my $obj_name = eval { $event->object->metadata->name } // '';
Condition50%1/2
eval { // ""
l!l
110
MC/DC0%0/1
eval { do { $event->object->metadata->name } } // ""
eval { do { $event->object->metadata->name } }
Truth table50%1/2
A
A= eval { do { $event->object->metadata->name } }
Aresult
11
00
394 11 ▶ my @patterns = ref $names eq 'ARRAY' ? @$names : ($names);
Branch: 1 branch
BranchTrueFalseTotal
ref $names eq 'ARRAY' ? : 3 8 11
395 11 my $matched = 0;
396 11 for my $pat (@patterns) {
397 13 ▶ if (ref $pat eq 'Regexp') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $pat eq 'Regexp') { } 11 2 13
398 11 ▶ $matched = 1, last if $obj_name =~ $pat;
Branch: 1 branch
BranchTrueFalseTotal
if $obj_name =~ /$pat/ 6 5 11
399 } else {
400 2 ▶ $matched = 1, last if $obj_name eq $pat;
Branch: 1 branch
BranchTrueFalseTotal
if $obj_name eq $pat 1 1 2
401 }
402 }
403 11 ▶ return unless $matched;
Branch: 1 branch
BranchTrueFalseTotal
unless $matched 4 7 11
404 }
405  
406 128 ▶ if (my $cb = $self->on_event) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cb = $self->on_event) 31 97 128
407 31 $cb->($event);
408 }
409  
410 128 ▶ if ($type eq 'ADDED' && $self->on_added) {
Branch: 4 branches
BranchTrueFalseTotal
if ($type eq 'ADDED' and $self->on_added) { } 101 27 128
elsif ($type eq 'MODIFIED' and $self->on_modified) { } 4 23 27
elsif ($type eq 'DELETED' and $self->on_deleted) { } 4 19 23
elsif ($type eq 'ERROR' and $self->on_error) { } 10 17 27
Condition100%3/3
$type eq "ADDED" and $self->on_added
!ll&&!rl&&r
225101
MC/DC100%2/2
$type eq "ADDED" and $self->on_added
$type eq "ADDED" $self->on_added
Truth table100%3/3
A and B
A= $type eq "ADDED"B= $self->on_added
ABresult
0X0
100
111
411 101 $self->on_added->($event->object);
412 ▶ } elsif ($type eq 'MODIFIED' && $self->on_modified) {
Condition100%3/3
$type eq "MODIFIED" and $self->on_modified
!ll&&!rl&&r
2214
MC/DC100%2/2
$type eq "MODIFIED" and $self->on_modified
$type eq "MODIFIED" $self->on_modified
Truth table100%3/3
A and B
A= $type eq "MODIFIED"B= $self->on_modified
ABresult
0X0
100
111
413 4 $self->on_modified->($event->object);
414 ▶ } elsif ($type eq 'DELETED' && $self->on_deleted) {
Condition100%3/3
$type eq "DELETED" and $self->on_deleted
!ll&&!rl&&r
1724
MC/DC100%2/2
$type eq "DELETED" and $self->on_deleted
$type eq "DELETED" $self->on_deleted
Truth table100%3/3
A and B
A= $type eq "DELETED"B= $self->on_deleted
ABresult
0X0
100
111
415 4 $self->on_deleted->($event->object);
416 ▶ } elsif ($type eq 'ERROR' && $self->on_error) {
Condition100%3/3
$type eq "ERROR" and $self->on_error
!ll&&!rl&&r
8110
MC/DC100%2/2
$type eq "ERROR" and $self->on_error
$type eq "ERROR" $self->on_error
Truth table100%3/3
A and B
A= $type eq "ERROR"B= $self->on_error
ABresult
0X0
100
111
417 10 $self->on_error->($event->object);
418 }
419 }
420  
421 48 1;
422  
423 __END__
424  
425 =pod
426  
427 =encoding UTF-8
428  
429 =head1 NAME
430  
431 Net::Async::Kubernetes::Watcher - Auto-reconnecting Kubernetes watch as IO::Async::Notifier
432  
433 =head1 VERSION
434  
435 version 0.009
436  
437 =head1 SYNOPSIS
438  
439 my $watcher = $kube->watcher('Pod',
440 namespace => 'default',
441 label_selector => 'app=web',
442 on_added => sub { my ($pod) = @_; say "Added: " . $pod->metadata->name },
443 on_modified => sub { my ($pod) = @_; say "Modified: " . $pod->metadata->name },
444 on_deleted => sub { my ($pod) = @_; say "Deleted: " . $pod->metadata->name },
445 on_error => sub { my ($status) = @_; warn "Error: $status->{message}" },
446 );
447  
448 # Client-side filtering by name and event type
449 $kube->watcher('Pod',
450 namespace => 'default',
451 names => [qr/^nginx/, qr/^redis/], # only matching names
452 event_types => ['ADDED', 'DELETED'], # skip MODIFIED
453 on_added => sub { ... },
454 on_deleted => sub { ... },
455 );
456  
457 # Watch multiple resources concurrently
458 $kube->watcher('Deployment', namespace => 'production', on_modified => sub { ... });
459 $kube->watcher('Service', namespace => 'production', on_added => sub { ... });
460  
461 # Stop watching
462 $watcher->stop;
463  
464 # Restart
465 $watcher->start;
466  
467 =head1 DESCRIPTION
468  
469 An L<IO::Async::Notifier> that watches a Kubernetes resource for changes.
470 Created via L<Net::Async::Kubernetes/watcher>.
471  
472 The watcher automatically:
473  
474 =over 4
475  
476 =item * Reconnects when the server-side timeout expires
477  
478 =item * Resumes from the last C<resourceVersion> to avoid missing events
479  
480 =item * Handles 410 Gone by clearing the C<resourceVersion> and restarting
481  
482 =item * Retries a failed watch attempt -- a transport error, a rejection
483 such as C<401> or C<403>, or a stream that closes at once without an event
484 or right after an C<ERROR> event -- with an exponential backoff (1s, 2s, 4s,
485 ... up to 30s by default, see L</reconnect_delay>, each shortened at random
486 by up to a fifth, see L</reconnect_jitter>), reports every such
487 failure to L</on_error> or as a warning, and gives up after L</max_retries>
488 consecutive failures when a limit is set
489  
490 =item * Filters events client-side by name patterns (C<names>) and event types (C<event_types>)
491  
492 =back
493  
494 =head2 configure
495  
496 Internal L<IO::Async::Notifier> configuration method. Handles initialization
497 of C<kube>, C<resource>, C<namespace>, C<timeout>, C<label_selector>,
498 C<field_selector>, C<names>, C<event_types>, C<reconnect_delay>,
499 C<max_reconnect_delay>, C<reconnect_jitter>, C<max_retries>,
500 C<min_watch_duration>, and all event callbacks (C<on_added>, C<on_modified>,
501 C<on_deleted>, C<on_error>, C<on_event>). Croaks on a C<reconnect_delay>,
502 C<max_reconnect_delay> or C<min_watch_duration> that is not a non-negative
503 number, on a C<reconnect_jitter> that is not a number from 0 to 1, and on a
504 C<max_retries> that is neither a non-negative integer nor C<undef>.
505  
506 =head2 kube
507  
508 Returns the parent L<Net::Async::Kubernetes> instance.
509  
510 =head2 resource
511  
512 Required. The Kubernetes resource kind to watch (e.g., C<'Pod'>,
513 C<'Deployment'>), or a qualified C<'group/version/Kind'> name to watch a
514 specific API version -- see L<Net::Async::Kubernetes/expand_class>.
515  
516 =head2 namespace
517  
518 Optional. Namespace to watch. Omit for cluster-scoped resources or to
519 watch all namespaces.
520  
521 =head2 timeout
522  
523 Server-side timeout per watch cycle in seconds. Default: 300.
524  
525 =head2 reconnect_delay
526  
527 Seconds to wait before reconnecting after a failed watch attempt (see
528 L</on_error> for what counts as one). Default: 1. Each further consecutive
529 failure doubles the delay, up to L</max_reconnect_delay>, and every delay is
530 shortened at random by up to L</reconnect_jitter>. A reconnect that
531 gets through -- an event arrives on the stream (an C<ERROR> event does not
532 count), or the watch cycle ends cleanly -- starts the next failure at
533 C<reconnect_delay> again. A watch cycle that ends cleanly (the server-side
534 L</timeout>) is not a failure and reconnects at once; one that closes within
535 L</min_watch_duration> without an event, or right after an C<ERROR> event,
536 did not end cleanly.
537  
538 =head2 max_reconnect_delay
539  
540 Upper bound in seconds for the reconnect delay. Default: 30, the same cap
541 client-go's reflector puts on its watch backoff: a cluster that comes back is
542 noticed within half a minute, and one that stays away costs one request and
543 one report per half minute.
544  
545 =head2 reconnect_jitter
546  
547 The share, from 0 to 1, by which each reconnect delay is shortened at random.
548 Default: 0.2 -- a delay of 4 seconds becomes one between 3.2 and 4 seconds,
549 rounded to the millisecond. Without it, watchers that fail together (every
550 watch of a process, or of a fleet, on an API server that restarts) would
551 send their reconnects together again on every step of the backoff.
552  
553 The delay is only ever shortened: L</reconnect_delay> and
554 L</max_reconnect_delay> stay upper bounds, and C<retryAfterSeconds> in the
555 report (see L</on_error>) is the delay the watcher actually waits. With the
556 default each step of the backoff still lies above the one before it
557 (0.8 times double the delay is more than the delay). C<0> turns jitter off,
558 for delays that are exactly the documented ones.
559  
560 =head2 max_retries
561  
562 How many consecutive failed watch requests are retried before the watcher
563 gives up. Default: C<undef>, retry for as long as the watcher runs. When the
564 limit is exceeded the watcher stops and reports that it gave up (see
565 L</on_error>); C<start()> begins again with the full count. C<0> gives up on
566 the first failure.
567  
568 =head2 min_watch_duration
569  
570 Seconds a watch stream has to stay open before it may end without an event.
571 Default: 1. A stream that closes sooner without delivering a single event is
572 no watch cycle that ran its course but a failed attempt (see L</on_error>):
573 reconnecting at once would send the API server one watch request after
574 another in a tight loop -- a proxy or API server that accepts the watch and
575 closes it straight away. The default is the threshold client-go's reflector
576 uses for the same case (a "very short watch"): a real watch cycle runs until
577 the server-side L</timeout>, minutes, so one second tells the two apart with
578 room for a slow connection. C<0> turns the check off.
579  
580 =head2 label_selector
581  
582 Optional label selector (e.g., C<'app=web,env=prod'>).
583  
584 =head2 field_selector
585  
586 Optional field selector (e.g., C<'status.phase=Running'>).
587  
588 =head2 names
589  
590 Optional client-side filter for resource names. Accepts a single regex,
591 a string (exact match), or an arrayref of regexes/strings. Events whose
592 resource name does not match any of the patterns are silently dropped
593 before callbacks fire.
594  
595 # Single regex
596 names => qr/^nginx/
597  
598 # Multiple patterns (any match passes)
599 names => [qr/^nginx/, qr/^redis/]
600  
601 # Exact string match
602 names => 'my-pod'
603  
604 =head2 event_types
605  
606 Optional client-side filter for event types. Accepts an arrayref of
607 type strings (C<ADDED>, C<MODIFIED>, C<DELETED>, C<ERROR>). Events
608 whose type is not in the list are silently dropped.
609  
610 # Only ADDED and DELETED events
611 event_types => ['ADDED', 'DELETED']
612  
613 When not set, event types are automatically derived from which callbacks
614 are registered. If only C<on_added> is set, only C<ADDED> events are
615 dispatched. If C<on_event> is set (catch-all), all types pass through.
616  
617 =head2 on_added
618  
619 Callback for ADDED events. Receives the inflated IO::K8s object.
620  
621 =head2 on_modified
622  
623 Callback for MODIFIED events. Receives the inflated IO::K8s object.
624  
625 =head2 on_deleted
626  
627 Callback for DELETED events. Receives the inflated IO::K8s object.
628  
629 =head2 on_error
630  
631 Callback for errors of the watch. Receives a hashref shaped like a Kubernetes
632 C<Status>, in two cases:
633  
634 =over 4
635  
636 =item * An C<ERROR> event on the stream, for example a C<403> arriving
637 mid-stream: the raw C<Status> hashref the API server sent. C<410 Gone> is
638 handled internally and never reaches it.
639  
640 =item * A failed watch attempt: the request fails outright (TLS support
641 missing, a TLS or connection error, an unreachable API server), the API
642 server rejects it with an HTTP error status (C<401>, C<403>, C<5xx>), or the
643 stream it opens ends badly -- within L</min_watch_duration> without a single
644 event, or right after an C<ERROR> event other than C<410 Gone> (that event
645 is reported first, as above). The watcher builds this C<Status> itself.
646 C<reason> is C<WatchFailed>, C<code> the HTTP status of a rejected request,
647 the C<code> of the C<ERROR> event the stream ended on, or C<0> when neither
648 is there (no response arrived, or the stream closed without an event),
649 C<message> names the resource, what the watcher does next and the cause (for
650 a rejected request its HTTP status, reason and message, as in C<HTTP 403
651 Forbidden: pods is forbidden: ...>), and C<details> carries C<kind> (the watched resource) and, while the watcher
652 retries, C<retryAfterSeconds>:
653  
654 {
655 kind => 'Status',
656 apiVersion => 'v1',
657 status => 'Failure',
658 reason => 'WatchFailed',
659 code => 0,
660 message => 'watch Pod failed, retrying in 4s: Connection refused',
661 details => { kind => 'Pod', retryAfterSeconds => 4 },
662 }
663  
664 Once L</max_retries> is exceeded, the message says C<giving up after N
665 retries> instead and C<retryAfterSeconds> is absent; the watcher has
666 stopped by then.
667  
668 =back
669  
670 A failed watch attempt is reported whatever L</event_types> says. Without an
671 C<on_error> it is passed to C<warn> instead, so a watch that cannot reach its
672 cluster never fails silently. C<ERROR> events without an C<on_error> are
673 dropped, as before. The callback may call C<stop()>, which also cancels the
674 reconnect just announced.
675  
676 =head2 on_event
677  
678 Catch-all callback. Receives the L<Kubernetes::REST::WatchEvent> object.
679 Called in addition to the type-specific callbacks.
680  
681 =head2 start
682  
683 Start (or restart) the watch stream. Called automatically when the watcher
684 is added to the event loop. Safe to call multiple times (idempotent): a
685 watcher waiting to reconnect after a failed request is already running. After
686 C<stop()>, or after giving up on L</max_retries>, it starts over with the full
687 retry count.
688  
689 =head2 stop
690  
691 Stop the watch stream and cancel the current HTTP request, or a reconnect
692 that is waiting out its delay. The watcher will not automatically reconnect
693 until C<start()> is called again.
694  
695 =head1 SEE ALSO
696  
697 L<Net::Async::Kubernetes>, L<Kubernetes::REST::WatchEvent>,
698 L<IO::Async::Notifier>
699  
700 =head1 SUPPORT
701  
702 =head2 Issues
703  
704 Please report bugs and feature requests on GitHub at
705 L<https://github.com/Getty/p5-net-async-kubernetes/issues>.
706  
707 =head2 IRC
708  
709 Join C<#kubernetes> on C<irc.perl.org> or message Getty directly.
710  
711 =head1 CONTRIBUTING
712  
713 Contributions are welcome! Please fork the repository and submit a pull request.
714  
715 =head1 AUTHOR
716  
717 Torsten Raudssus <torsten@raudssus.de>
718  
719 =head1 COPYRIGHT AND LICENSE
720  
721 This software is copyright (c) 2026 by Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>.
722  
723 This is free software; you can redistribute it and/or modify it under
724 the same terms as the Perl 5 programming language system itself.
725  
726 =cut
↑ Summary Kubernetes.pm »