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 76     76   3493 use strict;
  76         148  
  76         2336  
9 76     76   369 use warnings;
  76         119  
  76         2637  
10 76     76   354 use base qw( IO::Async::Notifier );
  76         118  
  76         23463  
11              
12             our $VERSION = '0.802';
13              
14 76     76   634 use Carp;
  76         137  
  76         4378  
15              
16 76     76   6278 use IO::Handle; # give methods to bare IO handles
  76         64025  
  76         2795  
17              
18 76     76   434 use Future;
  76         172  
  76         2306  
19 76     76   33654 use Future::Utils qw( try_repeat );
  76         158006  
  76         4689  
20              
21 76     76   1361 use IO::Async::OS;
  76         149  
  76         150922  
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 1121     1121 1 2173 my $self = shift;
144 1121         4891 my %params = @_;
145              
146 1121 100       3610 if( exists $params{on_read_ready} ) {
147 79         401 $self->{on_read_ready} = delete $params{on_read_ready};
148 79         195 undef $self->{cb_r};
149              
150 79 100       307 $self->_watch_read(0), $self->_watch_read(1) if $self->want_readready;
151             }
152              
153 1121 100       2486 if( exists $params{on_write_ready} ) {
154 17         31 $self->{on_write_ready} = delete $params{on_write_ready};
155 17         28 undef $self->{cb_w};
156              
157 17 100       42 $self->_watch_write(0), $self->_watch_write(1) if $self->want_writeready;
158             }
159              
160 1121 100       2320 if( exists $params{on_closed} ) {
161 16         36 $self->{on_closed} = delete $params{on_closed};
162             }
163              
164 1121 100 100     9935 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         61 delete $params{read_fileno};
169 1         1 delete $params{write_fileno};
170             }
171             else {
172             $params{read_handle} = IO::Handle->new_from_fd( delete $params{read_fileno}, "r" )
173 1120 100       2279 if defined $params{read_fileno};
174              
175             $params{write_handle} = IO::Handle->new_from_fd( delete $params{write_fileno}, "w" )
176 1120 100       2470 if defined $params{write_fileno};
177             }
178              
179             # 'handle' is a shortcut for setting read_ and write_
180 1121 100       2326 if( exists $params{handle} ) {
181 39         79 $params{read_handle} = $params{handle};
182 39         74 $params{write_handle} = $params{handle};
183 39         61 delete $params{handle};
184             }
185              
186 1121 100       2414 if( exists $params{read_handle} ) {
187 761         2731 my $read_handle = delete $params{read_handle};
188              
189 761 100       2215 if( defined $read_handle ) {
190 700 100       3323 if( !defined eval { $read_handle->fileno } ) {
  700         9358  
191 1         175 croak 'Expected that read_handle can ->fileno';
192             }
193              
194 699 50       11171 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 699         6267 my @layers = PerlIO::get_layers( $read_handle );
199 699 50 33     12342 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 699         1813 $self->{read_handle} = $read_handle;
206              
207 699         7379 $self->want_readready( defined $read_handle );
208             }
209             else {
210 61         174 $self->want_readready( 0 );
211              
212 61         81 undef $self->{read_handle};
213             }
214              
215             # In case someone has reopened the filehandles during an on_closed handler
216 760         2975 undef $self->{handle_closing};
217             }
218              
219 1120 100       2425 if( exists $params{write_handle} ) {
220 229         442 my $write_handle = delete $params{write_handle};
221              
222 229 100       766 if( defined $write_handle ) {
223 161 50       284 if( !defined eval { $write_handle->fileno } ) {
  161         533  
224 0         0 croak 'Expected that write_handle can ->fileno';
225             }
226              
227 161 50       1245 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         503 $self->{write_handle} = $write_handle;
233             }
234             else {
235 68         169 $self->want_writeready( 0 );
236              
237 68         236 undef $self->{write_handle};
238             }
239              
240             # In case someone has reopened the filehandles during an on_closed handler
241 229         518 undef $self->{handle_closing};
242             }
243              
244 1120 50       2076 if( exists $params{want_readready} ) {
245 0         0 $self->want_readready( delete $params{want_readready} );
246             }
247              
248 1120 100       2093 if( exists $params{want_writeready} ) {
249 3         10 $self->want_writeready( delete $params{want_writeready} );
250             }
251              
252 1120         5102 $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 2561     2561   3881 my $self = shift;
263 2561         4055 my ( $want ) = @_;
264              
265 2561 100       8058 my $loop = $self->loop or return;
266 1817 100       3564 my $fh = $self->read_handle or return;
267              
268 1243 100       2661 if( $want ) {
269 674   66     9612 $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 674         6879 );
275             }
276             else {
277 569         2106 $loop->unwatch_io(
278             handle => $fh,
279             on_read_ready => 1,
280             );
281             }
282             }
283              
284             sub _watch_write
285             {
286 803     803   1444 my $self = shift;
287 803         1379 my ( $want ) = @_;
288              
289 803 100       1679 my $loop = $self->loop or return;
290 799 100       2188 my $fh = $self->write_handle or return;
291              
292 173 100       408 if( $want ) {
293 73   66     585 $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         314 );
299             }
300             else {
301 100         375 $loop->unwatch_io(
302             handle => $fh,
303             on_write_ready => 1,
304             );
305             }
306             }
307              
308             sub _add_to_loop
309             {
310 793     793   1355 my $self = shift;
311 793         1264 my ( $loop ) = @_;
312              
313 793 100       1756 $self->_watch_read(1) if $self->want_readready;
314 793 100       7695 $self->_watch_write(1) if $self->want_writeready;
315             }
316              
317             sub _remove_from_loop
318             {
319 674     674   989 my $self = shift;
320 674         1133 my ( $loop ) = @_;
321              
322 674         1724 $self->_watch_read(0);
323 674         2101 $self->_watch_write(0);
324             }
325              
326             sub notifier_name
327             {
328 35     35 1 1798 my $self = shift;
329              
330 35         71 my @parts;
331              
332 35 100       149 if( length( my $name = $self->SUPER::notifier_name ) ) {
333 30         79 push @parts, $name;
334             }
335              
336 35         143 my $r = $self->read_fileno;
337 35         139 my $w = $self->write_fileno;
338              
339 35 100 100     377 if( defined $r and defined $w and $r == $w ) {
    50 66        
    100 66        
    100          
340 2         8 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         4 push @parts, "w=$w";
350             }
351              
352 35         312 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 369 my $self = shift;
395 18         34 my ( $fh ) = @_;
396              
397 18         61 $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 1258 my $self = shift;
412              
413             # Prevent infinite loops if there's two crosslinked handles
414 646 100       1709 return if $self->{handle_closing};
415 594         1056 $self->{handle_closing} = 1;
416              
417 594         1966 $self->want_readready( 0 );
418 594         1777 $self->want_writeready( 0 );
419              
420 594         1177 my $read_handle = delete $self->{read_handle};
421 594 100       2759 $read_handle->close if defined $read_handle;
422              
423 594         13198 my $write_handle = delete $self->{write_handle};
424 594 100       1875 $write_handle->close if defined $write_handle;
425              
426 594         4730 $self->_closed;
427             }
428              
429             sub _closed
430             {
431 611     611   1285 my $self = shift;
432              
433 611         2273 $self->maybe_invoke_event( on_closed => );
434 611 100       1898 if( $self->{close_futures} ) {
435 173         421 $_->done for @{ $self->{close_futures} };
  173         1625  
436             }
437 611         17790 $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 8 my $self = shift;
459              
460 2         5 $self->want_readready( 0 );
461              
462 2         3 my $read_handle = delete $self->{read_handle};
463 2 50       10 $read_handle->close if defined $read_handle;
464              
465 2 100       57 $self->_closed if !$self->{write_handle};
466             }
467              
468             sub close_write
469             {
470 20     20 1 146 my $self = shift;
471              
472 20         137 $self->want_writeready( 0 );
473              
474 20         156 my $write_handle = delete $self->{write_handle};
475 20 50       243 $write_handle->close if defined $write_handle;
476              
477 20 100       566 $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 381 my $self = shift;
493              
494 199         270 push @{ $self->{close_futures} }, my $future = $self->loop->new_future;
  199         793  
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         1267 );
503              
504 199         4161 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 4369     4369 1 12623 my $self = shift;
522 4369         12437 return $self->{read_handle};
523             }
524              
525             sub write_handle
526             {
527 1648     1648 1 3527 my $self = shift;
528 1648         5608 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 78 my $self = shift;
547 36 100       113 my $handle = $self->read_handle or return undef;
548 4         15 return $handle->fileno;
549             }
550              
551             sub write_fileno
552             {
553 36     36 1 79 my $self = shift;
554 36 100       102 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 2230     2230 1 3328 my $self = shift;
579 2230 100       4380 if( @_ ) {
580 1357         4126 my ( $new ) = @_;
581              
582 1357         2447 $new = !!$new;
583 1357 100       3545 return $new if !$new == !$self->{want_readready}; # compare bools
584              
585 1230 100       2339 if( $new ) {
586 697 50       3421 defined $self->read_handle or
587             croak 'Cannot want_readready in a Handle with no read_handle';
588             }
589              
590 1230         3033 my $old = $self->{want_readready};
591 1230         4316 $self->{want_readready} = $new;
592              
593 1230         5805 $self->_watch_read( $new );
594              
595 1230         2937 return $old;
596             }
597             else {
598 873         3659 return $self->{want_readready};
599             }
600             }
601              
602             sub want_writeready
603             {
604 1723     1723 1 21380 my $self = shift;
605 1723 100       3497 if( @_ ) {
606 901         1541 my ( $new ) = @_;
607              
608 901         2043 $new = !!$new;
609 901 100       2676 return $new if !$new == !$self->{want_writeready}; # compare bools
610              
611 131 100       327 if( $new ) {
612 73 100       223 defined $self->write_handle or
613             croak 'Cannot want_writeready in a Handle with no write_handle';
614             }
615              
616 130         325 my $old = $self->{want_writeready};
617 130         337 $self->{want_writeready} = $new;
618              
619 130         619 $self->_watch_write( $new );
620              
621 130         376 return $old;
622             }
623             else {
624 822         2992 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 12 my $self = shift;
646 3         9 my ( $ai ) = @_;
647              
648             # TODO: Something about closing the old one?
649              
650 3         35 my ( $family, $socktype, $protocol ) = IO::Async::OS->extract_addrinfo( $ai );
651              
652 3         20 my $sock = IO::Async::OS->socket( $family, $socktype, $protocol );
653 3         508 $sock->blocking( 0 );
654              
655 3         52 $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       11 if( @_ == 1 ) {
686 2         5 my ( $ai ) = @_;
687              
688 2         7 $self->socket( $ai );
689 2         13 my $addr = ( IO::Async::OS->extract_addrinfo( $ai ) )[3];
690              
691 2 50       61 $self->read_handle->bind( $addr ) or
692             return Future->fail( "Cannot bind - $!", bind => $self->read_handle, $addr, $! );
693              
694 2         69 return Future->done( $self );
695             }
696              
697             $self->loop->resolver->getaddrinfo( passive => 1, @_ )->then( sub {
698 1     1   89 my @addrs = @_;
699              
700             try_repeat {
701 1         77 my $ai = shift;
702              
703 1         4 $self->bind( $ai );
704             } foreach => \@addrs,
705 1         10 until => sub { shift->is_done };
  1         47  
706 1         4 });
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 68 my $self = shift;
721 2         7 my %args = @_;
722              
723 2 50       5 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       6 ( map { defined $args{$_} ? "$_=$args{$_}" : () } qw( host service family socktype protocol local_host local_service ) )
  14         44  
728             ) );
729              
730 2         5 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;