more log lines - found deadlock where controller blocks on read seemingly outside...
[scpubgit/Object-Remote.git] / lib / Object / Remote / ReadChannel.pm
1 package Object::Remote::ReadChannel;
2
3 use CPS::Future;
4 use Scalar::Util qw(weaken);
5 use Object::Remote::Logging qw(:log);
6 use Moo;
7
8 has fh => (
9   is => 'ro', required => 1,
10   trigger => sub {
11     my ($self, $fh) = @_;
12     weaken($self);
13     log_trace { "Watching filehandle via trigger on 'fh' attribute in Object::Remote::ReadChannel" };
14     Object::Remote->current_loop
15                   ->watch_io(
16                       handle => $fh,
17                       on_read_ready => sub { $self->_receive_data_from($fh) }
18                     );
19   },
20 );
21
22 has on_close_call => (
23   is => 'rw', default => sub { sub {} },
24 );
25
26 has on_line_call => (is => 'rw');
27
28 has _receive_data_buffer => (is => 'ro', default => sub { my $x = ''; \$x });
29
30 sub _receive_data_from {
31   my ($self, $fh) = @_;
32   log_trace { "Preparing to read data" };
33   my $rb = $self->_receive_data_buffer;
34   my $len = sysread($fh, $$rb, 1024, length($$rb));
35   my $err = defined($len) ? '' : ": $!";
36   if (defined($len) and $len > 0) {
37     log_trace { "Read $len bytes of data" };
38     while (my $cb = $self->on_line_call and $$rb =~ s/^(.*)\n//) {
39       $cb->(my $line = $1);
40     }
41   } else {
42     log_trace { "Got EOF or error, this read channel is done" };
43     Object::Remote->current_loop
44                   ->unwatch_io(
45                       handle => $self->fh,
46                       on_read_ready => 1
47                     );
48     $self->on_close_call->($err);
49   }
50 }
51
52 sub DEMOLISH {
53   my ($self, $gd) = @_;
54   return if $gd;
55   log_trace { "read channel is being demolished" };
56   Object::Remote->current_loop
57                 ->unwatch_io(
58                     handle => $self->fh,
59                     on_read_ready => 1
60                   );
61 }
62
63 1;