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