File Coverage

blib/lib/IO/Async/Handle.pm
Criterion Covered Total %
statement 202 217 93.0
branch 99 118 83.9
condition 17 24 70.8
subroutine 30 32 93.7
pod 16 17 94.1
total 364 408 89.2


line stmt bran cond sub pod time code
1             # You may distribute under the terms of either the GNU General Public License
2             # or the Artistic License (the same terms as Perl itself)
3             #
4             # (C) Paul Evans, 2006-2019 -- leonerd@leonerd.org.uk
5              
6             package IO::Async::Handle;
7              
8 74     74   5442 use strict;
  74         175  
  74         2734  
9 74     74   418 use warnings;
  74         192  
  74         2932  
10 74     74   485 use base qw( IO::Async::Notifier );
  74         187  
  74         27910  
11              
12             our $VERSION = '0.79';
13              
14 74     74   600 use Carp;
  74         909  
  74         5941  
15              
16 74     74   7784 use IO::Handle; # give methods to bare IO handles
  74         78859  
  74         3507  
17              
18 74     74   489 use Future;
  74         160  
  74         2174  
19 74     74   44423 use Future::Utils qw( try_repeat );
  74         177303  
  74         5987  
20              
21 74     74   1787 use IO::Async::OS;
  74         627  
  74         180032  
22              
23             =head1 NAME
24              
25             C - event callbacks for a non-blocking file descriptor
26              
27             =head1 SYNOPSIS
28              
29             This class is likely not to be used directly, because subclasses of it exist
30             to handle more specific cases. Here is an example of how it would be used to
31             watch a listening socket for new connections. In real code, it is likely that
32             the C<< Loop->listen >> method would be used instead.
33              
34             use IO::Socket::INET;
35             use IO::Async::Handle;
36              
37             use IO::Async::Loop;
38             my $loop = IO::Async::Loop->new;
39              
40             my $socket = IO::Socket::INET->new( LocalPort => 1234, Listen => 1 );
41              
42             my $handle = IO::Async::Handle->new(
43             handle => $socket,
44              
45             on_read_ready => sub {
46             my $new_client = $socket->accept;
47             ...
48             },
49             );
50              
51             $loop->add( $handle );
52              
53             For most other uses with sockets, pipes or other filehandles that carry a byte
54             stream, the L class is likely to be more suitable. For
55             non-stream sockets, see L.
56              
57             =head1 DESCRIPTION
58              
59             This subclass of L allows non-blocking IO on filehandles.
60             It provides event handlers for when the filehandle is read- or write-ready.
61              
62             =cut
63              
64             =head1 EVENTS
65              
66             The following events are invoked, either using subclass methods or CODE
67             references in parameters:
68              
69             =head2 on_read_ready
70              
71             Invoked when the read handle becomes ready for reading.
72              
73             =head2 on_write_ready
74              
75             Invoked when the write handle becomes ready for writing.
76              
77             =head2 on_closed
78              
79             Optional. Invoked when the handle becomes closed.
80              
81             This handler is invoked before the filehandles are closed and the Handle
82             removed from its containing Loop. The C will still return the containing
83             Loop object.
84              
85             =cut
86              
87             =head1 PARAMETERS
88              
89             The following named parameters may be passed to C or C:
90              
91             =head2 read_handle => IO
92              
93             =head2 write_handle => IO
94              
95             The reading and writing IO handles. Each must implement the C method.
96             Primarily used for passing C / C; see the SYNOPSIS section of
97             L for an example.
98              
99             =head2 handle => IO
100              
101             The IO handle for both reading and writing; instead of passing each separately
102             as above. Must implement C method in way that C does.
103              
104             =head2 read_fileno => INT
105              
106             =head2 write_fileno => INT
107              
108             File descriptor numbers for reading and writing. If these are given as an
109             alternative to C or C then a new C
110             instance will be constructed around each.
111              
112             =head2 on_read_ready => CODE
113              
114             =head2 on_write_ready => CODE
115              
116             =head2 on_closed => CODE
117              
118             CODE references for event handlers.
119              
120             =head2 want_readready => BOOL
121              
122             =head2 want_writeready => BOOL
123              
124             If present, enable or disable read- or write-ready notification as per the
125             C and C methods.
126              
127             It is required that a matching C or C are
128             available for any handle that is provided; either passed as a callback CODE
129             reference or as an overridden the method. I.e. if only a C is
130             given, then C can be absent. If C is used as a
131             shortcut, then both read and write-ready callbacks or methods are required.
132              
133             If no IO handles are provided at construction time, the object is still
134             created but will not yet be fully-functional as a Handle. IO handles can be
135             assigned later using the C or C methods, or by
136             C. This may be useful when constructing an object to represent a
137             network connection, before the C has actually been performed yet.
138              
139             =cut
140              
141             sub configure
142             {
143 1119     1119 1 2678 my $self = shift;
144 1119         5760 my %params = @_;
145              
146 1119 100       3605 if( exists $params{on_read_ready} ) {
147 77         448 $self->{on_read_ready} = delete $params{on_read_ready};
148 77         262 undef $self->{cb_r};
149              
150 77 100       304 $self->_watch_read(0), $self->_watch_read(1) if $self->want_readready;
151             }
152              
153 1119 100       3621 if( exists $params{on_write_ready} ) {
154 17         44 $self->{on_write_ready} = delete $params{on_write_ready};
155 17         31 undef $self->{cb_w};
156              
157 17 100       40 $self->_watch_write(0), $self->_watch_write(1) if $self->want_writeready;
158             }
159              
160 1119 100       2866 if( exists $params{on_closed} ) {
161 16         60 $self->{on_closed} = delete $params{on_closed};
162             }
163              
164 1119 100 100     5180 if( defined $params{read_fileno} and defined $params{write_fileno} and
      66        
165             $params{read_fileno} == $params{write_fileno} ) {
166 1         5 $params{handle} = IO::Handle->new_from_fd( $params{read_fileno}, "r+" );
167              
168 1         105 delete $params{read_fileno};
169 1         2 delete $params{write_fileno};
170             }
171             else {
172             $params{read_handle} = IO::Handle->new_from_fd( delete $params{read_fileno}, "r" )
173 1118 100       2984 if defined $params{read_fileno};
174              
175             $params{write_handle} = IO::Handle->new_from_fd( delete $params{write_fileno}, "w" )
176 1118 100       3333 if defined $params{write_fileno};
177             }
178              
179             # 'handle' is a shortcut for setting read_ and write_
180 1119 100       2754 if( exists $params{handle} ) {
181 39         100 $params{read_handle} = $params{handle};
182 39         91 $params{write_handle} = $params{handle};
183 39         92 delete $params{handle};
184             }
185              
186 1119 100       2785 if( exists $params{read_handle} ) {
187 759         2768 my $read_handle = delete $params{read_handle};
188              
189 759 100       3547 if( defined $read_handle ) {
190 698 100       4175 if( !defined eval { $read_handle->fileno } ) {
  698         10863  
191 1         219 croak 'Expected that read_handle can ->fileno';
192             }
193              
194 697 50       15719 unless( $self->can_event( 'on_read_ready' ) ) {
195 0         0 croak 'Expected either a on_read_ready callback or an ->on_read_ready method';
196             }
197              
198 697         8287 my @layers = PerlIO::get_layers( $read_handle );
199 697 50 33     14517 if( grep m/^encoding\(/, @layers or grep m/^utf8$/, @layers ) {
200             # Only warn for now, because if it's UTF-8 by default but only
201             # passes ASCII then all will be well
202 0         0 carp "Constructing a ".ref($self)." with an encoding-enabled handle may not read correctly";
203             }
204              
205 697         2307 $self->{read_handle} = $read_handle;
206              
207 697         8811 $self->want_readready( defined $read_handle );
208             }
209             else {
210 61         869 $self->want_readready( 0 );
211              
212 61         131 undef $self->{read_handle};
213             }
214              
215             # In case someone has reopened the filehandles during an on_closed handler
216 758         4725 undef $self->{handle_closing};
217             }
218              
219 1118 100       2971 if( exists $params{write_handle} ) {
220 229         535 my $write_handle = delete $params{write_handle};
221              
222 229 100       762 if( defined $write_handle ) {
223 161 50       342 if( !defined eval { $write_handle->fileno } ) {
  161         671  
224 0         0 croak 'Expected that write_handle can ->fileno';
225             }
226              
227 161 50       1543 unless( $self->can_event( 'on_write_ready' ) ) {
228             # This used not to be fatal. Make it just a warning for now.
229 0         0 carp 'A write handle was provided but neither a on_write_ready callback nor an ->on_write_ready method were. Perhaps you mean \'read_handle\' instead?';
230             }
231              
232 161         605 $self->{write_handle} = $write_handle;
233             }
234             else {
235 68         195 $self->want_writeready( 0 );
236              
237 68         215 undef $self->{write_handle};
238             }
239              
240             # In case someone has reopened the filehandles during an on_closed handler
241 229         460 undef $self->{handle_closing};
242             }
243              
244 1118 50       2449 if( exists $params{want_readready} ) {
245 0         0 $self->want_readready( delete $params{want_readready} );
246             }
247              
248 1118 100       2469 if( exists $params{want_writeready} ) {
249 3         11 $self->want_writeready( delete $params{want_writeready} );
250             }
251              
252 1118         6125 $self->SUPER::configure( %params );
253             }
254              
255             # We'll be calling these any of three times
256             # adding to/removing from loop
257             # caller en/disables readiness checking
258             # changing filehandle
259              
260             sub _watch_read
261             {
262 2557     2557   4382 my $self = shift;
263 2557         5638 my ( $want ) = @_;
264              
265 2557 100       10698 my $loop = $self->loop or return;
266 1815 100       4187 my $fh = $self->read_handle or return;
267              
268 1241 100       3209 if( $want ) {
269 672   66     9609 $self->{cb_r} ||= $self->make_event_cb( 'on_read_ready' );
270              
271             $loop->watch_io(
272             handle => $fh,
273             on_read_ready => $self->{cb_r},
274 672         8225 );
275             }
276             else {
277 569         3228 $loop->unwatch_io(
278             handle => $fh,
279             on_read_ready => 1,
280             );
281             }
282             }
283              
284             sub _watch_write
285             {
286 803     803   1551 my $self = shift;
287 803         1639 my ( $want ) = @_;
288              
289 803 100       2015 my $loop = $self->loop or return;
290 799 100       2105 my $fh = $self->write_handle or return;
291              
292 173 100       441 if( $want ) {
293 73   66     727 $self->{cb_w} ||= $self->make_event_cb( 'on_write_ready' );
294              
295             $loop->watch_io(
296             handle => $fh,
297             on_write_ready => $self->{cb_w},
298 73         343 );
299             }
300             else {
301 100         556 $loop->unwatch_io(
302             handle => $fh,
303             on_write_ready => 1,
304             );
305             }
306             }
307              
308             sub _add_to_loop
309             {
310 791     791   1781 my $self = shift;
311 791         1645 my ( $loop ) = @_;
312              
313 791 100       2075 $self->_watch_read(1) if $self->want_readready;
314 791 100       4618 $self->_watch_write(1) if $self->want_writeready;
315             }
316              
317             sub _remove_from_loop
318             {
319 674     674   1233 my $self = shift;
320 674         1418 my ( $loop ) = @_;
321              
322 674         2043 $self->_watch_read(0);
323 674         2379 $self->_watch_write(0);
324             }
325              
326             sub notifier_name
327             {
328 35     35 1 1564 my $self = shift;
329              
330 35         91 my @parts;
331              
332 35 100       192 if( length( my $name = $self->SUPER::notifier_name ) ) {
333 30         94 push @parts, $name;
334             }
335              
336 35         281 my $r = $self->read_fileno;
337 35         148 my $w = $self->write_fileno;
338              
339 35 100 100     368 if( defined $r and defined $w and $r == $w ) {
    50 66        
    100 66        
    100          
340 2         9 push @parts, "rw=$r";
341             }
342             elsif( defined $r and defined $w ) {
343 0         0 push @parts, "r=$r,w=$w";
344             }
345             elsif( defined $r ) {
346 1         4 push @parts, "r=$r";
347             }
348             elsif( defined $w ) {
349 1         5 push @parts, "w=$w";
350             }
351              
352 35         330 return join ",", @parts;
353             }
354              
355             =head1 METHODS
356              
357             The following methods documented with a trailing call to C<< ->get >> return
358             L instances.
359              
360             =cut
361              
362             =head2 set_handle
363              
364             $handle->set_handles( %params )
365              
366             Sets new reading or writing filehandles. Equivalent to calling the
367             C method with the same parameters.
368              
369             =cut
370              
371             sub set_handles
372             {
373 0     0 0 0 my $self = shift;
374 0         0 my %params = @_;
375              
376             $self->configure(
377             exists $params{read_handle} ? ( read_handle => $params{read_handle} ) : (),
378 0 0       0 exists $params{write_handle} ? ( write_handle => $params{write_handle} ) : (),
    0          
379             );
380             }
381              
382             =head2 set_handle
383              
384             $handle->set_handle( $fh )
385              
386             Shortcut for
387              
388             $handle->configure( handle => $fh )
389              
390             =cut
391              
392             sub set_handle
393             {
394 18     18 1 479 my $self = shift;
395 18         44 my ( $fh ) = @_;
396              
397 18         64 $self->configure( handle => $fh );
398             }
399              
400             =head2 close
401              
402             $handle->close
403              
404             This method calls C on the underlying IO handles. This method will then
405             remove the handle from its containing loop.
406              
407             =cut
408              
409             sub close
410             {
411 646     646 1 1624 my $self = shift;
412              
413             # Prevent infinite loops if there's two crosslinked handles
414 646 100       2129 return if $self->{handle_closing};
415 594         1407 $self->{handle_closing} = 1;
416              
417 594         2333 $self->want_readready( 0 );
418 594         2058 $self->want_writeready( 0 );
419              
420 594         1510 my $read_handle = delete $self->{read_handle};
421 594 100       3363 $read_handle->close if defined $read_handle;
422              
423 594         15073 my $write_handle = delete $self->{write_handle};
424 594 100       2129 $write_handle->close if defined $write_handle;
425              
426 594         5196 $self->_closed;
427             }
428              
429             sub _closed
430             {
431 611     611   1234 my $self = shift;
432              
433 611         2442 $self->maybe_invoke_event( on_closed => );
434 611 100       2164 if( $self->{close_futures} ) {
435 173         428 $_->done for @{ $self->{close_futures} };
  173         1935  
436             }
437 611         21204 $self->remove_from_parent;
438             }
439              
440             =head2 close_read
441              
442             =head2 close_write
443              
444             $handle->close_read
445              
446             $handle->close_write
447              
448             Closes the underlying read or write handle, and deconfigures it from the
449             object. Neither of these methods will invoke the C event, nor
450             remove the object from the Loop if there is still one open handle in the
451             object. Only when both handles are closed, will C be fired, and the
452             object removed.
453              
454             =cut
455              
456             sub close_read
457             {
458 2     2 1 7 my $self = shift;
459              
460 2         7 $self->want_readready( 0 );
461              
462 2         4 my $read_handle = delete $self->{read_handle};
463 2 50       10 $read_handle->close if defined $read_handle;
464              
465 2 100       71 $self->_closed if !$self->{write_handle};
466             }
467              
468             sub close_write
469             {
470 20     20 1 126 my $self = shift;
471              
472 20         226 $self->want_writeready( 0 );
473              
474 20         167 my $write_handle = delete $self->{write_handle};
475 20 50       208 $write_handle->close if defined $write_handle;
476              
477 20 100       683 $self->_closed if !$self->{read_handle};
478             }
479              
480             =head2 new_close_future
481              
482             $handle->new_close_future->get
483              
484             Returns a new L object which will become done when the
485             handle is closed. Cancelling the C<$future> will remove this notification
486             ability but will not otherwise affect the C<$handle>.
487              
488             =cut
489              
490             sub new_close_future
491             {
492 199     199 1 458 my $self = shift;
493              
494 199         343 push @{ $self->{close_futures} }, my $future = $self->loop->new_future;
  199         851  
495             $future->on_cancel(
496             $self->_capture_weakself( sub {
497 0 0   0   0 my $self = shift or return;
498 0         0 my $future = shift;
499              
500 0 0       0 @{ $self->{close_futures} } = grep { $_ and $_ != $future } @{ $self->{close_futures} };
  0         0  
  0         0  
  0         0  
501             })
502 199         1583 );
503              
504 199         5793 return $future;
505             }
506              
507             =head2 read_handle
508              
509             =head2 write_handle
510              
511             $handle = $handle->read_handle
512              
513             $handle = $handle->write_handle
514              
515             These accessors return the underlying IO handles.
516              
517             =cut
518              
519             sub read_handle
520             {
521 4365     4365 1 14451 my $self = shift;
522 4365         14124 return $self->{read_handle};
523             }
524              
525             sub write_handle
526             {
527 1648     1648 1 4175 my $self = shift;
528 1648         6499 return $self->{write_handle};
529             }
530              
531             =head2 read_fileno
532              
533             =head2 write_fileno
534              
535             $fileno = $handle->read_fileno
536              
537             $fileno = $handle->write_fileno
538              
539             These accessors return the file descriptor numbers of the underlying IO
540             handles.
541              
542             =cut
543              
544             sub read_fileno
545             {
546 36     36 1 104 my $self = shift;
547 36 100       121 my $handle = $self->read_handle or return undef;
548 4         14 return $handle->fileno;
549             }
550              
551             sub write_fileno
552             {
553 36     36 1 73 my $self = shift;
554 36 100       105 my $handle = $self->write_handle or return undef;
555 4         12 return $handle->fileno;
556             }
557              
558             =head2 want_readready
559              
560             =head2 want_writeready
561              
562             $value = $handle->want_readready
563              
564             $oldvalue = $handle->want_readready( $newvalue )
565              
566             $value = $handle->want_writeready
567              
568             $oldvalue = $handle->want_writeready( $newvalue )
569              
570             These are the accessor for the C and C
571             properties, which define whether the object is interested in knowing about
572             read- or write-readiness on the underlying file handle.
573              
574             =cut
575              
576             sub want_readready
577             {
578 2224     2224 1 4180 my $self = shift;
579 2224 100       5476 if( @_ ) {
580 1355         13565 my ( $new ) = @_;
581              
582 1355         2905 $new = !!$new;
583 1355 100       3815 return $new if !$new == !$self->{want_readready}; # compare bools
584              
585 1228 100       3346 if( $new ) {
586 695 50       3406 defined $self->read_handle or
587             croak 'Cannot want_readready in a Handle with no read_handle';
588             }
589              
590 1228         3069 my $old = $self->{want_readready};
591 1228         5268 $self->{want_readready} = $new;
592              
593 1228         7123 $self->_watch_read( $new );
594              
595 1228         3488 return $old;
596             }
597             else {
598 869         4020 return $self->{want_readready};
599             }
600             }
601              
602             sub want_writeready
603             {
604 1721     1721 1 5480 my $self = shift;
605 1721 100       4234 if( @_ ) {
606 901         1819 my ( $new ) = @_;
607              
608 901         2213 $new = !!$new;
609 901 100       2960 return $new if !$new == !$self->{want_writeready}; # compare bools
610              
611 131 100       410 if( $new ) {
612 73 100       178 defined $self->write_handle or
613             croak 'Cannot want_writeready in a Handle with no write_handle';
614             }
615              
616 130         429 my $old = $self->{want_writeready};
617 130         492 $self->{want_writeready} = $new;
618              
619 130         670 $self->_watch_write( $new );
620              
621 130         415 return $old;
622             }
623             else {
624 820         3336 return $self->{want_writeready};
625             }
626             }
627              
628             =head2 socket
629              
630             $handle->socket( $ai )
631              
632             Convenient shortcut to creating a socket handle, as given by an addrinfo
633             structure, and setting it as the read and write handle for the object.
634              
635             C<$ai> may be either a C or C reference of the same form as given
636             to L's C method.
637              
638             This method returns nothing if it succeeds, or throws an exception if it
639             fails.
640              
641             =cut
642              
643             sub socket
644             {
645 3     3 1 10 my $self = shift;
646 3         7 my ( $ai ) = @_;
647              
648             # TODO: Something about closing the old one?
649              
650 3         36 my ( $family, $socktype, $protocol ) = IO::Async::OS->extract_addrinfo( $ai );
651              
652 3         37 my $sock = IO::Async::OS->socket( $family, $socktype, $protocol );
653 3         552 $sock->blocking( 0 );
654              
655 3         61 $self->set_handle( $sock );
656             }
657              
658             =head2 bind
659              
660             $handle = $handle->bind( %args )->get
661              
662             Performs a C resolver operation with the C flag set,
663             and then attempts to bind a socket handle of any of the return values.
664              
665             =head2 bind (1 argument)
666              
667             $handle = $handle->bind( $ai )->get
668              
669             When invoked with a single argument, this method is a convenient shortcut to
670             creating a socket handle and Cing it to the address as given by an
671             addrinfo structure, and setting it as the read and write handle for the
672             object.
673              
674             C<$ai> may be either a C or C reference of the same form as given
675             to L's C method.
676              
677             The returned future returns the handle object itself for convenience.
678              
679             =cut
680              
681             sub bind
682             {
683 3     3 1 604 my $self = shift;
684              
685 3 100       19 if( @_ == 1 ) {
686 2         6 my ( $ai ) = @_;
687              
688 2         8 $self->socket( $ai );
689 2         15 my $addr = ( IO::Async::OS->extract_addrinfo( $ai ) )[3];
690              
691 2 50       8 $self->read_handle->bind( $addr ) or
692             return Future->fail( "Cannot bind - $!", bind => $self->read_handle, $addr, $! );
693              
694 2         68 return Future->done( $self );
695             }
696              
697             $self->loop->resolver->getaddrinfo( passive => 1, @_ )->then( sub {
698 1     1   90 my @addrs = @_;
699              
700             try_repeat {
701 1         84 my $ai = shift;
702              
703 1         6 $self->bind( $ai );
704             } foreach => \@addrs,
705 1         11 until => sub { shift->is_done };
  1         66  
706 1         5 });
707             }
708              
709             =head2 connect
710              
711             $handle = $handle->connect( %args )->get
712              
713             A convenient wrapper for calling the C method on the underlying
714             L object.
715              
716             =cut
717              
718             sub connect
719             {
720 2     2 1 82 my $self = shift;
721 2         8 my %args = @_;
722              
723 2 50       7 my $loop = $self->loop or croak "Cannot ->connect a Handle that is not in a Loop";
724              
725             $self->debug_printf( "CONNECT " . join( ", ",
726             # These args should be stringy
727 2 100       7 ( map { defined $args{$_} ? "$_=$args{$_}" : () } qw( host service family socktype protocol local_host local_service ) )
  14         43  
728             ) );
729              
730 2         13 return $self->loop->connect( %args, handle => $self );
731             }
732              
733             =head1 SEE ALSO
734              
735             =over 4
736              
737             =item *
738              
739             L - Supply object methods for I/O handles
740              
741             =back
742              
743             =head1 AUTHOR
744              
745             Paul Evans
746              
747             =cut
748              
749             0x55AA;