blib/lib/Mojo/Reactor/UV.pm

filter: Statementstmt 86.6% 13 / 15 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 90.0% 18 / 20 CC 1 SCAR 0.6
CC
1
Cov
87%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 package Mojo::Reactor::UV;
2 1 ▶use Mojo::Base 'Mojo::Reactor::Poll';
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 $ENV{MOJO_REACTOR} ||= 'Mojo::Reactor::UV';
5  
6 1 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Mojo::Util qw(md5_sum steady_time);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Scalar::Util qw(blessed weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 0 ▶use UV;
Subroutine BEGIN: called CC=1 SCAR=2.6
10 use UV::Poll;
11 use UV::Timer;
12 use UV::Loop;
13  
14 use constant DEBUG => $ENV{MOJO_REACTOR_UV_DEBUG} || 0;
15  
16 our $VERSION = '1.901';
17  
18 my $UV;
19  
20 # Use UV::Loop singleton for the first instance only
21 sub new {
22 my $self = shift->SUPER::new;
23 if ($UV++) {
24 $self->{loop} = UV::Loop->new;
25 } else {
26 $self->{loop} = UV::Loop->default_loop;
27 $self->{loop_singleton} = 1;
28 }
29 return $self;
30 }
31  
32 sub DESTROY { undef $UV if shift->{loop_singleton} }
33  
34 sub again {
35 my ($self, $id, $after) = @_;
36 croak 'Timer not active' unless my $timer = $self->{timers}{$id};
37 my $w = $timer->{watcher};
38 if (defined $after) {
39 $after *= 1000; # Intervals in milliseconds
40 # Timer will not repeat with (integer) interval of 0
41 $after = 1 if $after < 1;
42 eval { $w->repeat($after); 1 } or $self->_error($@);
43 }
44 eval { $w->again; 1 } or $self->_error($@);
45 }
46  
47 sub io {
48 my ($self, $handle, $cb) = @_;
49 my $fd = fileno($handle) // croak 'Handle is closed';
50 # Must use existing watcher if present
51 $self->{io}{$fd}{cb} = $cb;
52 warn "-- Set IO watcher for $fd\n" if DEBUG;
53 return $self->watch($handle, 1, 1);
54 }
55  
56 sub one_tick {
57 my $self = shift;
58 # Just one tick
59 local $self->{running} = 1 unless $self->{running};
60 $self->{loop}->run(UV::Loop::UV_RUN_ONCE) or $self->stop;
61 }
62  
63 sub recurring { shift->_timer(1, @_) }
64  
65 sub remove {
66 my ($self, $remove) = @_;
67 return unless defined $remove;
68 if (ref $remove) {
69 my $fd = fileno($remove) // croak 'Handle is closed';
70 if (exists $self->{io}{$fd}) {
71 warn "-- Removed IO watcher for $fd\n" if DEBUG;
72 my $w = delete $self->{io}{$fd}{watcher};
73 $w->close if $w;
74 }
75 return !!delete $self->{io}{$fd};
76 } else {
77 if (exists $self->{timers}{$remove}) {
78 warn "-- Removed timer $remove\n" if DEBUG;
79 my $w = delete $self->{timers}{$remove}{watcher};
80 $w->close if $w;
81 }
82 return !!delete $self->{timers}{$remove};
83 }
84 }
85  
86 sub reset {
87 my $self = shift;
88 $_->close for map { $_->{watcher} ? ($_->{watcher}) : () }
89 values %{$self->{io}}, values %{$self->{timers}};
90 $self->SUPER::reset;
91 }
92  
93 sub timer { shift->_timer(0, @_) }
94  
95 sub watch {
96 my ($self, $handle, $read, $write) = @_;
97
98 my $fd = fileno $handle;
99 croak 'I/O watcher not active' unless my $io = $self->{io}{$fd};
100
101 my $mode = 0;
102 $mode |= UV::Poll::UV_READABLE if $read;
103 $mode |= UV::Poll::UV_WRITABLE if $write;
104
105 my $w;
106 unless ($w = $io->{watcher}) { $w = $io->{watcher} = UV::Poll->new(loop => $self->{loop}, fd => $fd); }
107
108 if ($mode == 0) { eval { $w->stop; 1 } or $self->_error($@); }
109 else {
110 weaken $self;
111 my $cb = sub {
112 my ($w, $status, $events) = @_;
113 return $self->_error($status) if $status < 0;
114 $self->_try('I/O watcher', $self->{io}{$fd}{cb}, 0)
115 if UV::Poll::UV_READABLE & $events;
116 $self->_try('I/O watcher', $self->{io}{$fd}{cb}, 1)
117 if UV::Poll::UV_WRITABLE & $events && $self->{io}{$fd};
118 };
119 eval { $w->start($mode, $cb); 1 } or $self->_error($@);
120 }
121
122 return $self;
123 }
124  
125 sub _error {
126 my ($self, $err) = @_;
127 if (blessed $err and $err->isa('UV::Exception')) {
128 $self->emit(error => sprintf 'UV error: %s', $err->message);
129 } elsif (!ref $err and $err < 0) {
130 $self->emit(error => sprintf 'UV error: %s', UV::strerror($err));
131 }
132 return $err;
133 }
134  
135 sub _id {
136 my $self = shift;
137 my $id;
138 do { $id = md5_sum 't' . steady_time . rand } while $self->{timers}{$id};
139 return $id;
140 }
141  
142 sub _timer {
143 my ($self, $recurring, $after, $cb) = @_;
144 $after *= 1000; # Intervals in milliseconds
145 my $recur_after = $after;
146 # Timer will not repeat with (integer) interval of 0
147 $recur_after = 1 if $recurring and $after < 1;
148
149 my $id = $self->_id;
150 weaken $self;
151 my $wrapper = sub {
152 $self->remove($id) unless $recurring;
153 $self->_try('Timer', $cb);
154 };
155 my $w = $self->{timers}{$id}{watcher} = UV::Timer->new(loop => $self->{loop});
156 eval { $w->start($after, $recur_after, $wrapper); 1 } or $self->_error($@);
157
158 if (DEBUG) {
159 my $is_recurring = $recurring ? ' (recurring)' : '';
160 my $seconds = $after / 1000;
161 warn "-- Set timer $id after $seconds seconds$is_recurring\n";
162 }
163
164 return $id;
165 }
166  
167 sub _try {
168 my ($self, $what, $cb) = (shift, shift, shift);
169 eval { $self->$cb(@_); 1 } or $self->emit(error => "$what failed: $@");
170 }
171  
172 1;
173  
174 =encoding utf8
175  
176 =head1 NAME
177  
178 Mojo::Reactor::UV - UV backend for Mojo::Reactor
179  
180 =head1 SYNOPSIS
181  
182 use Mojo::Reactor::UV;
183  
184 # Watch if handle becomes readable or writable
185 my $reactor = Mojo::Reactor::UV->new;
186 $reactor->io($first => sub {
187 my ($reactor, $writable) = @_;
188 say $writable ? 'First handle is writable' : 'First handle is readable';
189 });
190  
191 # Change to watching only if handle becomes writable
192 $reactor->watch($first, 0, 1);
193  
194 # Turn file descriptor into handle and watch if it becomes readable
195 my $second = IO::Handle->new_from_fd($fd, 'r');
196 $reactor->io($second => sub {
197 my ($reactor, $writable) = @_;
198 say $writable ? 'Second handle is writable' : 'Second handle is readable';
199 })->watch($second, 1, 0);
200  
201 # Add a timer
202 $reactor->timer(15 => sub {
203 my $reactor = shift;
204 $reactor->remove($first);
205 $reactor->remove($second);
206 say 'Timeout!';
207 });
208  
209 # Start reactor if necessary
210 $reactor->start unless $reactor->is_running;
211  
212 # Or in an application using Mojo::IOLoop
213 use Mojo::Reactor::UV;
214 use Mojo::IOLoop;
215  
216 # Or in a Mojolicious application
217 $ MOJO_REACTOR=Mojo::Reactor::UV hypnotoad script/myapp
218  
219 =head1 DESCRIPTION
220  
221 L<Mojo::Reactor::UV> is an event reactor for L<Mojo::IOLoop> that uses
222 C<libuv>. The usage is exactly the same as other L<Mojo::Reactor>
223 implementations such as L<Mojo::Reactor::Poll>. L<Mojo::Reactor::UV> will be
224 used as the default backend for L<Mojo::IOLoop> if it is loaded before
225 L<Mojo::IOLoop> or any module using the loop. However, when invoking a
226 L<Mojolicious> application through L<morbo> or L<hypnotoad>, the reactor must
227 be set as the default by setting the C<MOJO_REACTOR> environment variable to
228 C<Mojo::Reactor::UV>.
229  
230 =head1 EVENTS
231  
232 L<Mojo::Reactor::UV> inherits all events from L<Mojo::Reactor::Poll>.
233  
234 =head1 METHODS
235  
236 L<Mojo::Reactor::UV> inherits all methods from L<Mojo::Reactor::Poll> and
237 implements the following new ones.
238  
239 =head2 new
240  
241 my $reactor = Mojo::Reactor::UV->new;
242  
243 Construct a new L<Mojo::Reactor::UV> object.
244  
245 =head2 again
246  
247 $reactor->again($id);
248 $reactor->again($id, 0.5);
249  
250 Restart timer and optionally change the invocation time. Note that this method
251 requires an active timer.
252  
253 =head2 io
254  
255 $reactor = $reactor->io($handle => sub {...});
256  
257 Watch handle for I/O events, invoking the callback whenever handle becomes
258 readable or writable.
259  
260 # Callback will be invoked twice if handle becomes readable and writable
261 $reactor->io($handle => sub {
262 my ($reactor, $writable) = @_;
263 say $writable ? 'Handle is writable' : 'Handle is readable';
264 });
265  
266 =head2 one_tick
267  
268 $reactor->one_tick;
269  
270 Run reactor until an event occurs or no events are being watched anymore. Note
271 that this method can recurse back into the reactor, so you need to be careful.
272  
273 # Don't block longer than 0.5 seconds
274 my $id = $reactor->timer(0.5 => sub {});
275 $reactor->one_tick;
276 $reactor->remove($id);
277  
278 =head2 recurring
279  
280 my $id = $reactor->recurring(0.25 => sub {...});
281  
282 Create a new recurring timer, invoking the callback repeatedly after a given
283 amount of time in seconds.
284  
285 =head2 remove
286  
287 my $bool = $reactor->remove($handle);
288 my $bool = $reactor->remove($id);
289  
290 Remove handle or timer.
291  
292 =head2 reset
293  
294 $reactor->reset;
295  
296 Remove all handles and timers.
297  
298 =head2 timer
299  
300 my $id = $reactor->timer(0.5 => sub {...});
301  
302 Create a new timer, invoking the callback after a given amount of time in
303 seconds.
304  
305 =head2 watch
306  
307 $reactor = $reactor->watch($handle, $readable, $writable);
308  
309 Change I/O events to watch handle for with true and false values. Note that
310 this method requires an active I/O watcher.
311  
312 # Watch only for readable events
313 $reactor->watch($handle, 1, 0);
314  
315 # Watch only for writable events
316 $reactor->watch($handle, 0, 1);
317  
318 # Watch for readable and writable events
319 $reactor->watch($handle, 1, 1);
320  
321 # Pause watching for events
322 $reactor->watch($handle, 0, 0);
323  
324 =head1 CAVEATS
325  
326 When using L<Mojo::IOLoop> with L<UV>, the event loop must be controlled by
327 L<Mojo::IOLoop> or L<Mojo::Reactor::UV>, such as with the methods
328 L<Mojo::IOLoop/"start">, L<Mojo::IOLoop/"stop">, and L</"one_tick">. Starting
329 or stopping the event loop through L<UV> will not provide required
330 functionality to L<Mojo::IOLoop> applications.
331  
332 Care should be taken that file descriptors are not closed while being watched
333 by the reactor. They can be safely closed after calling L</"watch"> with
334 C<readable> and C<writable> set to 0, or after removing the handle with
335 L</"remove"> or L</"reset">.
336  
337 On windows, C<libuv> can only watch sockets, not regular filehandles.
338  
339 =head1 BUGS
340  
341 Report any issues on the public bugtracker.
342  
343 =head1 AUTHOR
344  
345 Dan Book, C<dbook@cpan.org>
346  
347 =head1 COPYRIGHT AND LICENSE
348  
349 Copyright 2015, Dan Book.
350  
351 This library is free software; you may redistribute it and/or modify it under
352 the terms of the Artistic License version 2.0.
353  
354 =head1 SEE ALSO
355  
356 L<Mojolicious>, L<Mojo::IOLoop>, L<UV>
↑ Summary