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