Commit | Line | Data |
12fb4a80 |
1 | package Object::Remote::ReadChannel; |
2 | |
3 | use CPS::Future; |
4 | use Scalar::Util qw(weaken); |
5d59cb98 |
5 | use Object::Remote::Logging qw(:log); |
12fb4a80 |
6 | use Moo; |
7 | |
8 | has 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 | |
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) = @_; |
5d59cb98 |
32 | log_trace { "Preparing to read data" }; |
12fb4a80 |
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) { |
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 | } |
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 | ); |
48 | $self->on_close_call->($err); |
49 | } |
50 | } |
51 | |
52 | sub DEMOLISH { |
53 | my ($self, $gd) = @_; |
54 | return if $gd; |
5d59cb98 |
55 | log_trace { "read channel is being demolished" }; |
12fb4a80 |
56 | Object::Remote->current_loop |
57 | ->unwatch_io( |
58 | handle => $self->fh, |
59 | on_read_ready => 1 |
60 | ); |
61 | } |
62 | |
63 | 1; |