JSONUnix/Client.pm

filter: Statementstmt 89.8% 177 / 197 Branchbran 61.4% 43 / 70 Conditioncond 38.8% 21 / 54 MC/DCmcdc 9.3% 3 / 32 Subroutinesub 89.4% 34 / 38 Podpod 100% 11 / 11 totaltotal 71.8% 289 / 402 SCAR 47.3
CC
59
Cov
75%
__ANON__
21.6
_poe_disconnect
12.0
_poe_server_input
12.0
CRAP 112.9
« JSONUnix.pm ↑ Summary JSONUnix/BlockingClient.pm »
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(
13 Wheel::SocketFactory
14 Wheel::ReadWrite
15 Filter::Line
16 Driver::SysRW
17 2 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 2 our $VERSION = '0.1.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 sub spawn {
149 6 ▶ my ( $class, %args ) = @_;
Subroutine spawn: called CC=5 SCAR=16.3
Pod documented
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") 0 6 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 sub call {
294 17 ▶ my ( $self, %req ) = @_;
Subroutine call: called CC=5 SCAR=16.5
Pod documented
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 ? : 6 11 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 Perform the server's Unix-ownership challenge: call C<auth_start>, write the
331 returned cookie to a fresh file in the server's C<temp_dir> (the OS stamps the
332 file with this process's effective UID, which is the proof the server checks),
333 then call C<auth_verify> and clean the file up.
334  
335 Takes the same C<callback> / C<event> / C<context> arguments as L</call>. The
336 response delivered is the C<auth_verify> response on success, or a synthesised
337 C<< {status => 'error', ...} >> envelope if any step fails. After success,
338 L</authenticated>, L</uid> and L</username> reflect the verified identity.
339  
340 =cut
341  
342 sub authenticate {
343 2 ▶ my ( $self, %opt ) = @_;
Subroutine authenticate: called CC=1 SCAR=0.7
Pod documented
344  
345 2 my $done = $self->_make_responder(%opt);
346  
347 $self->call(
348 command => 'auth_start',
349 callback => sub {
350 2 ▶ my ($challenge) = @_;
Subroutine __ANON__: called CC=11 SCAR=30.7
351  
352 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
353 $done->(
354 {
355 status => 'error',
356 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
357 }
358 );
359 0 return;
360 } ## end unless ( ( $challenge->{status} // '' ) eq 'ok')
361  
362 2 ▶ my $cookie = $challenge->{result}{cookie} // '';
Condition50%1/2
$challenge->{"result"}{"cookie"} // ""
l!l
20
MC/DC0%0/1
$challenge->{"result"}{"cookie"} // ""
$challenge->{"result"}{"cookie"}
Truth table50%1/2
A
A= $challenge->{"result"}{"cookie"}
Aresult
11
00
363 2 ▶ my $temp_dir = $challenge->{result}{temp_dir} // '';
Condition50%1/2
$challenge->{"result"}{"temp_dir"} // ""
l!l
20
MC/DC0%0/1
$challenge->{"result"}{"temp_dir"} // ""
$challenge->{"result"}{"temp_dir"}
Truth table50%1/2
A
A= $challenge->{"result"}{"temp_dir"}
Aresult
11
00
364 2 ▶ 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 2 2
Condition33%2/6
length $cookie and length $temp_dir and -d $temp_dir
!ll&&!rl&&r
002
length $cookie and length $temp_dir
!ll&&!rl&&r
002
MC/DC0%0/3
length $cookie and length $temp_dir and -d $temp_dir
length $cookie length $temp_dir -d $temp_dir
Truth table25%1/4
A and B and C
A= length $cookieB= length $temp_dirC= -d $temp_dir
ABCresult
0XX0
10X0
1100
1111
365 0 $done->(
366 {
367 status => 'error',
368 error => 'auth_start returned an unusable cookie or temp_dir',
369 }
370 );
371 0 return;
372 } ## end unless ( length $cookie && length $temp_dir &&...)
373  
374 # PERMS creates the file as 0644 from the start rather than
375 # File::Temp's 0600 default: the server may run as another
376 # unprivileged user and must be able to read it. The proof is the
377 # file's ownership, not its secrecy -- the cookie is single-use
378 # and the file is unlinked on verify -- so world-readable is
379 # acceptable and there is no window where the file exists with
380 # the wrong mode.
381 2 my ( $fh, $cookie_path ) = eval {
382 2 File::Temp::tempfile(
383 'jsonunix_auth_XXXXXX',
384 DIR => $temp_dir,
385 UNLINK => 0,
386 PERMS => 0644,
387 );
388 };
389 2 ▶ unless ($fh) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($fh) 0 2 2
390 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
391 {
392 status => 'error',
393 error => "could not create cookie file in $temp_dir: " . ( $@ || $! ),
394 }
395 );
396 0 return;
397 } ## end unless ($fh)
398 2 print {$fh} $cookie;
399 2 close $fh;
400  
401 $self->call(
402 command => 'auth_verify',
403 args => { path => $cookie_path },
404 callback => sub {
405 2 ▶ my ($verdict) = @_;
Subroutine __ANON__: called CC=4 SCAR=14.5
406 2 unlink $cookie_path; # server unlinks it; clean up if it did not
407 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
408 $self->{auth} = {
409 uid => $verdict->{result}{uid},
410 username => $verdict->{result}{username},
411 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
412 };
413 }
414 2 $done->($verdict);
415 2 return;
416 },
417 2 );
418 2 return;
419 },
420 2 );
421 2 return;
422 } ## end sub authenticate
423  
424 =head2 connected
425  
426 True while a connection to the server is up.
427  
428 =head2 authenticated
429  
430 True after a successful L</authenticate> on the current connection.
431  
432 =head2 uid
433  
434 =head2 username
435  
436 The verified identity, or C<undef> before authentication. Cleared on
437 disconnect.
438  
439 =head2 groups
440  
441 Array reference of the verified user's group names, or C<undef> before
442 authentication. Empty unless the server has a permission policy configured
443 (only then does its C<auth_verify> report groups). Cleared on disconnect.
444  
445 =cut
446  
447 3 ▶sub connected { return $_[0]{connected} }
Subroutine connected: called CC=1 SCAR=0.0
Pod documented
448 4 ▶sub authenticated { return defined $_[0]{auth} }
Subroutine authenticated: called CC=1 SCAR=0.0
Pod documented
449 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
450 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
451 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
452  
453 #--- response routing --------------------------------------------------------
454  
455 # Normalise callback/event/context into a single coderef that delivers one
456 # response envelope. Called in the requester's context so that
457 # get_active_session() names the right session for event-style delivery.
458 sub _make_responder {
459 19 ▶ my ( $self, %opt ) = @_;
Subroutine _make_responder: called CC=5 SCAR=16.2
460  
461 19 my $callback = delete $opt{callback};
462 19 my $event = delete $opt{event};
463 19 my $context = delete $opt{context};
464  
465 19 ▶ if ( defined $callback ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $callback) 17 2 19
466 17 ▶ croak "'callback' must be a code reference"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $callback eq "CODE" 0 17 17
467 unless ref $callback eq 'CODE';
468 17 ▶ return sub { $callback->( $_[0], $context ); return };
Subroutine __ANON__: called CC=1 SCAR=0.0
469 }
470  
471 2 ▶ if ( defined $event ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $event) 1 1 2
472 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
473 1 $poe_kernel->refcount_increment( $session_id, REFCOUNT_TAG );
474 return sub {
475 1 ▶ $poe_kernel->post( $session_id, $event, $_[0], $context );
Subroutine __ANON__: called CC=1 SCAR=0.0
476 1 $poe_kernel->refcount_decrement( $session_id, REFCOUNT_TAG );
477 1 return;
478 1 };
479 } ## end if ( defined $event )
480  
481 1 ▶ return sub { }; # fire and forget
Subroutine __ANON__: called CC=1 SCAR=0.0
482 } ## end sub _make_responder
483  
484 #--- POE: session lifecycle --------------------------------------------------
485  
486 sub _poe_start {
487 6 ▶ my ( $self, $kernel, $session ) = @_[ OBJECT, KERNEL, SESSION ];
Subroutine _poe_start: called CC=2 SCAR=6.9
488 6 $self->{session_id} = $session->ID;
489 6 $kernel->alias_set( $self->{alias} );
490 6 ▶ $kernel->yield('connect') if $self->{auto_connect};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"auto_connect"} 5 1 6
491 6 return;
492 }
493  
494 sub _poe_shutdown {
495 6 ▶ my ( $self, $kernel ) = @_[ OBJECT, KERNEL ];
Subroutine _poe_shutdown: called CC=1 SCAR=0.0
496 6 $self->_drop_connection('client shutting down');
497 6 $kernel->alias_remove( $self->{alias} );
498 6 return;
499 }
500  
501 #--- POE: connection management ----------------------------------------------
502  
503 sub _poe_connect {
504 5 ▶ my ($self) = $_[OBJECT];
Subroutine _poe_connect: called CC=3 SCAR=11.8
505  
506 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
507  
508 5 $self->{connecting} = 1;
509 $self->{connector} = POE::Wheel::SocketFactory->new(
510 SocketDomain => PF_UNIX,
511 SocketType => SOCK_STREAM,
512 RemoteAddress => $self->{socket_path},
513 5 SuccessEvent => 'got_socket',
514 FailureEvent => 'connect_error',
515 );
516 5 return;
517 } ## end sub _poe_connect
518  
519 sub _poe_got_socket {
520 4 ▶ my ( $self, $kernel, $socket ) = @_[ OBJECT, KERNEL, ARG0 ];
Subroutine _poe_got_socket: called CC=4 SCAR=13.9
521  
522 4 delete $self->{connector};
523 4 $self->{connecting} = 0;
524 4 $self->{connected} = 1;
525  
526 4 $self->{wheel} = POE::Wheel::ReadWrite->new(
527 Handle => $socket,
528 Driver => POE::Driver::SysRW->new,
529 Filter => POE::Filter::Line->new( Literal => "\n" ),
530 InputEvent => 'server_input',
531 ErrorEvent => 'server_error',
532 );
533  
534 # Flush anything queued while the connection was being made.
535 4 my @queued = splice @{ $self->{queue} };
536 4 $kernel->yield( send_request => $_ ) for @queued;
537  
538 4 ▶ $self->{on_connect}->($self) if $self->{on_connect};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"on_connect"} 3 1 4
539  
540 4 ▶ if ( $self->{auto_auth} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"auto_auth"}) 1 3 4
541 $self->authenticate(
542 callback => sub {
543 1 ▶ my ($response) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.1
544 1 ▶ $self->{on_auth}->( $self, $response ) if $self->{on_auth};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"on_auth"} 1 0 1
545 1 return;
546 },
547 1 );
548 } ## end if ( $self->{auto_auth} )
549 4 return;
550 } ## end sub _poe_got_socket
551  
552 sub _poe_connect_error {
553 1 ▶ my ( $self, $op, $errnum, $errstr ) = @_[ OBJECT, ARG0, ARG1, ARG2 ];
Subroutine _poe_connect_error: called CC=2 SCAR=7.0
554  
555 1 ▶ $self->{on_error}->( "connect:$op", $errnum, $errstr ) if $self->{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"on_error"} 1 0 1
556 1 $self->_drop_connection("connect failed during $op: $errstr");
557 1 return;
558 }
559  
560 sub _poe_disconnect {
561 0 ▶ my ($self) = $_[OBJECT];
Subroutine _poe_disconnect: not called CC=3 SCAR=24.8
562 0 my $was_connected = $self->{connected};
563 0 $self->_drop_connection('disconnected');
564 $self->{on_disconnect}->( $self, 'disconnected' )
565 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
566 0 return;
567 }
568  
569 sub _poe_server_error {
570 2 ▶ my ( $self, $op, $errnum, $errstr ) = @_[ OBJECT, ARG0, ARG1, ARG2 ];
Subroutine _poe_server_error: called CC=6 SCAR=20.5
571  
572 # operation 'read' with errnum 0 is a normal EOF (server hung up).
573 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
574 2 ▶ my $reason = $eof ? 'server closed connection' : "$op error: $errstr ($errnum)";
Branch: 1 branch
BranchTrueFalseTotal
$eof ? : 2 0 2
575  
576 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
577 2 $self->_drop_connection($reason);
578 2 ▶ $self->{on_disconnect}->( $self, $reason ) if $self->{on_disconnect};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"on_disconnect"} 2 0 2
579 2 return;
580 } ## end sub _poe_server_error
581  
582 # Tear down the connection state and answer every outstanding request with an
583 # error so no caller is left waiting forever.
584 sub _drop_connection {
585 9 ▶ my ( $self, $reason ) = @_;
Subroutine _drop_connection: called CC=3 SCAR=11.0
586  
587 9 delete $self->{wheel};
588 9 delete $self->{connector};
589 9 $self->{connecting} = 0;
590 9 $self->{connected} = 0;
591 9 $self->{auth} = undef;
592  
593 9 my @records = ( ( splice @{ $self->{queue} } ), values %{ $self->{pending} } );
594 9 %{ $self->{pending} } = ();
595  
596 9 for my $record (@records) {
597 $poe_kernel->alarm_remove( $record->{alarm_id} )
598 1 ▶ if defined $record->{alarm_id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $record->{"alarm_id"} 0 1 1
599 1 $record->{respond}->( { status => 'error', error => $reason, id => $record->{id} } );
600 }
601 9 return;
602 } ## end sub _drop_connection
603  
604 #--- POE: request / response flow --------------------------------------------
605  
606 sub _poe_send_request {
607 17 ▶ my ( $self, $kernel, $record ) = @_[ OBJECT, KERNEL, ARG0 ];
Subroutine _poe_send_request: called CC=5 SCAR=16.2
608  
609 17 ▶ unless ( $self->{connected} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"connected"}) 2 15 17
610 2 ▶ if ( $self->{connecting} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"connecting"}) 1 1 2
611 1 push @{ $self->{queue} }, $record;
612 1 return;
613 }
614 1 $record->{respond}->( { status => 'error', error => 'not connected', id => $record->{id} } );
615 1 return;
616 } ## end unless ( $self->{connected} )
617  
618 15 my $json = eval { $self->{json}->encode( $record->{request} ) };
619 15 ▶ unless ( defined $json ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $json) 0 15 15
620 $record->{respond}->(
621 {
622 status => 'error',
623 error => 'request could not be serialised as JSON',
624 id => $record->{id},
625 }
626 0 );
627 0 return;
628 } ## end unless ( defined $json )
629  
630 15 $self->{pending}{ $record->{id} } = $record;
631 15 ▶ if ( defined $record->{timeout} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $record->{"timeout"}) 2 13 15
632 2 $record->{alarm_id} = $kernel->delay_set( request_timed_out => $record->{timeout}, $record->{id} );
633 }
634 15 $self->{wheel}->put($json); # Filter::Line appends the trailing newline
635 15 return;
636 } ## end sub _poe_send_request
637  
638 sub _poe_server_input {
639 14 ▶ my ( $self, $kernel, $line ) = @_[ OBJECT, KERNEL, ARG0 ];
Subroutine _poe_server_input: called CC=9 SCAR=24.8
640  
641 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
642  
643 14 my $response;
644 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
645 && ref $response eq 'HASH' )
646 {
647 0 carp "unparsable line from server: $line";
648 0 return;
649 }
650  
651 my $record =
652 defined $response->{id}
653 ? delete $self->{pending}{ $response->{id} }
654 14 ▶ : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $response->{'id'} ? : 14 0 14
655  
656 14 ▶ unless ($record) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($record) 1 13 14
657 # No id, or an id we are not waiting on (e.g. the response arrived
658 # after its timeout already fired).
659 1 ▶ $self->{on_notice}->( $self, $response ) if $self->{on_notice};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"on_notice"} 1 0 1
660 1 return;
661 }
662  
663 $kernel->alarm_remove( $record->{alarm_id} )
664 13 ▶ if defined $record->{alarm_id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $record->{"alarm_id"} 0 13 13
665 13 $record->{respond}->($response);
666 13 return;
667 } ## end sub _poe_server_input
668  
669 sub _poe_request_timed_out {
670 2 ▶ my ( $self, $request_id ) = @_[ OBJECT, ARG0 ];
Subroutine _poe_request_timed_out: called CC=2 SCAR=7.0
671  
672 2 ▶ my $record = delete $self->{pending}{$request_id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $record = delete $self->{"pending"}{$request_id} or return 0 2 2
673 2 $record->{respond}->( { status => 'error', error => 'request timed out', id => $request_id } );
674 2 return;
675 }
676  
677 2 1;
678  
679 __END__
« JSONUnix.pm ↑ Summary JSONUnix/BlockingClient.pm »