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   4859 use strict;
  76         169  
  76         2774  
9 76     76   423 use warnings;
  76         147  
  76         3256  
10 76     76   422 use base qw( IO::Async::Notifier );
  76         167  
  76         29128  
11              
12             our $VERSION = '0.801';
13              
14 76     76   1172 use Carp;
  76         176  
  76         5299  
15              
16 76     76   7828 use IO::Handle; # give methods to bare IO handles
  76         78599  
  76         3465  
17              
18 76     76   545 use Future;
  76         184  
  76         2191  
19 76     76   42011 use Future::Utils qw( try_repeat );
  76         182207  
  76         5722  
20              
21 76     76   1977 use IO::Async::OS;
  76         200  
  76         183888  
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 3356 my $self = shift;
144 1121         5797 my %params = @_;
145              
146 1121 100       4409 if( exists $params{on_read_ready} ) {
147 79         480 $self->{on_read_ready} = delete $params{on_read_ready};
148 79         222 undef $self->{cb_r};
149              
150 79 100       290 $self->_watch_read(0), $self->_watch_read(1) if $self->want_readready;
151             }
152              
153 1121 100       3567 if( exists $params{on_write_ready} ) {
154 17         47 $self->{on_write_ready} = delete $params{on_write_ready};
155 17         35 undef $self->{cb_w};
156              
157 17 100       45 $self->_watch_write(0), $self->_watch_write(1) if $self->want_writeready;
158             }
159              
160 1121 100       2547 if( exists $params{on_closed} ) {
161 16         46 $self->{on_closed} = delete $params{on_closed};
162             }
163              
164 1121 100 100     4659 if( defined $params{read_fileno} and defined $params{write_fileno} and
      66        
165             $params{read_fileno} == $params{write_fileno} ) {
166 1         6 $params{handle} = IO::Handle->new_from_fd( $params{read_fileno}, "r+" );
167              
168 1         75 delete $params{read_fileno};
169 1         3 delete $params{write_fileno};
170             }
171             else {
172             $params{read_handle} = IO::Handle->new_from_fd( delete $params{read_fileno}, "r" )
173 1120 100       2588 if defined $params{read_fileno};
174              
175             $params{write_handle} = IO::Handle->new_from_fd( delete $params{write_fileno}, "w" )
176 1120 100       3215 if defined $params{write_fileno};
177             }
178              
179             # 'handle' is a shortcut for setting read_ and write_
180 1121 100       3079 if( exists $params{handle} ) {
181 39         105 $params{read_handle} = $params{handle};
182 39         93 $params{write_handle} = $params{handle};
183 39         91 delete $params{handle};
184             }
185              
186 1121 100       3516 if( exists $params{read_handle} ) {
187 761         3245 my $read_handle = delete $params{read_handle};
188              
189 761 100       2644 if( defined $read_handle ) {
190 700 100       4005 if( !defined eval { $read_handle->fileno } ) {
  700         10871  
191 1         220 croak 'Expected that read_handle can ->fileno';
192             }
193              
194 699 50       14126 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         7271 my @layers = PerlIO::get_layers( $read_handle );
199 699 50 33     14085 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         1978 $self->{read_handle} = $read_handle;
206              
207 699         7439 $self->want_readready( defined $read_handle );
208             }
209             else {
210 61         229 $self->want_readready( 0 );
211              
212 61         114 undef $self->{read_handle};
213             }
214              
215             # In case someone has reopened the filehandles during an on_closed handler
216 760         4140 undef $self->{handle_closing};
217             }
218              
219 1120 100       3125 if( exists $params{write_handle} ) {
220 229         514 my $write_handle = delete $params{write_handle};
221              
222 229 100       1114 if( defined $write_handle ) {
223 161 50       398 if( !defined eval { $write_handle->fileno } ) {
  161         643  
224 0         0 croak 'Expected that write_handle can ->fileno';
225             }
226              
227 161 50       1846 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         571 $self->{write_handle} = $write_handle;
233             }
234             else {
235 68         207 $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         466 undef $self->{handle_closing};
242             }
243              
244 1120 50       2545 if( exists $params{want_readready} ) {
245 0         0 $self->want_readready( delete $params{want_readready} );
246             }
247              
248 1120 100       7932 if( exists $params{want_writeready} ) {
249 3         10 $self->want_writeready( delete $params{want_writeready} );
250             }
251              
252 1120         5992 $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   4023 my $self = shift;
263 2561         4534 my ( $want ) = @_;
264              
265 2561 100       8346 my $loop = $self->loop or return;
266 1817 100       4415 my $fh = $self->read_handle or return;
267              
268 1243 100       3111 if( $want ) {
269 674   66     9452 $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         8416 );
275             }
276             else {
277 569         3033 $loop->unwatch_io(
278             handle => $fh,
279             on_read_ready => 1,
280             );
281             }
282             }
283              
284             sub _watch_write
285             {
286 803     803   1632 my $self = shift;
287 803         1646 my ( $want ) = @_;
288              
289 803 100       2115 my $loop = $self->loop or return;
290 799 100       2265 my $fh = $self->write_handle or return;
291              
292 173 100       456 if( $want ) {
293 73   66     771 $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         333 );
299             }
300             else {
301 100         728 $loop->unwatch_io(
302             handle => $fh,
303             on_write_ready => 1,
304             );
305             }
306             }
307              
308             sub _add_to_loop
309             {
310 793     793   1712 my $self = shift;
311 793         1505 my ( $loop ) = @_;
312              
313 793 100       2092 $self->_watch_read(1) if $self->want_readready;
314 793 100       3383 $self->_watch_write(1) if $self->want_writeready;
315             }
316              
317             sub _remove_from_loop
318             {
319 674     674   1276 my $self = shift;
320 674         1394 my ( $loop ) = @_;
321              
322 674         2022 $self->_watch_read(0);
323 674         2910 $self->_watch_write(0);
324             }
325              
326             sub notifier_name
327             {
328 35     35 1 1578 my $self = shift;
329              
330 35         93 my @parts;
331              
332 35 100       286 if( length( my $name = $self->SUPER::notifier_name ) ) {
333 30         82 push @parts, $name;
334             }
335              
336 35         162 my $r = $self->read_fileno;
337 35         143 my $w = $self->write_fileno;
338              
339 35 100 100     371 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         5 push @parts, "r=$r";
347             }
348             elsif( defined $w ) {
349 1         4 push @parts, "w=$w";
350             }
351              
352 35         289 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 415 my $self = shift;
395 18         42 my ( $fh ) = @_;
396              
397 18         77 $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 1333 my $self = shift;
412              
413             # Prevent infinite loops if there's two crosslinked handles
414 646 100       1960 return if $self->{handle_closing};
415 594         1287 $self->{handle_closing} = 1;
416              
417 594         2033 $self->want_readready( 0 );
418 594         2134 $self->want_writeready( 0 );
419              
420 594         1394 my $read_handle = delete $self->{read_handle};
421 594 100       2955 $read_handle->close if defined $read_handle;
422              
423 594         14985 my $write_handle = delete $self->{write_handle};
424 594 100       1975 $write_handle->close if defined $write_handle;
425              
426 594         5145 $self->_closed;
427             }
428              
429             sub _closed
430             {
431 611     611   1246 my $self = shift;
432              
433 611         2495 $self->maybe_invoke_event( on_closed => );
434 611 100       2306 if( $self->{close_futures} ) {
435 173         411 $_->done for @{ $self->{close_futures} };
  173         1848  
436             }
437 611         20163 $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 10 my $self = shift;
459              
460 2         6 $self->want_readready( 0 );
461              
462 2         6 my $read_handle = delete $self->{read_handle};
463 2 50       24 $read_handle->close if defined $read_handle;
464              
465 2 100       78 $self->_closed if !$self->{write_handle};
466             }
467              
468             sub close_write
469             {
470 20     20 1 104 my $self = shift;
471              
472 20         167 $self->want_writeready( 0 );
473              
474 20         219 my $write_handle = delete $self->{write_handle};
475 20 50       360 $write_handle->close if defined $write_handle;
476              
477 20 100       612 $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         349 push @{ $self->{close_futures} }, my $future = $self->loop->new_future;
  199         828  
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         1533 );
503              
504 199         4749 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 13746 my $self = shift;
522 4369         14147 return $self->{read_handle};
523             }
524              
525             sub write_handle
526             {
527 1648     1648 1 4017 my $self = shift;
528 1648         6596 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 83 my $self = shift;
547 36 100       124 my $handle = $self->read_handle or return undef;
548 4         13 return $handle->fileno;
549             }
550              
551             sub write_fileno
552             {
553 36     36 1 70 my $self = shift;
554 36 100       280 my $handle = $self->write_handle or return undef;
555 4         11 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 4124 my $self = shift;
579 2230 100       5360 if( @_ ) {
580 1357         5116 my ( $new ) = @_;
581              
582 1357         2798 $new = !!$new;
583 1357 100       3788 return $new if !$new == !$self->{want_readready}; # compare bools
584              
585 1230 100       3116 if( $new ) {
586 697 50       3427 defined $self->read_handle or
587             croak 'Cannot want_readready in a Handle with no read_handle';
588             }
589              
590 1230         2573 my $old = $self->{want_readready};
591 1230         4908 $self->{want_readready} = $new;
592              
593 1230         5627 $self->_watch_read( $new );
594              
595 1230         3347 return $old;
596             }
597             else {
598 873         4316 return $self->{want_readready};
599             }
600             }
601              
602             sub want_writeready
603             {
604 1723     1723 1 4566 my $self = shift;
605 1723 100       4553 if( @_ ) {
606 901         1926 my ( $new ) = @_;
607              
608 901         2344 $new = !!$new;
609 901 100       3047 return $new if !$new == !$self->{want_writeready}; # compare bools
610              
611 131 100       562 if( $new ) {
612 73 100       213 defined $self->write_handle or
613             croak 'Cannot want_writeready in a Handle with no write_handle';
614             }
615              
616 130         259 my $old = $self->{want_writeready};
617 130         409 $self->{want_writeready} = $new;
618              
619 130         922 $self->_watch_write( $new );
620              
621 130         487 return $old;
622             }
623             else {
624 822         3219 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         6 my ( $ai ) = @_;
647              
648             # TODO: Something about closing the old one?
649              
650 3         38 my ( $family, $socktype, $protocol ) = IO::Async::OS->extract_addrinfo( $ai );
651              
652 3         140 my $sock = IO::Async::OS->socket( $family, $socktype, $protocol );
653 3         548 $sock->blocking( 0 );
654              
655 3         73 $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 630 my $self = shift;
684              
685 3 100       15 if( @_ == 1 ) {
686 2         6 my ( $ai ) = @_;
687              
688 2         10 $self->socket( $ai );
689 2         18 my $addr = ( IO::Async::OS->extract_addrinfo( $ai ) )[3];
690              
691 2 50       11 $self->read_handle->bind( $addr ) or
692             return Future->fail( "Cannot bind - $!", bind => $self->read_handle, $addr, $! );
693              
694 2         80 return Future->done( $self );
695             }
696              
697             $self->loop->resolver->getaddrinfo( passive => 1, @_ )->then( sub {
698 1     1   98 my @addrs = @_;
699              
700             try_repeat {
701 1         86 my $ai = shift;
702              
703 1         7 $self->bind( $ai );
704             } foreach => \@addrs,
705 1         11 until => sub { shift->is_done };
  1         56  
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 87 my $self = shift;
721 2         9 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       8 ( map { defined $args{$_} ? "$_=$args{$_}" : () } qw( host service family socktype protocol local_host local_service ) )
  14         54  
728             ) );
729              
730 2         7 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;