re-entrancy attempt
[scpubgit/Object-Remote.git] / lib / Object / Remote / MiniLoop.pm
1 package Object::Remote::MiniLoop;
2
3 use IO::Select;
4 use Time::HiRes qw(time);
5 use Object::Remote::Logging qw( :log :dlog router );
6 use Moo;
7
8 BEGIN {
9   $SIG{PIPE} = sub { log_debug { "Got a PIPE signal" } };
10
11   router()->exclude_forwarding
12 }
13
14 # this is ro because we only actually set it using local in sub run
15 has is_running => (is => 'ro', clearer => 'stop');
16 #maximum duration that select() will block - undef means indefinite,
17 #0 means no blocking, otherwise maximum time in seconds
18 has block_duration => ( is => 'rw' );
19
20 has _read_watches => (is => 'ro', default => sub { {} });
21 has _read_select => (is => 'ro', default => sub { IO::Select->new });
22
23 has _write_watches => (is => 'ro', default => sub { {} });
24 has _write_select => (is => 'ro', default => sub { IO::Select->new });
25
26 has _timers => (is => 'ro', default => sub { [] });
27
28 sub pass_watches_to {
29   my ($self, $new_loop) = @_;
30   log_debug { "passing watches to new run loop" };
31   foreach my $fh ($self->_read_select->handles) {
32     $new_loop->watch_io(
33       handle => $fh,
34       on_read_ready => $self->_read_watches->{$fh}
35     );
36   }
37   foreach my $fh ($self->_write_select->handles) {
38     $new_loop->watch_io(
39       handle => $fh,
40       on_write_ready => $self->_write_watches->{$fh}
41     );
42   }
43 }
44
45 sub watch_io {
46   my ($self, %watch) = @_;
47   my $fh = $watch{handle};
48   Dlog_debug { "Adding IO watch for $_" } $fh;
49
50   if (my $cb = $watch{on_read_ready}) {
51     log_trace { "IO watcher is registering with select for reading" };
52     $self->_read_select->add($fh);
53     $self->_read_watches->{$fh} = $cb;
54   }
55   if (my $cb = $watch{on_write_ready}) {
56     log_trace { "IO watcher is registering with select for writing" };
57     $self->_write_select->add($fh);
58     $self->_write_watches->{$fh} = $cb;
59   }
60   return;
61 }
62
63 sub unwatch_io {
64   my ($self, %watch) = @_;
65   my $fh = $watch{handle};
66   Dlog_debug { "Removing IO watch for $_" } $fh;
67   if ($watch{on_read_ready}) {
68     log_trace { "IO watcher is removing read from select()" };
69     $self->_read_select->remove($fh);
70     delete $self->_read_watches->{$fh};
71   }
72   if ($watch{on_write_ready}) {
73     log_trace { "IO watcher is removing write from select()" };
74     $self->_write_select->remove($fh);
75     delete $self->_write_watches->{$fh};
76   }
77   return;
78 }
79
80 sub _sort_timers {
81   my ($self, @new) = @_;
82   my $timers = $self->_timers;
83
84   log_trace { "Sorting timers" };
85
86   @{$timers} = sort { $a->[0] <=> $b->[0] } @{$timers}, @new;
87   return;
88 }
89
90 sub watch_time {
91   my ($self, %watch) = @_;
92   my $at;
93
94   Dlog_trace { "watch_time() invoked with $_" } \%watch;
95
96   if (exists($watch{every})) {
97     $at = time() + $watch{every};
98   } elsif (exists($watch{after})) {
99     $at = time() + $watch{after};
100   } elsif (exists($watch{at})) {
101     $at = $watch{at};
102   } else {
103     die "watch_time requires every, after or at";
104   }
105
106   die "watch_time requires code" unless my $code = $watch{code};
107   my $timers = $self->_timers;
108   my $new = [ $at => $code, $watch{every} ];
109   $self->_sort_timers($new);
110   log_debug { "Created new timer with id '$new' that expires at '$at'" };
111   return "$new";
112 }
113
114 sub unwatch_time {
115   my ($self, $id) = @_;
116   log_trace { "Removing timer with id of '$id'" };
117   @$_ = grep !($_ eq $id), @$_ for $self->_timers;
118   return;
119 }
120
121 sub _next_timer_expires_delay {
122   my ($self) = @_;
123   my $timers = $self->_timers;
124   my $delay_max = $self->block_duration;
125
126   return $delay_max unless @$timers;
127   my $duration = $timers->[0]->[0] - time;
128
129   log_trace { "next timer fires in '$duration' seconds" };
130
131   if ($duration < 0) {
132     $duration = 0;
133   } elsif (defined $delay_max && $duration > $delay_max) {
134     $duration = $delay_max;
135   }
136
137   return $duration;
138 }
139
140 sub loop_once {
141   my ($self) = @_;
142   $self->{was_re_entered} = 1 if exists $self->{was_re_entered};
143   my $read = $self->_read_watches;
144   my $write = $self->_write_watches;
145   my $read_count = 0;
146   my $write_count = 0;
147   my @c = caller;
148   my $wait_time = $self->_next_timer_expires_delay;
149   log_trace {
150     sprintf("Run loop: loop_once() has been invoked by $c[1]:$c[2] with read:%i write:%i select timeout:%s",
151       scalar(keys(%$read)), scalar(keys(%$write)), defined $wait_time ? $wait_time : 'indefinite' )
152   };
153   my ($readable, $writeable) = IO::Select->select(
154     $self->_read_select, $self->_write_select, undef, $wait_time
155   );
156   log_trace {
157     my $readable_count = defined $readable ? scalar(@$readable) : 0;
158     my $writable_count = defined $writeable ? scalar(@$writeable) : 0;
159     "Run loop: select returned readable:$readable_count writeable:$writable_count";
160   };
161   # I would love to trap errors in the select call but IO::Select doesn't
162   # differentiate between an error and a timeout.
163   #   -- no, love, mst.
164
165   log_trace { "Reading from ready filehandles" };
166   foreach my $fh (@$readable) {
167     next unless $read->{$fh};
168     $read_count++;
169     my $was_re_entered = do {
170       local $self->{was_re_entered};
171       $read->{$fh}();
172       $self->{was_re_entered};
173     };
174     return if $was_re_entered;
175   }
176   log_trace { "Writing to ready filehandles" };
177   foreach my $fh (@$writeable) {
178     next unless $write->{$fh};
179     $write_count++;
180     my $was_re_entered = do {
181       local $self->{was_re_entered};
182       $write->{$fh}();
183       $self->{was_re_entered};
184     };
185     return if $was_re_entered;
186   }
187
188   #moving the timers above the read() section exposes a deadlock
189   log_trace { "Read from $read_count filehandles; wrote to $write_count filehandles" };
190   my $timers = $self->_timers;
191   my $now = time();
192   log_trace { "Checking timers" };
193   while (@$timers and $timers->[0][0] <= $now) {
194     my $active = $timers->[0];
195     Dlog_trace { "Found timer that needs to be executed: '$active'" };
196
197     if (defined($active->[2])) {
198       #handle the case of an 'every' timer
199       $active->[0] = time() + $active->[2];
200       Dlog_trace { "scheduling timer for repeat execution at $_"} $active->[0];
201       $self->_sort_timers;
202     } else {
203       #it doesn't repeat again so get rid of it
204       shift(@$timers);
205     }
206
207     #execute the timer
208     $active->[1]->();
209   }
210
211   log_trace { "Run loop: single loop is completed" };
212   return;
213 }
214
215 sub want_run {
216   my ($self) = @_;
217   Dlog_debug { "Run loop: Incremeting want_running, is now $_" }
218     ++$self->{want_running};
219 }
220
221 sub run_while_wanted {
222   my ($self) = @_;
223   log_debug { my $wr = $self->{want_running}; "Run loop: run_while_wanted() invoked; want_running: $wr" };
224   $self->loop_once while $self->{want_running};
225   log_debug { "Run loop: run_while_wanted() completed" };
226   return;
227 }
228
229 sub want_stop {
230   my ($self) = @_;
231   if (! $self->{want_running}) {
232     log_debug { "Run loop: want_stop() was called but want_running was not true" };
233     return;
234   }
235   Dlog_debug { "Run loop: decrimenting want_running, is now $_" }
236     --$self->{want_running};
237 }
238
239 sub run {
240   my ($self) = @_;
241   log_trace { "Run loop: run() invoked" };
242   local $self->{is_running} = 1;
243   while ($self->is_running) {
244     $self->loop_once;
245   }
246   log_trace { "Run loop: run() completed" };
247   return;
248 }
249
250 1;