revise log router api to match log::contextual router api change
[scpubgit/Object-Remote.git] / lib / Object / Remote / ReadChannel.pm
CommitLineData
12fb4a80 1package Object::Remote::ReadChannel;
2
3use CPS::Future;
b7a853b3 4use Scalar::Util qw(weaken openhandle);
9031635d 5use Object::Remote::Logging qw(:log :dlog);
12fb4a80 6use Moo;
7
8has fh => (
9 is => 'ro', required => 1,
10 trigger => sub {
11 my ($self, $fh) = @_;
12 weaken($self);
5d59cb98 13 log_trace { "Watching filehandle via trigger on 'fh' attribute in Object::Remote::ReadChannel" };
12fb4a80 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
22has on_close_call => (
23 is => 'rw', default => sub { sub {} },
24);
25
26has on_line_call => (is => 'rw');
27
28has _receive_data_buffer => (is => 'ro', default => sub { my $x = ''; \$x });
29
30sub _receive_data_from {
31 my ($self, $fh) = @_;
9031635d 32 Dlog_trace { "Preparing to read data from $_" } $fh;
12fb4a80 33 my $rb = $self->_receive_data_buffer;
9031635d 34 my $len = sysread($fh, $$rb, 32768, length($$rb));
c824fdf3 35 my $err = defined($len) ? 'eof' : ": $!";
12fb4a80 36 if (defined($len) and $len > 0) {
5d59cb98 37 log_trace { "Read $len bytes of data" };
12fb4a80 38 while (my $cb = $self->on_line_call and $$rb =~ s/^(.*)\n//) {
39 $cb->(my $line = $1);
40 }
353556c4 41 } else {
5d59cb98 42 log_trace { "Got EOF or error, this read channel is done" };
12fb4a80 43 Object::Remote->current_loop
44 ->unwatch_io(
45 handle => $self->fh,
46 on_read_ready => 1
47 );
f8080c1c 48 log_trace { "Invoking on_close_call() for dead read channel" };
12fb4a80 49 $self->on_close_call->($err);
50 }
51}
52
53sub DEMOLISH {
54 my ($self, $gd) = @_;
55 return if $gd;
5d59cb98 56 log_trace { "read channel is being demolished" };
b7a853b3 57
12fb4a80 58 Object::Remote->current_loop
59 ->unwatch_io(
60 handle => $self->fh,
61 on_read_ready => 1
62 );
b7a853b3 63
64
12fb4a80 65}
66
671;