WebKit/Client.pm untested

filter: Statementstmt 0.0% 0 / 284 Branchbran 0.0% 0 / 94 Conditioncond 0.0% 0 / 89 MC/DCmcdc 0.0% 0 / 53 Subroutinesub 0.0% 0 / 38 Podpod 0.0% 0 / 24 totaltotal 0.0% 0 / 582 CC 48 SCAR 36.6
CC
48
Cov
0%
_read_until
110.0
_request
110.0
connect
56.0
CRAP 38.8
1 package EV::WebKit::Client;
2 use v5.10;
3 use strict;
4 use warnings;
5  
6 use Carp ();
7 use Errno ();
8 use Scalar::Util ();
9 use IO::Socket::UNIX (); # () like every other import here: its Socket re-exports would otherwise land in this package as callable methods
10 use MIME::Base64 ();
11 use EV::WebKit::Protocol;
12 use EV::WebKit::Client::Element;
13  
14 our $VERSION = '0.05';
15  
16 # How many undelivered broadcast events to keep when no on_event handler was
17 # given. A page produces console output at its own pace and a caller may never
18 # call events(); this bounds what that costs in the caller's process.
19 use constant MAX_EVENT_BACKLOG => 10_000;
20  
21 # Strip the " at FILE line N." a croak adds, so an error delivered to a callback
22 # reads like every other error this API produces.
23 sub _clean { my $e = shift // ''; $e =~ s/ at \S+ line \d+\.?\s*$//; $e }
24  
25 # Deliver a failure on a clean tick, never on the caller's own stack. EV::WebKit
26 # defers every callback for the same reason: delivered inline, the ordinary
27 # retry-on-error shape (`$c->title(sub { $retry->() if $_[1] })`) recurses
28 # instead of looping, and code after the call has not run yet when the callback
29 # depending on it fires. The timer is held by its own closure -- a void-context
30 # watcher is collected before it fires.
31 sub _defer_err {
32 my ($self, $cb, $err) = @_;
33 my $t; $t = EV::timer(0, 0, sub { undef $t; _deliver($cb, undef, $err) });
34 return;
35 }
36  
37 # Drive a browser running in another process.
38 #
39 # Blocking by default -- `say $c->title` -- which is what you want from a shell
40 # or a one-off script. Blocking mode is PLAIN SOCKET I/O, deliberately not a
41 # nested EV::run: a nested loop inside a callback is how EV::Glib gets wedged,
42 # and a client has no business running somebody else's loop anyway.
43 #
44 # With `ev => 1` every method takes a trailing callback instead and behaves like
45 # EV::WebKit itself, so code moves between a local browser and a remote one
46 # without being rewritten.
47  
48 # The browser methods, forwarded verbatim.
49 #
50 # NOT here: find, find_all, find_js, find_all_js and wait_for (all resolve with an element, so
51 # they are wrapped into a proxy), and screenshot (bytes mode comes back base64'd
52 # and has to be decoded). They are defined separately below -- and they must not
53 # appear here as well, because this loop assigns the globs at RUNTIME and would
54 # quietly clobber them.
55 my @METHODS = qw(
56 go load_html back forward reload stop
57 can_go_back can_go_forward uri title is_loading html status
58 script script_async pdf
59 press scroll download wait_for_js frames resize zoom wait_for_navigation
60 settings set_user_agent user_agent set_proxy show_devtools
61 set_cookie cookies clear_cookies save_cookies load_cookies
62 quit
63 );
64  
65 sub connect {
66 my ($class, $path) = (shift, shift);
67 Carp::croak('connect: a socket path is required') unless defined $path && length $path;
68 # Before %o = @_: an odd list warns from inside this file and drops the
69 # trailing token, so connect($path, 'ev') built a BLOCKING client with `ev`
70 # unset -- and the first call from inside the caller's loop then blocks it.
71 Carp::croak('connect: options must be name => value pairs') if @_ % 2;
72 my %o = @_;
73 if (my @bad = sort grep { !/^(?:ev|on_event)$/ } keys %o) {
74 Carp::croak("connect: unknown option(s): @bad (expected ev/on_event)");
75 }
76 Carp::croak('connect: on_event must be a code reference')
77 if defined $o{on_event} && ref $o{on_event} ne 'CODE';
78 my $sock = IO::Socket::UNIX->new(Peer => $path)
79 or Carp::croak("connect: cannot connect to '$path': $!");
80  
81 my $self = bless {
82 sock => $sock,
83 path => $path,
84 dec => EV::WebKit::Protocol::decoder(),
85 next_id => 0,
86 events => [],
87 pending => {}, # ev mode: id => callback
88 stash => {}, # blocking: somebody else's answer, read while we waited
89 out => '', # ev mode: queued outbound octets
90 on_event => $o{on_event},
91 ev => $o{ev} ? 1 : 0,
92 hello => undef,
93 }, $class;
94  
95 if ($self->{ev}) {
96 # EV is loaded only for ev mode -- a blocking client is plain socket I/O
97 # and has no business pulling in an event loop. Hence EV::READ() with
98 # parens: a bareword would have to resolve at compile time, and EV is not
99 # loaded then.
100 require EV;
101 $sock->blocking(0);
102 # WEAK, like every other self-stored watcher in this distribution: the
103 # watcher lives on $self and its closure captured $self, so an ev client
104 # the caller simply dropped was never collected -- DESTROY never ran, the
105 # socket stayed open, and anything in flight at that moment was never
106 # resolved. A daemon that attaches one client per job leaked an fd each
107 # time.
108 Scalar::Util::weaken(my $wself = $self);
109 $self->{rw} = EV::io($sock, EV::READ(), sub { my $s = $wself or return; $s->_ev_readable });
110 }
111 else {
112 # The greeting tells a client attaching to a long-lived session where the
113 # browser already is. Read it now so ->hello is available immediately.
114 $self->{hello} = $self->_read_until(sub { ($_[0]{ev} // '') eq 'hello' });
115 }
116  
117 return $self;
118 }
119  
120 sub path { $_[0]{path} }
121 sub hello { $_[0]{hello} }
122  
123 # Drain the events that have arrived (blocking mode buffers them; ev mode
124 # delivers them to on_event instead).
125 sub events {
126 my $self = shift;
127 my @e = @{ $self->{events} };
128 $self->{events} = [];
129 return @e;
130 }
131  
132 sub disconnect {
133 my $self = shift;
134 delete $self->{rw};
135 delete $self->{ww};
136 close $self->{sock} if $self->{sock};
137 delete $self->{sock};
138 # Anything still in flight is owed an answer. Walking away from a pending
139 # callback is a hung caller -- and disconnect() is an ordinary, documented
140 # call, not an error path, so it is if anything the likelier way to get here.
141 my @owed = values %{ $self->{pending} || {} };
142 $self->{pending} = {};
143 _deliver($_, undef, 'disconnected') for @owed;
144 return;
145 }
146  
147 sub DESTROY { local $@; eval { $_[0]->disconnect } }
148  
149 # ---------------------------------------------------------------- plumbing
150  
151 sub _write {
152 my ($self, $octets) = @_;
153 my $sock = $self->{sock} or Carp::croak('the connection is closed');
154  
155 if ($self->{ev}) {
156 # Non-blocking. Queue it and let a write watcher drain it: spinning on
157 # EAGAIN would burn a whole core AND block the caller's entire loop --
158 # and an ev-mode call is supposed to return immediately. (The server's
159 # own _flush already does exactly this; the client did not.)
160 $self->{out} .= $octets;
161 return $self->_flush;
162 }
163  
164 # Writing to a peer that has closed raises SIGPIPE, whose default is to KILL
165 # THE PROCESS -- so one call after the browser has gone would end the client
166 # outright, and no eval can catch a signal. Ignore it and let syswrite report
167 # EPIPE like any other error.
168 local $SIG{PIPE} = 'IGNORE';
169 while (length $octets) {
170 my $n = syswrite($sock, $octets);
171 if (!defined $n) {
172 next if $!{EINTR} || $!{EAGAIN};
173 Carp::croak("write failed: $!");
174 }
175 substr($octets, 0, $n, '');
176 }
177 return;
178 }
179  
180 sub _flush {
181 my $self = shift;
182 my $sock = $self->{sock} or return;
183 local $SIG{PIPE} = 'IGNORE';
184 while (length $self->{out}) {
185 my $n = syswrite($sock, $self->{out});
186 if (!defined $n) {
187 last if $!{EAGAIN} || $!{EINTR};
188 return $self->_ev_gone("write failed: $!");
189 }
190 substr($self->{out}, 0, $n, '');
191 }
192 if (length $self->{out}) {
193 Scalar::Util::weaken(my $wself = $self);
194 $self->{ww} ||= EV::io($sock, EV::WRITE(), sub { my $s = $wself or return; $s->_flush });
195 }
196 else {
197 delete $self->{ww};
198 }
199 return;
200 }
201  
202 sub _event {
203 my ($self, $f) = @_;
204 # The greeting is an event, but it is also the answer to "where is this
205 # browser?" -- keep it, in ev mode too, or ->hello is undef forever and
206 # re-attaching to a long-lived session cannot work.
207 $self->{hello} = $f if ($f->{ev} // '') eq 'hello' && !$self->{hello};
208 if (my $cb = $self->{on_event}) {
209 # Guarded: a throwing event handler must not take down whatever else is
210 # being delivered in the same batch.
211 unless (eval { $cb->($f->{ev}, $f); 1 }) {
212 warn "EV::WebKit::Client: on_event callback died: $@";
213 }
214 return;
215 }
216 # Bounded, for the same reason the server bounds its per-client outbound
217 # queue: a page generates console lines as fast as it likes, and a client
218 # that never drains events() must not grow without limit inside the caller's
219 # own process. Oldest first, which is what a caller watching for "what just
220 # happened" wants kept.
221 push @{ $self->{events} }, $f;
222 shift @{ $self->{events} } while @{ $self->{events} } > MAX_EVENT_BACKLOG;
223 return;
224 }
225  
226 # Blocking: read frames until $want->($frame) says one of them is the one we are
227 # after. Events met on the way are dispatched, never confused with a response.
228 sub _read_until {
229 my ($self, $want) = @_;
230 my $sock = $self->{sock} or Carp::croak('the connection is closed');
231 while (1) {
232 # Check the stash EVERY iteration, not just once. on_event is invoked
233 # from inside this loop, and a handler that makes its own blocking call
234 # nests a second _read_until that reads -- and stashes -- the OUTER
235 # call's answer while we were parked in sysread. So our answer can appear
236 # in the stash between reads; binning it, or checking only at entry,
237 # leaves the outer caller waiting forever for a response already in hand.
238 for my $sid (sort { $a <=> $b } keys %{ $self->{stash} }) {
239 my $f = $self->{stash}{$sid};
240 if ($want->($f)) { delete $self->{stash}{$sid}; return $f }
241 }
242 my $n = sysread($sock, my $buf, 65536);
243 if (!defined $n) {
244 next if $!{EAGAIN} || $!{EINTR};
245 Carp::croak("read failed: $!");
246 }
247 Carp::croak('the browser closed the connection') unless $n;
248 # Drain the WHOLE batch before returning. One read can decode several
249 # frames, and returning on the first match would silently drop the rest --
250 # exactly the reentrancy hang: a nested call reads its own answer AND the
251 # outer call's in one batch, and abandoning the batch loses the outer's,
252 # which was already pulled out of the decoder. So keep our match aside and
253 # finish draining: events get dispatched, other answers get stashed for
254 # whoever is waiting, and only then do we return.
255 my ($mine, $got_mine);
256 for my $f ($self->{dec}->($buf)) {
257 # The predicate goes FIRST, before the event branch: the frame we are
258 # waiting for can itself BE an event -- the hello is one -- and
259 # dispatching it as an event would mean losing the very thing we want.
260 # The codec gives up permanently on an oversized line (see
261 # EV::WebKit::Protocol) and reports it as {_bad}. Nothing further
262 # can ever be decoded on this connection, so surface it as the
263 # answer rather than letting every call from here on quietly return
264 # undef with no error -- which is what happened while this frame
265 # shape went unrecognised.
266 if (defined $f->{_bad}) { $mine = { e => "protocol error: $f->{_bad}" }; $got_mine = 1; next }
267 if (!$got_mine && $want->($f)) { $mine = $f; $got_mine = 1; next }
268 if (defined $f->{ev}) { $self->_event($f); next }
269 # A null-id error (a malformed line) answers no particular request; if
270 # nothing else here is ours, it belongs to whoever is waiting.
271 if (!defined $f->{i}) { $mine //= $f; $got_mine ||= 1; next }
272 $self->{stash}{ $f->{i} } = $f; # somebody else's answer -- keep it
273 }
274 return $mine if $got_mine;
275 }
276 }
277  
278 # ---------------------------------------------------------------- calls
279  
280 sub _next_id { ++$_[0]{next_id} }
281  
282 # One request. In blocking mode this returns the result and CROAKS on error --
283 # synchronous code has no callback to hand an error to, and croaking is how it
284 # reports one. In ev mode the last argument is a callback and it gets
285 # ($result, $err), exactly as EV::WebKit does.
286 sub _request {
287 my ($self, $m, $a, $h, $cb, $post) = @_;
288 my $id = $self->_next_id;
289 my %frame = (i => $id, m => $m, a => $a);
290 $frame{h} = $h if defined $h;
291  
292 if ($self->{ev}) {
293 Carp::croak("$m: a callback is required in ev mode (it cannot block: you own the loop)")
294 unless $cb;
295 # Encode before registering, and undo the registration if the write
296 # fails -- either way a failure of the two is DELIVERED to the callback. Both can croak on a healthy connection (an argument the
297 # JSON codec cannot represent) or a dead one, and an ev-mode call is
298 # nearly always made from inside another callback -- where the croak is
299 # swallowed by $EV::DIED and the just-registered entry would sit in
300 # {pending} forever, never called. This is the one contract this mode
301 # has: an error is DELIVERED, never thrown.
302 my $line = eval { EV::WebKit::Protocol::encode(\%frame) };
303 return $self->_defer_err($cb, "$m: " . _clean($@)) unless defined $line;
304 my $wrapped = sub {
305 my ($r, $e) = @_;
306 return $cb->(undef, $e) if defined $e;
307 return $cb->($post ? $post->($r) : $r, undef);
308 };
309 $self->{pending}{$id} = $wrapped;
310 unless (eval { $self->_write($line); 1 }) {
311 delete $self->{pending}{$id};
312 return $self->_defer_err($cb, "$m: " . _clean($@));
313 }
314 return;
315 }
316  
317 $self->_write(EV::WebKit::Protocol::encode(\%frame));
318 my $f = $self->_read_until(sub { defined $_[0]{i} && $_[0]{i} == $id });
319 Carp::croak("$m: $f->{e}") if defined $f->{e};
320 return $post ? $post->($f->{r}) : $f->{r};
321 }
322  
323 sub _call {
324 my ($s, $m, $a, $h) = (shift, shift, shift, shift);
325 my $cb = _cb($a);
326 $s->_no_cb_in_blocking_mode($m, $cb);
327 $s->_request($m, $a, $h, $cb);
328 }
329 sub _call_el {
330 my ($s, $m, $a, $h) = (shift, shift, shift, shift);
331 my $cb = _cb($a);
332 $s->_no_cb_in_blocking_mode($m, $cb);
333 # WEAK, like the watchers: this closure is reachable from {pending} and
334 # captured $s, so an ev client dropped with an element-returning request in
335 # flight was not collected until the answer came back -- which for a
336 # wait_for could be an hour.
337 Scalar::Util::weaken(my $ws = $s);
338 $s->_request($m, $a, $h, $cb, sub { my $c = $ws or return undef; $c->_wrap($_[0]) });
339 }
340  
341 # Blocking mode returns its result; a trailing callback there is a caller who
342 # meant to open the client with ev => 1, and silently never running it is the
343 # worst of the three possible answers.
344 sub _no_cb_in_blocking_mode {
345 my ($s, $m, $cb) = @_;
346 Carp::croak("$m: a callback needs ev => 1 (this client is in blocking mode, which returns the result)")
347 if $cb && !$s->{ev};
348 return;
349 }
350  
351 # In ev mode the caller's callback is the last argument they passed; strip it out
352 # of the wire arguments.
353 sub _cb {
354 my $a = shift;
355 return undef unless @$a && ref $a->[-1] eq 'CODE';
356 # ...but not when it is the VALUE of a named callback option. scroll takes
357 # `cb => $cb` as well as a trailing one, so popping blindly left the orphan
358 # key travelling alone; the server then appended its own `cb =>`, the method
359 # saw an odd option list, and the documented spelling croaked remotely while
360 # working locally. Pull the pair out instead, and send it as a trailing
361 # callback, which is what the wire carries.
362 if (@$a >= 2 && defined $a->[-2] && !ref $a->[-2]
363 && ($a->[-2] eq 'cb' || $a->[-2] eq 'callback')) {
364 my $c = pop @$a;
365 pop @$a;
366 return $c;
367 }
368 return pop @$a;
369 }
370  
371 # A handle (or a list of them) becomes an element proxy.
372 sub _wrap {
373 my ($self, $r) = @_;
374 return undef unless defined $r;
375 return [ map { EV::WebKit::Client::Element->_new($self, $_->{h}) } @$r ] if ref $r eq 'ARRAY';
376 # wait_for(gone => 1) resolves with a plain TRUE, not a handle -- there is
377 # no node left to hand back. The server stopped marshalling it as one; this
378 # is the other half. Without it `1->{h}` dies under strict refs: in blocking
379 # mode that raw error replaces the answer, and in ev mode _deliver's eval
380 # swallows it and the caller's callback is never invoked at all.
381 return $r unless ref $r;
382 return EV::WebKit::Client::Element->_new($self, $r->{h});
383 }
384  
385 # Raw bytes cannot live in a JSON string, so screenshot({ bytes => 1 }) comes back
386 # base64'd. Decode it here, so a caller gets the same raw PNG octets they would
387 # get from EV::WebKit itself -- the whole point being that code moves between a
388 # local browser and a remote one without being rewritten.
389 sub _unb64 {
390 my (undef, $r) = @_;
391 return $r unless ref $r eq 'HASH' && exists $r->{b64};
392 return MIME::Base64::decode_base64($r->{b64});
393 }
394  
395 sub _ev_readable {
396 my $self = shift;
397 my $sock = $self->{sock} or return;
398 my $n = sysread($sock, my $buf, 65536);
399 if (!defined $n) { return if $!{EAGAIN} || $!{EINTR}; return $self->_ev_gone("read failed: $!") }
400 return $self->_ev_gone('the browser closed the connection') unless $n;
401 for my $f ($self->{dec}->($buf)) {
402 # A dead codec cannot produce another frame, so every pending callback
403 # is owed an error now -- otherwise they are simply never called, and
404 # the caller's EV::run waits for answers that can no longer arrive.
405 return $self->_ev_gone("protocol error: $f->{_bad}") if defined $f->{_bad};
406 if (defined $f->{ev}) { $self->_event($f); next }
407 my $cb = delete $self->{pending}{ $f->{i} // '' } or next;
408 _deliver($cb, $f->{r}, $f->{e});
409 }
410 return;
411 }
412  
413 # Deliver one callback, guarded. Several responses can arrive in a single read,
414 # and a die from one of them must not swallow the rest of the batch -- the caller
415 # would never hear about requests it is still waiting on. (The same lesson the
416 # browser's own quit() flush loops taught.)
417 sub _deliver {
418 my ($cb, @args) = @_;
419 return if eval { $cb->(@args); 1 };
420 warn "EV::WebKit::Client: callback died: $@";
421 return;
422 }
423  
424 # The far end went away. Every request still in flight is owed an answer -- a
425 # dropped callback is a hung caller, which is the one failure mode this protocol
426 # must not have.
427 sub _ev_gone {
428 my ($self, $why) = @_;
429 my @owed = values %{ $self->{pending} };
430 $self->{pending} = {};
431 $self->disconnect;
432 # On a clean tick, never on the caller's stack. A socket that died unnoticed
433 # is discovered inside _write, so delivering here ran the new request's
434 # callback -- and every earlier one still in flight -- before the method the
435 # caller just invoked had returned.
436 my $t; $t = EV::timer(0, 0, sub { undef $t; _deliver($_, undef, $why) for @owed });
437 return;
438 }
439  
440 # ---------------------------------------------------------------- the API
441  
442 for my $m (@METHODS) {
443 no strict 'refs';
444 *{__PACKAGE__ . "::$m"} = sub {
445 my $self = shift;
446 return $self->_call($m, [@_]);
447 };
448 }
449  
450 # All of these resolve with an element.
451 for my $m (qw(find find_all find_js find_all_js wait_for)) {
452 no strict 'refs';
453 *{__PACKAGE__ . "::$m"} = sub {
454 my $self = shift;
455 return $self->_call_el($m, [@_]);
456 };
457 }
458  
459 # bytes mode comes back base64'd; give the caller the raw octets.
460 sub screenshot {
461 my $self = shift;
462 my $a = [@_];
463 my $cb = _cb($a);
464 $self->_no_cb_in_blocking_mode('screenshot', $cb);
465 Scalar::Util::weaken(my $ws = $self);
466 return $self->_request('screenshot', $a, undef, $cb, sub { my $c = $ws or return undef; $c->_unb64($_[0]) });
467 }
468  
469 1;
470  
471 __END__