af9ce36ad4b4a9ba9229543103cf616877175a83
[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 );
6 use Moo;
7
8 # this is ro because we only actually set it using local in sub run
9
10 has is_running => (is => 'ro', clearer => 'stop');
11
12 has _read_watches => (is => 'ro', default => sub { {} });
13 has _read_select => (is => 'ro', default => sub { IO::Select->new });
14
15 has _write_watches => (is => 'ro', default => sub { {} });
16 has _write_select => (is => 'ro', default => sub { IO::Select->new });
17
18 has _timers => (is => 'ro', default => sub { [] });
19
20 sub pass_watches_to {
21   my ($self, $new_loop) = @_;
22   log_debug { "passing watches to new run loop" };
23   foreach my $fh ($self->_read_select->handles) {
24     $new_loop->watch_io(
25       handle => $fh,
26       on_read_ready => $self->_read_watches->{$fh}
27     );
28   }
29   foreach my $fh ($self->_write_select->handles) {
30     $new_loop->watch_io(
31       handle => $fh,
32       on_write_ready => $self->_write_watches->{$fh}
33     );
34   }
35 }
36
37 sub watch_io {
38   my ($self, %watch) = @_;
39   my $fh = $watch{handle};
40   Dlog_debug { "Adding IO watch for $_" } $fh;
41
42   #TODO if this works out non-blocking support
43   #will need to be integrated in a way that
44   #is compatible with Windows which has no
45   #non-blocking support - see also ::ReadChannel
46   if (0) {
47     Dlog_warn { "setting file handle to be non-blocking: $_" } $fh;
48     use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
49     my $flags = fcntl($fh, F_GETFL, 0)
50       or die "Can't get flags for the socket: $!\n";
51     $flags = fcntl($fh, F_SETFL, $flags | O_NONBLOCK)
52       or die "Can't set flags for the socket: $!\n"; 
53   }
54   
55   if (my $cb = $watch{on_read_ready}) {
56     log_trace { "IO watcher is registering with select for reading" };
57     $self->_read_select->add($fh);
58     $self->_read_watches->{$fh} = $cb;
59   }
60   if (my $cb = $watch{on_write_ready}) {
61     log_trace { "IO watcher is registering with select for writing" };
62     $self->_write_select->add($fh);
63     $self->_write_watches->{$fh} = $cb;
64   }
65   return;
66 }
67
68 sub unwatch_io {
69   my ($self, %watch) = @_;
70   my $fh = $watch{handle};
71   Dlog_debug { "Removing IO watch for $_" } $fh;
72   if ($watch{on_read_ready}) {
73     log_trace { "IO watcher is removing read from select()" };
74     $self->_read_select->remove($fh);
75     delete $self->_read_watches->{$fh};
76   }
77   if ($watch{on_write_ready}) {
78     log_trace { "IO watcher is removing write from select()" };
79     $self->_write_select->remove($fh);
80     delete $self->_write_watches->{$fh};
81   }
82   return;
83 }
84
85 sub _sort_timers {
86   my ($self, @new) = @_;
87   my $timers = $self->_timers; 
88   
89   log_trace { "Sorting timers" };
90   
91   @{$timers} = sort { $a->[0] <=> $b->[0] } @{$timers}, @new;
92   return;   
93 }
94
95 sub watch_time {
96   my ($self, %watch) = @_;
97   my $at; 
98   
99   Dlog_trace { "watch_time() invoked with $_" } \%watch;
100  
101   if (exists($watch{every})) {
102     $at = time() + $watch{every};
103   } elsif (exists($watch{after})) {
104     $at = time() + $watch{after}; 
105   } elsif (exists($watch{at})) {
106       $at = $watch{at}; 
107   } else {
108       die "watch_time requires every, after or at";
109   }
110   
111   die "watch_time requires code" unless my $code = $watch{code};
112   my $timers = $self->_timers;
113   my $new = [ $at => $code, $watch{every} ];
114   $self->_sort_timers($new); 
115   log_debug { "Created new timer that expires at '$at'" };
116   return "$new";
117 }
118
119 sub unwatch_time {
120   my ($self, $id) = @_;
121   log_debug { "Removing timer with id of '$id'" };
122   @$_ = grep !($_ eq $id), @$_ for $self->_timers;
123   return;
124 }
125
126 sub _next_timer_expires_delay {
127   my ($self) = @_;
128   my $timers = $self->_timers;
129   #undef means no timeout, select only returns
130   #when data is ready - when the system
131   #deadlocks the chatter from the timeout in
132   #select clogs up the logs
133   #TODO should make this an attribute
134   my $delay_max = undef;
135     
136   return $delay_max unless @$timers;
137   my $duration = $timers->[0]->[0] - time;
138
139   log_trace { "next timer fires in '$duration' seconds " };
140   
141   if ($duration < 0) {
142     $duration = 0; 
143   } elsif (defined $delay_max && $duration > $delay_max) {
144     $duration = $delay_max;
145   }
146   
147   return $duration; 
148 }
149
150 sub loop_once {
151   my ($self) = @_;
152   my $read = $self->_read_watches;
153   my $write = $self->_write_watches;
154   our $Loop_Entered = 1; 
155   my $read_count = 0;
156   my $write_count = 0; 
157   my @c = caller;
158   my $wait_time = $self->_next_timer_expires_delay;
159   log_trace {  sprintf("Run loop: loop_once() has been invoked by $c[1]:$c[2] with read:%i write:%i select timeout:%s",
160       scalar(keys(%$read)), scalar(keys(%$write)), defined $wait_time ? $wait_time : 'indefinite' ) };
161   #TODO The docs state that select() in some instances can return a socket as ready to
162   #read data even if reading from it would block and the recomendation is to set
163   #handles used with select() as non-blocking but Perl on Windows can not set a 
164   #handle to use non-blocking IO - If Windows is not one of the operating
165   #systems where select() returns a handle that could block it would work to
166   #enable non-blocking mode only under Posix - the non-blocking sysread()
167   #logic would work unmodified for both blocking and non-blocking handles
168   #under Posix and Windows.
169   my ($readable, $writeable) = IO::Select->select(
170     #TODO how come select() isn't used to identify handles with errors on them?
171     #TODO is there a specific reason for a half second maximum wait duration?
172     #The two places I've found for the runloop to be invoked don't return control
173     #to the caller until a controlling variable interrupts the loop that invokes
174     #loop_once() - is this to allow that variable to be polled and exit the
175     #run loop? If so why isn't that behavior event driven and causes select() to
176     #return? 
177     $self->_read_select, $self->_write_select, undef, $wait_time
178   ); 
179   log_trace { 
180     my $readable_count = defined $readable ? scalar(@$readable) : 0;
181     my $writable_count = defined $writeable ? scalar(@$writeable) : 0;
182     "Run loop: select returned readable:$readable_count writeable:$writable_count";
183   };
184   # I would love to trap errors in the select call but IO::Select doesn't
185   # differentiate between an error and a timeout.
186   #   -- no, love, mst.
187
188   local $Loop_Entered;
189
190   log_trace { "Reading from all ready filehandles" };
191   foreach my $fh (@$readable) {
192     next unless $read->{$fh};
193     $read_count++;
194     $read->{$fh}();
195     last if $Loop_Entered;
196   }
197   log_trace { "Writing to all ready filehandles" };
198   foreach my $fh (@$writeable) {
199     next unless $write->{$fh};
200     $write_count++;
201     $write->{$fh}();
202     last if $Loop_Entered;
203   }
204   
205   log_trace { "Read from $read_count filehandles; wrote to $write_count filehandles" };
206   my $timers = $self->_timers;
207   my $now = time();
208   log_trace { "Checking timers" };
209   while (@$timers and $timers->[0][0] <= $now) {
210     my $active = $timers->[0]; 
211     Dlog_debug { "Found timer that needs to be executed: $_" } $active;
212 #   my (shift @$timers)->[1]->();
213      
214     if (defined($active->[2])) {
215       #handle the case of an 'every' timer
216       $active->[0] = time() + $active->[2]; 
217       Dlog_trace { "scheduling timer for repeat execution at $_"} $active->[0];
218       $self->_sort_timers;
219     } else {
220       #it doesn't repeat again so get rid of it  
221       shift(@$timers);    
222     }
223
224     #execute the timer
225     $active->[1]->();
226      
227     last if $Loop_Entered;
228   }
229   
230   log_trace { "Run loop: single loop is completed" };
231   return;
232 }
233
234 #::Node and ::ConnectionServer use the want_run() / want_stop()
235 #counter to cause a run-loop to execute while something is active;
236 #the futures do this via a different mechanism
237 sub want_run {
238   my ($self) = @_;
239   Dlog_debug { "Run loop: Incrimenting want_running, is now $_" }
240     ++$self->{want_running};
241 }
242
243 sub run_while_wanted {
244   my ($self) = @_;
245   log_debug { my $wr = $self->{want_running}; "Run loop: run_while_wanted() invoked; want_running: $wr" };
246   $self->loop_once while $self->{want_running};
247   log_debug { "Run loop: run_while_wanted() completed" };
248   return;
249 }
250
251 sub want_stop {
252   my ($self) = @_;
253   if (! $self->{want_running}) {
254     log_debug { "Run loop: want_stop() was called but want_running was not true" };
255     return; 
256   }
257   Dlog_debug { "Run loop: decrimenting want_running, is now $_" }
258     --$self->{want_running};
259 }
260
261 #TODO Hypothesis: Futures invoke run() which gives that future
262 #it's own localized is_running attribute - any adjustment to the
263 #is_running attribute outside of that future will not effect that
264 #future so each future winds up able to call run() and stop() at 
265 #will with out interfering with each other - how about having
266 #run loop until the future becomes ready? 
267 sub run {
268   my ($self) = @_;
269   log_trace { "Run loop: run() invoked" };
270   local $self->{is_running} = 1;
271   while ($self->is_running) {
272     $self->loop_once;
273   }
274   log_trace { "Run loop: run() completed" };
275   return;
276 }
277
278 1;