JSONUnix/Client.pm

filter: Statementstmt 82.8% 169 / 204 Branchbran 58.3% 42 / 72 Conditioncond 31.4% 17 / 54 MC/DCmcdc 9.3% 3 / 32 Subroutinesub 87.1% 34 / 39 Podpod 100% 11 / 11 totaltotal 66.9% 276 / 412 CC 60 SCAR 27.8
CC
60
Cov
69%
__ANON__
98.3
_poe_disconnect
12.0
_poe_server_input
12.0
CRAP 16.2
« JSONUnix/BlockingClient.pm ↑ Summary
1 package POE::Component::Server::JSONUnix::Client;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use v5.10;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 2 ▶use Carp qw(carp croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use Socket qw(PF_UNIX SOCK_STREAM);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use File::Temp 0.2310 (); # 0.2310 for tempfile's PERMS option
Subroutine BEGIN: called CC=1 SCAR=0.0
10 2 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 2 ▶use POE qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
13 Wheel::SocketFactory
14 Wheel::ReadWrite
15 Filter::Line
16 Driver::SysRW
17 2 );
18  
19 2 our $VERSION = '0.2.0';
20  
21 # Refcount tag used to keep event-style requesters alive while a reply is
22 # outstanding.
23 2 ▶use constant REFCOUNT_TAG => 'jsonunix_client_pending';
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25 =head1 NAME
26  
27 POE::Component::Server::JSONUnix::Client - POE client for POE::Component::Server::JSONUnix
28  
29 =head1 SYNOPSIS
30  
31 use POE;
32 use POE::Component::Server::JSONUnix::Client;
33  
34 my $client = POE::Component::Server::JSONUnix::Client->spawn(
35 socket_path => '/tmp/app.sock',
36 auto_auth => 1,
37 on_auth => sub {
38 my ($client, $response) = @_;
39 die $response->{error} if $response->{status} ne 'ok';
40  
41 $client->call(
42 command => 'whoami',
43 callback => sub {
44 my ($response) = @_;
45 print "I am $response->{result}{username}\n";
46 $client->shutdown;
47 },
48 );
49 },
50 );
51  
52 $poe_kernel->run;
53  
54 =head1 DESCRIPTION
55  
56 An event-driven client for L<POE::Component::Server::JSONUnix>. It connects to
57 the server's Unix domain socket, frames requests as newline-delimited JSON,
58 assigns each request an C<id>, and dispatches each response back to the caller
59 by matching the echoed C<id> -- so any number of requests may be in flight at
60 once.
61  
62 It also knows how to complete the server's Unix-ownership authentication
63 challenge (see L</authenticate>).
64  
65 =head1 CONSTRUCTOR
66  
67 =head2 spawn
68  
69 my $client = POE::Component::Server::JSONUnix::Client->spawn(%args);
70  
71 Creates the client's POE session and returns the client object. Recognised
72 arguments:
73  
74 =head3 socket_path
75  
76 Required. Filesystem path of the server's Unix domain socket.
77  
78 =head3 alias
79  
80 POE session alias. Defaults to C<json_unix_client>. Set this if you run more
81 than one client in a single process.
82  
83 =head3 auto_connect
84  
85 Connect immediately from C<spawn>. Defaults to true. When false, call
86 L</connect> yourself.
87  
88 =head3 auto_auth
89  
90 Run L</authenticate> automatically as soon as the connection is up. Defaults
91 to false. The outcome is delivered to C<on_auth>.
92  
93 =head3 request_timeout
94  
95 Default per-request timeout in seconds. A request that receives no response
96 in time is answered locally with
97 C<< {status => 'error', error => 'request timed out'} >>. No timeout by
98 default. Can be overridden per request.
99  
100 =head3 on_connect
101  
102 Code reference called as C<< $cb->($client) >> once the connection is
103 established.
104  
105 =head3 on_auth
106  
107 Code reference called as C<< $cb->($client, $response) >> when an
108 C<auto_auth> handshake completes (successfully or not).
109  
110 =head3 on_disconnect
111  
112 Code reference called as C<< $cb->($client, $reason) >> when the connection
113 is lost or closed.
114  
115 =head3 on_error
116  
117 Code reference called as C<< $cb->($operation, $errnum, $errstr) >> on
118 connect and I/O errors. A normal EOF from the server is not reported here
119 (it is reported via C<on_disconnect>).
120  
121 =head3 on_notice
122  
123 Code reference called as C<< $cb->($client, $response) >> for any server
124 message that cannot be matched to a pending request. This happens when:
125  
126 =over 4
127  
128 =item *
129  
130 the message has no C<id> at all -- e.g. the server's error response to a
131 request it could not parse an C<id> out of, or an unsolicited message pushed
132 by a server-side handler;
133  
134 =item *
135  
136 the C<id> is one this client is no longer waiting on -- most notably a
137 response that arrives I<after> its timeout already fired locally (see
138 L</call>), or a duplicate response to a request that was already answered.
139  
140 =back
141  
142 Unmatched messages are dropped silently if this is not set. A response
143 delivered here is never also delivered to the original request's C<callback>
144 or C<event> -- each request is answered exactly once.
145  
146 =cut
147  
148 6 ▶sub spawn {
Subroutine spawn: called CC=5 SCAR=16.3
Pod documented
149 6 my ( $class, %args ) = @_;
150  
151 my $path = delete $args{socket_path}
152 6 ▶ or croak "spawn() requires a 'socket_path' argument";
Branch: 1 branch
BranchTrueFalseTotal
my $path = delete $args{"socket_path"} or croak("spawn() requires a 'socket_path' argument") 6 0 6
153  
154 my $self = bless {
155 socket_path => $path,
156 alias => ( delete $args{alias} ) // 'json_unix_client',
157 auto_connect => ( delete $args{auto_connect} ) // 1,
158 auto_auth => ( delete $args{auto_auth} ) // 0,
159 request_timeout => delete $args{request_timeout}, # seconds (optional)
160 on_connect => delete $args{on_connect},
161 on_auth => delete $args{on_auth},
162 on_disconnect => delete $args{on_disconnect},
163 on_error => delete $args{on_error},
164 on_notice => delete $args{on_notice},
165 6 ▶ json => JSON::MaybeXS->new(
Condition83%5/6
delete $args{"alias"} // "json_unix_client"
l!l
60
delete $args{"auto_connect"} // 1
l!l
15
delete $args{"auto_auth"} // 0
l!l
15
MC/DC0%0/1
delete $args{"alias"} // "json_unix_client"
delete $args{"alias"}
MC/DC100%1/1
delete $args{"auto_connect"} // 1
delete $args{"auto_connect"}
MC/DC100%1/1
delete $args{"auto_auth"} // 0
delete $args{"auto_auth"}
Truth table50%1/2
A
A= delete $args{"alias"}
Aresult
11
00
Truth table100%2/2
A
A= delete $args{"auto_connect"}
Aresult
11
00
Truth table100%2/2
A
A= delete $args{"auto_auth"}
Aresult
11
00
166 utf8 => 1,
167 canonical => 1,
168 allow_nonref => 0,
169 ),
170 next_request_id => 1,
171 pending => {}, # request id => record
172 queue => [], # records created while still connecting
173 connecting => 0,
174 connected => 0,
175 auth => undef, # {uid, username} after a successful handshake
176 }, $class;
177  
178 6 POE::Session->create(
179 object_states => [
180 $self => {
181 _start => '_poe_start',
182 connect => '_poe_connect',
183 disconnect => '_poe_disconnect',
184 shutdown => '_poe_shutdown',
185 got_socket => '_poe_got_socket',
186 connect_error => '_poe_connect_error',
187 server_input => '_poe_server_input',
188 server_error => '_poe_server_error',
189 send_request => '_poe_send_request',
190 request_timed_out => '_poe_request_timed_out',
191 },
192 ],
193 );
194  
195 6 return $self;
196 } ## end sub spawn
197  
198 #--- public methods ----------------------------------------------------------
199  
200 =head1 METHODS
201  
202 =head2 connect
203  
204 $client->connect;
205  
206 Begin connecting to the server. A no-op if already connected or connecting.
207 Completion is signalled through C<on_connect> (or C<on_error> on failure).
208 May be called again after a disconnect.
209  
210 =head2 disconnect
211  
212 $client->disconnect;
213  
214 Drop the connection. Every request still awaiting a response is answered
215 locally with an error.
216  
217 =head2 shutdown
218  
219 $client->shutdown;
220  
221 Disconnect, release the session alias, and let the session end.
222  
223 =cut
224  
225 0 ▶sub connect { $poe_kernel->post( $_[0]{session_id}, 'connect' ); return }
Subroutine connect: not called CC=1 SCAR=6.9
Pod documented
226 0 ▶sub disconnect { $poe_kernel->post( $_[0]{session_id}, 'disconnect' ); return }
Subroutine disconnect: not called CC=1 SCAR=6.9
Pod documented
227 6 ▶sub shutdown { $poe_kernel->post( $_[0]{session_id}, 'shutdown' ); return }
Subroutine shutdown: called CC=1 SCAR=0.0
Pod documented
228  
229 =head2 call
230  
231 my $request_id = $client->call(
232 command => 'add',
233 args => { numbers => [ 1, 2, 3 ] },
234 callback => sub { my ($response) = @_; ... },
235 );
236  
237 Send a request. Returns the C<id> assigned to it.
238  
239 With neither C<callback> nor C<event> the request is fire-and-forget: it is
240 sent, and its response is discarded when it arrives.
241  
242 Every request is eventually answered exactly once: by the server, by the
243 timeout, or with a local error if the connection is (or comes) down. Requests
244 made while a connection attempt is in progress are queued and sent once it
245 completes.
246  
247 Arguments:
248  
249 =head3 command
250  
251 Required. The command name. C<cmd> is accepted as an alias.
252  
253 =head3 args
254  
255 Arbitrary payload for the command's handler.
256  
257 =head3 callback
258  
259 Code reference invoked as C<< $cb->($response, $context) >> with the full
260 decoded response envelope, e.g.
261 C<< {id => 7, status => 'ok', result => {...}} >>.
262  
263 =head3 event
264  
265 Instead of C<callback>, the name of an event to post back to the calling
266 session, with the response as C<ARG0> and C<$context> as C<ARG1>. The
267 requesting session is kept alive (via a reference count) until the response
268 arrives. Must be used from inside a running POE session; C<session> may be
269 given to direct the event elsewhere.
270  
271 =head3 context
272  
273 An opaque value handed back with the response, for correlating state on your
274 side.
275  
276 =head3 timeout
277  
278 Per-request timeout in seconds, overriding C<request_timeout>.
279  
280 A note on timeouts: a timeout is a local judgement, not a cancellation. The
281 server knows nothing about it and may still be working on the request; there
282 is no protocol message to withdraw one. When a timeout fires, the request's
283 C<callback> or C<event> receives C<< {status => 'error', error => 'request
284 timed out', id => $id} >> and the request is forgotten. If the server's real
285 response shows up later, it no longer matches anything pending and is routed
286 to C<on_notice> (carrying its C<id>, so it can still be recognised there) --
287 it will never be delivered to the original C<callback> or C<event>, which
288 have already been answered. Set C<on_notice> if late results matter to you;
289 otherwise they are dropped.
290  
291 =cut
292  
293 17 ▶sub call {
Subroutine call: called CC=5 SCAR=16.5
Pod documented
294 17 my ( $self, %req ) = @_;
295  
296 17 ▶ my $command = delete $req{command} // delete $req{cmd};
Condition33%1/3
delete $req{"command"} // delete $req{"cmd"}
l!l&&r!l&&!r
1700
MC/DC0%0/2
delete $req{"command"} // delete $req{"cmd"}
delete $req{"command"} delete $req{"cmd"}
Truth table33%1/3
A // B
A= delete $req{"command"}B= delete $req{"cmd"}
ABresult
1X1
011
000
297 17 ▶ croak "call() requires a 'command' argument"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $command 0 17 17
298 unless defined $command;
299  
300 17 my $args = delete $req{args};
301 17 ▶ my $timeout = ( delete $req{timeout} ) // $self->{request_timeout};
Condition66%2/3
delete $req{"timeout"} // $self->{"request_timeout"}
l!l&&r!l&&!r
2015
MC/DC50%1/2
delete $req{"timeout"} // $self->{"request_timeout"}
delete $req{"timeout"} $self->{"request_timeout"}
Truth table66%2/3
A // B
A= delete $req{"timeout"}B= $self->{"request_timeout"}
ABresult
1X1
011
000
302  
303 17 my $respond = $self->_make_responder(%req);
304  
305 17 my $request_id = $self->{next_request_id}++;
306 17 ▶ my $record = {
Branch: 1 branch
BranchTrueFalseTotal
defined $args ? : 4 13 17
307 id => $request_id,
308 respond => $respond,
309 timeout => $timeout,
310 request => {
311 command => $command,
312 id => $request_id,
313 ( defined $args ? ( args => $args ) : () ),
314 },
315 };
316  
317 17 $poe_kernel->post( $self->{session_id}, send_request => $record );
318 17 return $request_id;
319 } ## end sub call
320  
321 =head2 authenticate
322  
323 $client->authenticate(
324 callback => sub {
325 my ($response) = @_;
326 # {status => 'ok', result => {uid => 1000, username => 'alice'}}
327 },
328 );
329  
330 Authenticate to the server. If the server advertises kernel peer-credential
331 authentication (C<< peercred => 1 >> in its C<auth_start> reply), this simply
332 calls C<auth_verify> with no arguments -- no file is created, the OS proves the
333 UID. Otherwise it performs the Unix-ownership challenge: call C<auth_start>,
334 write the returned cookie to a fresh file in the server's C<temp_dir> (the OS
335 stamps the file with this process's effective UID, which is the proof the
336 server checks), then call C<auth_verify> and clean the file up. See
337 L<POE::Component::Server::JSONUnix/"KERNEL PEER-CREDENTIAL AUTHENTICATION">.
338  
339 Takes the same C<callback> / C<event> / C<context> arguments as L</call>. The
340 response delivered is the C<auth_verify> response on success, or a synthesised
341 C<< {status => 'error', ...} >> envelope if any step fails. After success,
342 L</authenticated>, L</uid> and L</username> reflect the verified identity.
343  
344 =cut
345  
346 2 ▶sub authenticate {
Subroutine authenticate: called CC=1 SCAR=2.8
Pod documented
347 2 my ( $self, %opt ) = @_;
348  
349 2 my $done = $self->_make_responder(%opt);
350  
351 # Record the verified identity from a successful auth_verify, then hand the
352 # response to the caller. Shared by the peercred and cookie paths.
353 2 ▶ my $finish = sub {
Subroutine __ANON__: called CC=4 SCAR=14.6
354 2 my ($verdict) = @_;
355 2 ▶ if ( ( $verdict->{status} // '' ) eq 'ok' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (($verdict->{"status"} // "") eq "ok") 2 0 2
Condition50%1/2
$verdict->{"status"} // ""
l!l
20
MC/DC0%0/1
$verdict->{"status"} // ""
$verdict->{"status"}
Truth table50%1/2
A
A= $verdict->{"status"}
Aresult
11
00
356 $self->{auth} = {
357 uid => $verdict->{result}{uid},
358 username => $verdict->{result}{username},
359 2 ▶ groups => $verdict->{result}{groups} // [],
Condition50%1/2
$verdict->{"result"}{"groups"} // []
l!l
02
MC/DC0%0/1
$verdict->{"result"}{"groups"} // []
$verdict->{"result"}{"groups"}
Truth table50%1/2
A
A= $verdict->{"result"}{"groups"}
Aresult
11
00
360 };
361 }
362 2 $done->($verdict);
363 2 return;
364 2 };
365  
366 $self->call(
367 command => 'auth_start',
368 2 ▶ callback => sub {
Subroutine __ANON__: called CC=12 SCAR=45.9
369 2 my ($challenge) = @_;
370  
371 2 ▶ unless ( ( $challenge->{status} // '' ) eq 'ok' ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (($challenge->{"status"} // "") eq "ok") 0 2 2
Condition50%1/2
$challenge->{"status"} // ""
l!l
20
MC/DC0%0/1
$challenge->{"status"} // ""
$challenge->{"status"}
Truth table50%1/2
A
A= $challenge->{"status"}
Aresult
11
00
372 $done->(
373 {
374 status => 'error',
375 0 ▶ error => 'auth_start failed: ' . ( $challenge->{error} // 'unknown error' ),
Condition0%0/2
$challenge->{"error"} // "unknown error"
l!l
00
MC/DC0%0/1
$challenge->{"error"} // "unknown error"
$challenge->{"error"}
Truth table0%0/2
A
A= $challenge->{"error"}
Aresult
11
00
376 }
377 );
378 0 return;
379 } ## end unless ( ( $challenge->{status} // '' ) eq 'ok')
380  
381 # When the server advertises kernel peer-credential auth, skip the
382 # file entirely: the uid is proven by the OS, so auth_verify needs
383 # no path.
384 2 ▶ if ( $challenge->{result}{peercred} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($challenge->{"result"}{"peercred"}) 2 0 2
385 2 $self->call(
386 command => 'auth_verify',
387 callback => $finish,
388 );
389 2 return;
390 }
391  
392 0 ▶ my $cookie = $challenge->{result}{cookie} // '';
Condition0%0/2
$challenge->{"result"}{"cookie"} // ""
l!l
00
MC/DC0%0/1
$challenge->{"result"}{"cookie"} // ""
$challenge->{"result"}{"cookie"}
Truth table0%0/2
A
A= $challenge->{"result"}{"cookie"}
Aresult
11
00
393 0 ▶ my $temp_dir = $challenge->{result}{temp_dir} // '';
Condition0%0/2
$challenge->{"result"}{"temp_dir"} // ""
l!l
00
MC/DC0%0/1
$challenge->{"result"}{"temp_dir"} // ""
$challenge->{"result"}{"temp_dir"}
Truth table0%0/2
A
A= $challenge->{"result"}{"temp_dir"}
Aresult
11
00
394 0 ▶ unless ( length $cookie && length $temp_dir && -d $temp_dir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $cookie and length $temp_dir and -d $temp_dir) 0 0 0
Condition0%0/6
length $cookie and length $temp_dir and -d $temp_dir
!ll&&!rl&&r
000
length $cookie and length $temp_dir
!ll&&!rl&&r
000
MC/DC0%0/3
length $cookie and length $temp_dir and -d $temp_dir
length $cookie length $temp_dir -d $temp_dir
Truth table0%0/4
A and B and C
A= length $cookieB= length $temp_dirC= -d $temp_dir
ABCresult
0XX0
10X0
1100
1111
395 0 $done->(
396 {
397 status => 'error',
398 error => 'auth_start returned an unusable cookie or temp_dir',
399 }
400 );
401 0 return;
402 } ## end unless ( length $cookie && length $temp_dir &&...)
403  
404 # PERMS creates the file as 0644 from the start rather than
405 # File::Temp's 0600 default: the server may run as another
406 # unprivileged user and must be able to read it. The proof is the
407 # file's ownership, not its secrecy -- the cookie is single-use
408 # and the file is unlinked on verify -- so world-readable is
409 # acceptable and there is no window where the file exists with
410 # the wrong mode.
411 0 my ( $fh, $cookie_path ) = eval {
412 0 File::Temp::tempfile(
413 'jsonunix_auth_XXXXXX',
414 DIR => $temp_dir,
415 UNLINK => 0,
416 PERMS => 0644,
417 );
418 };
419 0 ▶ unless ($fh) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($fh) 0 0 0
420 0 ▶ $done->(
Condition0%0/3
$@ || $!
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ || $!
$@ $!
Truth table0%0/3
A || B
A= $@B= $!
ABresult
1X1
011
000
421 {
422 status => 'error',
423 error => "could not create cookie file in $temp_dir: " . ( $@ || $! ),
424 }
425 );
426 0 return;
427 } ## end unless ($fh)
428 0 print {$fh} $cookie;
429 0 close $fh;
430  
431 $self->call(
432 command => 'auth_verify',
433 args => { path => $cookie_path },
434 0 ▶ callback => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
435 0 my ($verdict) = @_;
436 0 unlink $cookie_path; # server unlinks it; clean up if it did not
437 0 $finish->($verdict);
438 0 return;
439 },
440 0 );
441 0 return;
442 },
443 2 );
444 2 return;
445 } ## end sub authenticate
446  
447 =head2 connected
448  
449 True while a connection to the server is up.
450  
451 =head2 authenticated
452  
453 True after a successful L</authenticate> on the current connection.
454  
455 =head2 uid
456  
457 =head2 username
458  
459 The verified identity, or C<undef> before authentication. Cleared on
460 disconnect.
461  
462 =head2 groups
463  
464 Array reference of the verified user's group names, or C<undef> before
465 authentication. Empty unless the server has a permission policy configured
466 (only then does its C<auth_verify> report groups). Cleared on disconnect.
467  
468 =cut
469  
470 3 ▶sub connected { return $_[0]{connected} }
Subroutine connected: called CC=1 SCAR=0.0
Pod documented
471 4 ▶sub authenticated { return defined $_[0]{auth} }
Subroutine authenticated: called CC=1 SCAR=0.0
Pod documented
472 2 ▶sub uid { return $_[0]{auth} ? $_[0]{auth}{uid} : undef }
Subroutine uid: called CC=2 SCAR=7.6
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$_[0]{'auth'} ? : 2 0 2
473 1 ▶sub username { return $_[0]{auth} ? $_[0]{auth}{username} : undef }
Subroutine username: called CC=2 SCAR=7.6
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$_[0]{'auth'} ? : 1 0 1
474 0 ▶sub groups { return $_[0]{auth} ? $_[0]{auth}{groups} : undef }
Subroutine groups: not called CC=2 SCAR=17.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$_[0]{'auth'} ? : 0 0 0
475  
476 #--- response routing --------------------------------------------------------
477  
478 # Normalise callback/event/context into a single coderef that delivers one
479 # response envelope. Called in the requester's context so that
480 # get_active_session() names the right session for event-style delivery.
481 19 ▶sub _make_responder {
Subroutine _make_responder: called CC=5 SCAR=16.2
482 19 my ( $self, %opt ) = @_;
483  
484 19 my $callback = delete $opt{callback};
485 19 my $event = delete $opt{event};
486 19 my $context = delete $opt{context};
487  
488 19 ▶ if ( defined $callback ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $callback) 17 2 19
489 17 ▶ croak "'callback' must be a code reference"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $callback eq "CODE" 0 17 17
490 unless ref $callback eq 'CODE';
491 17 ▶ return sub { $callback->( $_[0], $context ); return };
Subroutine __ANON__: called CC=1 SCAR=0.0
492 }
493  
494 2 ▶ if ( defined $event ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $event) 1 1 2
495 1 ▶ my $session_id = $opt{session} // $poe_kernel->get_active_session->ID;
Condition33%1/3
$opt{"session"} // $POE::Component::Server::JSONUnix::Client::poe_kernel->get_active_session->ID
l!l&&r!l&&!r
010
MC/DC0%0/2
$opt{"session"} // $POE::Component::Server::JSONUnix::Client::poe_kernel->get_active_session->ID
$opt{"session"} $POE::Component::Server::JSONUnix::Client::poe_kernel->get_active_session->ID
Truth table33%1/3
A // B
A= $opt{"session"}B= $POE::Component::Server::JSONUnix::Client::poe_kernel->get_active_session->ID
ABresult
1X1
011
000
496 1 $poe_kernel->refcount_increment( $session_id, REFCOUNT_TAG );
497 1 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
498 1 $poe_kernel->post( $session_id, $event, $_[0], $context );
499 1 $poe_kernel->refcount_decrement( $session_id, REFCOUNT_TAG );
500 1 return;
501 1 };
502 } ## end if ( defined $event )
503  
504 1 ▶ return sub { }; # fire and forget
Subroutine __ANON__: called CC=1 SCAR=0.0
505 } ## end sub _make_responder
506  
507 #--- POE: session lifecycle --------------------------------------------------
508  
509 6 ▶sub _poe_start {
Subroutine _poe_start: called CC=2 SCAR=6.9
510 6 my ( $self, $kernel, $session ) = @_[ OBJECT, KERNEL, SESSION ];
511 6 $self->{session_id} = $session->ID;
512 6 $kernel->alias_set( $self->{alias} );
513 6 ▶ $kernel->yield('connect') if $self->{auto_connect};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"auto_connect"} 5 1 6
514 6 return;
515 }
516  
517 6 ▶sub _poe_shutdown {
Subroutine _poe_shutdown: called CC=1 SCAR=0.0
518 6 my ( $self, $kernel ) = @_[ OBJECT, KERNEL ];
519 6 $self->_drop_connection('client shutting down');
520 6 $kernel->alias_remove( $self->{alias} );
521 6 return;
522 }
523  
524 #--- POE: connection management ----------------------------------------------
525  
526 5 ▶sub _poe_connect {
Subroutine _poe_connect: called CC=3 SCAR=11.8
527 5 my ($self) = $_[OBJECT];
528  
529 5 ▶ return if $self->{connected} || $self->{connecting};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"connected"} or $self->{"connecting"} 0 5 5
Condition33%1/3
$self->{"connected"} or $self->{"connecting"}
l!l&&r!l&&!r
005
MC/DC0%0/2
$self->{"connected"} or $self->{"connecting"}
$self->{"connected"} $self->{"connecting"}
Truth table33%1/3
A or B
A= $self->{"connected"}B= $self->{"connecting"}
ABresult
1X1
011
000
530  
531 5 $self->{connecting} = 1;
532 $self->{connector} = POE::Wheel::SocketFactory->new(
533 SocketDomain => PF_UNIX,
534 SocketType => SOCK_STREAM,
535 RemoteAddress => $self->{socket_path},
536 5 SuccessEvent => 'got_socket',
537 FailureEvent => 'connect_error',
538 );
539 5 return;
540 } ## end sub _poe_connect
541  
542 4 ▶sub _poe_got_socket {
Subroutine _poe_got_socket: called CC=4 SCAR=13.9
543 4 my ( $self, $kernel, $socket ) = @_[ OBJECT, KERNEL, ARG0 ];
544  
545 4 delete $self->{connector};
546 4 $self->{connecting} = 0;
547 4 $self->{connected} = 1;
548  
549 4 $self->{wheel} = POE::Wheel::ReadWrite->new(
550 Handle => $socket,
551 Driver => POE::Driver::SysRW->new,
552 Filter => POE::Filter::Line->new( Literal => "\n" ),
553 InputEvent => 'server_input',
554 ErrorEvent => 'server_error',
555 );
556  
557 # Flush anything queued while the connection was being made.
558 4 my @queued = splice @{ $self->{queue} };
559 4 $kernel->yield( send_request => $_ ) for @queued;
560  
561 4 ▶ $self->{on_connect}->($self) if $self->{on_connect};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"on_connect"} 3 1 4
562  
563 4 ▶ if ( $self->{auto_auth} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"auto_auth"}) 1 3 4
564 $self->authenticate(
565 1 ▶ callback => sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
566 1 my ($response) = @_;
567 1 ▶ $self->{on_auth}->( $self, $response ) if $self->{on_auth};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"on_auth"} 1 0 1
568 1 return;
569 },
570 1 );
571 } ## end if ( $self->{auto_auth} )
572 4 return;
573 } ## end sub _poe_got_socket
574  
575 1 ▶sub _poe_connect_error {
Subroutine _poe_connect_error: called CC=2 SCAR=7.0
576 1 my ( $self, $op, $errnum, $errstr ) = @_[ OBJECT, ARG0, ARG1, ARG2 ];
577  
578 1 ▶ $self->{on_error}->( "connect:$op", $errnum, $errstr ) if $self->{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"on_error"} 1 0 1
579 1 $self->_drop_connection("connect failed during $op: $errstr");
580 1 return;
581 }
582  
583 0 ▶sub _poe_disconnect {
Subroutine _poe_disconnect: not called CC=3 SCAR=24.8
584 0 my ($self) = $_[OBJECT];
585 0 my $was_connected = $self->{connected};
586 0 $self->_drop_connection('disconnected');
587 $self->{on_disconnect}->( $self, 'disconnected' )
588 0 ▶ if $was_connected && $self->{on_disconnect};
Branch: 1 branch
BranchTrueFalseTotal
if $was_connected and $self->{"on_disconnect"} 0 0 0
Condition0%0/3
$was_connected and $self->{"on_disconnect"}
!ll&&!rl&&r
000
MC/DC0%0/2
$was_connected and $self->{"on_disconnect"}
$was_connected $self->{"on_disconnect"}
Truth table0%0/3
A and B
A= $was_connectedB= $self->{"on_disconnect"}
ABresult
0X0
100
111
589 0 return;
590 }
591  
592 2 ▶sub _poe_server_error {
Subroutine _poe_server_error: called CC=6 SCAR=20.5
593 2 my ( $self, $op, $errnum, $errstr ) = @_[ OBJECT, ARG0, ARG1, ARG2 ];
594  
595 # operation 'read' with errnum 0 is a normal EOF (server hung up).
596 2 ▶ my $eof = ( $op eq 'read' && $errnum == 0 );
Condition33%1/3
$op eq 'read' && $errnum == 0
!ll&&!rl&&r
002
MC/DC0%0/2
$op eq 'read' && $errnum == 0
$op eq 'read' $errnum == 0
Truth table33%1/3
A && B
A= $op eq 'read'B= $errnum == 0
ABresult
0X0
100
111
597 2 ▶ my $reason = $eof ? 'server closed connection' : "$op error: $errstr ($errnum)";
Branch: 1 branch
BranchTrueFalseTotal
$eof ? : 2 0 2
598  
599 2 ▶ $self->{on_error}->( $op, $errnum, $errstr ) if $self->{on_error} && !$eof;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"on_error"} and not $eof 0 2 2
Condition33%1/3
$self->{"on_error"} and not $eof
!ll&&!rl&&r
200
MC/DC0%0/2
$self->{"on_error"} and not $eof
$self->{"on_error"} not $eof
Truth table33%1/3
A and not(B)
A= $self->{"on_error"}B= not $eof
ABresult
0X0
100
111
600 2 $self->_drop_connection($reason);
601 2 ▶ $self->{on_disconnect}->( $self, $reason ) if $self->{on_disconnect};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"on_disconnect"} 2 0 2
602 2 return;
603 } ## end sub _poe_server_error
604  
605 # Tear down the connection state and answer every outstanding request with an
606 # error so no caller is left waiting forever.
607 9 ▶sub _drop_connection {
Subroutine _drop_connection: called CC=3 SCAR=11.0
608 9 my ( $self, $reason ) = @_;
609  
610 9 delete $self->{wheel};
611 9 delete $self->{connector};
612 9 $self->{connecting} = 0;
613 9 $self->{connected} = 0;
614 9 $self->{auth} = undef;
615  
616 9 my @records = ( ( splice @{ $self->{queue} } ), values %{ $self->{pending} } );
617 9 %{ $self->{pending} } = ();
618  
619 9 for my $record (@records) {
620 $poe_kernel->alarm_remove( $record->{alarm_id} )
621 1 ▶ if defined $record->{alarm_id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $record->{"alarm_id"} 0 1 1
622 1 $record->{respond}->( { status => 'error', error => $reason, id => $record->{id} } );
623 }
624 9 return;
625 } ## end sub _drop_connection
626  
627 #--- POE: request / response flow --------------------------------------------
628  
629 17 ▶sub _poe_send_request {
Subroutine _poe_send_request: called CC=5 SCAR=16.2
630 17 my ( $self, $kernel, $record ) = @_[ OBJECT, KERNEL, ARG0 ];
631  
632 17 ▶ unless ( $self->{connected} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"connected"}) 2 15 17
633 2 ▶ if ( $self->{connecting} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"connecting"}) 1 1 2
634 1 push @{ $self->{queue} }, $record;
635 1 return;
636 }
637 1 $record->{respond}->( { status => 'error', error => 'not connected', id => $record->{id} } );
638 1 return;
639 } ## end unless ( $self->{connected} )
640  
641 15 my $json = eval { $self->{json}->encode( $record->{request} ) };
642 15 ▶ unless ( defined $json ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $json) 0 15 15
643 $record->{respond}->(
644 {
645 status => 'error',
646 error => 'request could not be serialised as JSON',
647 id => $record->{id},
648 }
649 0 );
650 0 return;
651 } ## end unless ( defined $json )
652  
653 15 $self->{pending}{ $record->{id} } = $record;
654 15 ▶ if ( defined $record->{timeout} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $record->{"timeout"}) 2 13 15
655 2 $record->{alarm_id} = $kernel->delay_set( request_timed_out => $record->{timeout}, $record->{id} );
656 }
657 15 $self->{wheel}->put($json); # Filter::Line appends the trailing newline
658 15 return;
659 } ## end sub _poe_send_request
660  
661 14 ▶sub _poe_server_input {
Subroutine _poe_server_input: called CC=9 SCAR=24.8
662 14 my ( $self, $kernel, $line ) = @_[ OBJECT, KERNEL, ARG0 ];
663  
664 14 ▶ return unless defined $line && $line =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line and $line =~ /\S/ 0 14 14
Condition33%1/3
defined $line and $line =~ /\S/
!ll&&!rl&&r
0014
MC/DC0%0/2
defined $line and $line =~ /\S/
defined $line $line =~ /\S/
Truth table33%1/3
A and B
A= defined $lineB= $line =~ /\S/
ABresult
0X0
100
111
665  
666 14 my $response;
667 14 ▶ unless ( eval { $response = $self->{json}->decode($line); 1 }
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $response = $self->{"json"}->decode($line); 1 } } and ref $response eq "HASH") 0 14 14
Condition33%1/3
eval { do { $response = $self->{"json"}->decode($line); 1 } } and ref $response eq "HASH"
!ll&&!rl&&r
0014
MC/DC0%0/2
eval { do { $response = $self->{"json"}->decode($line); 1 } } and ref $response eq "HASH"
eval { do { $response = $self->{"json"}->decode($line); 1 } } ref $response eq "HASH"
Truth table33%1/3
A and B
A= eval { do { $response = $self->{"json"}->decode($line); 1 } }B= ref $response eq "HASH"
ABresult
0X0
100
111
668 && ref $response eq 'HASH' )
669 {
670 0 carp "unparsable line from server: $line";
671 0 return;
672 }
673  
674 my $record =
675 defined $response->{id}
676 ? delete $self->{pending}{ $response->{id} }
677 14 ▶ : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $response->{'id'} ? : 14 0 14
678  
679 14 ▶ unless ($record) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($record) 1 13 14
680 # No id, or an id we are not waiting on (e.g. the response arrived
681 # after its timeout already fired).
682 1 ▶ $self->{on_notice}->( $self, $response ) if $self->{on_notice};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"on_notice"} 1 0 1
683 1 return;
684 }
685  
686 $kernel->alarm_remove( $record->{alarm_id} )
687 13 ▶ if defined $record->{alarm_id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $record->{"alarm_id"} 0 13 13
688 13 $record->{respond}->($response);
689 13 return;
690 } ## end sub _poe_server_input
691  
692 2 ▶sub _poe_request_timed_out {
Subroutine _poe_request_timed_out: called CC=2 SCAR=7.0
693 2 my ( $self, $request_id ) = @_[ OBJECT, ARG0 ];
694  
695 2 ▶ my $record = delete $self->{pending}{$request_id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $record = delete $self->{"pending"}{$request_id} or return 2 0 2
696 2 $record->{respond}->( { status => 'error', error => 'request timed out', id => $request_id } );
697 2 return;
698 }
699  
700 2 1;
701  
702 __END__
« JSONUnix/BlockingClient.pm ↑ Summary