Commit | Line | Data |
12fb4a80 |
1 | package Object::Remote::ReadChannel; |
2 | |
3 | use CPS::Future; |
4 | use Scalar::Util qw(weaken); |
07105aca |
5 | use Object::Remote::Logging qw(:log :dlog); |
90a3a7f2 |
6 | use POSIX; |
12fb4a80 |
7 | use Moo; |
8 | |
9 | has fh => ( |
10 | is => 'ro', required => 1, |
11 | trigger => sub { |
12 | my ($self, $fh) = @_; |
13 | weaken($self); |
0511910e |
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 | |
23 | has on_close_call => ( |
24 | is => 'rw', default => sub { sub {} }, |
25 | ); |
26 | |
27 | has on_line_call => (is => 'rw'); |
28 | |
29 | has _receive_data_buffer => (is => 'ro', default => sub { my $x = ''; \$x }); |
30 | |
31 | sub _receive_data_from { |
32 | my ($self, $fh) = @_; |
07105aca |
33 | Dlog_trace { "Preparing to read data from $_" } $fh; |
12fb4a80 |
34 | my $rb = $self->_receive_data_buffer; |
07105aca |
35 | my $len = sysread($fh, $$rb, 32768, length($$rb)); |
69aaad21 |
36 | my $err = defined($len) ? 'eof' : ": $!"; |
12fb4a80 |
37 | if (defined($len) and $len > 0) { |
0511910e |
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 | } |
90a3a7f2 |
42 | #TODO this isn't compatible with Windows but would be if |
43 | #EAGAIN was set to something that could never match |
44 | #if on Windows |
45 | } elsif ($! != EAGAIN) { |
0511910e |
46 | log_trace { "Got EOF or error, this read channel is done" }; |
12fb4a80 |
47 | Object::Remote->current_loop |
48 | ->unwatch_io( |
49 | handle => $self->fh, |
50 | on_read_ready => 1 |
51 | ); |
8ed52376 |
52 | log_trace { "Invoking on_close_call() for dead read channel" }; |
12fb4a80 |
53 | $self->on_close_call->($err); |
54 | } |
55 | } |
56 | |
57 | sub DEMOLISH { |
58 | my ($self, $gd) = @_; |
59 | return if $gd; |
0511910e |
60 | log_trace { "read channel is being demolished" }; |
12fb4a80 |
61 | Object::Remote->current_loop |
62 | ->unwatch_io( |
63 | handle => $self->fh, |
64 | on_read_ready => 1 |
65 | ); |
66 | } |
67 | |
68 | 1; |