Playwright.pm 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. package Playwright;
  2. use strict;
  3. use warnings;
  4. #ABSTRACT: Perl client for Playwright
  5. use 5.006;
  6. use v5.28.0; # Before 5.006, v5.10.0 would not be understood.
  7. use constant IS_WIN => $^O eq 'MSWin32';
  8. use File::ShareDir();
  9. use File::Basename();
  10. use Cwd();
  11. use LWP::UserAgent();
  12. use Sub::Install();
  13. use Net::EmptyPort();
  14. use JSON::MaybeXS();
  15. use File::Which();
  16. use Capture::Tiny qw{capture_merged capture_stderr};
  17. use Carp qw{confess};
  18. use Playwright::Base();
  19. use Playwright::Util();
  20. # Stuff closet full of skeletons at BEGIN time
  21. use Playwright::ModuleList();
  22. no warnings 'experimental';
  23. use feature qw{signatures};
  24. =head1 SYNOPSIS
  25. use Playwright;
  26. my $handle = Playwright->new();
  27. my $browser = $handle->launch( headless => 0, type => 'chrome' );
  28. my $page = $browser->newPage();
  29. my $res = $page->goto('http://somewebsite.test', { waitUntil => 'networkidle' });
  30. my $frameset = $page->mainFrame();
  31. my $kidframes = $frameset->childFrames();
  32. # Grab us some elements
  33. my $body = $page->select('body');
  34. # You can also get the innerText
  35. my $text = $body->textContent();
  36. $body->click();
  37. $body->screenshot();
  38. my $kids = $body->selectMulti('*');
  39. #Alternatively, use the new locator API instead of select/selectMulti:
  40. my $loc = $page->locator('body');
  41. my $innerTubes = $loc->allInnerTexts();
  42. print Dumper($innerTubes);
  43. # See a more full exploration of the API in example.pl on github.
  44. =head1 DESCRIPTION
  45. Perl interface to a lightweight node.js webserver that proxies commands runnable by Playwright.
  46. Checks and automatically installs a copy of the node dependencies in the local folder if needed.
  47. Currently understands commands you can send to all the playwright classes defined in api.json (installed wherever your OS puts shared files for CPAN distributions).
  48. See L<https://playwright.dev/versions> and drill down into your relevant version (run `npm list playwright` )
  49. for what the classes do, and their usage.
  50. All the classes mentioned there will correspond to a subclass of the Playwright namespace. For example:
  51. # ISA Playwright
  52. my $playwright = Playwright->new();
  53. # ISA Playwright::BrowserContext
  54. my $ctx = $playwright->newContext(...);
  55. # ISA Playwright::Page
  56. my $page = $ctx->newPage(...);
  57. # ISA Playwright::ElementHandle
  58. my $element = $ctx->select('body');
  59. See example.pl for a more thoroughly fleshed-out display on how to use this module.
  60. =head2 Getting Started
  61. When using the playwright module for the first time, you may be told to install node.js libraries.
  62. It should provide you with instructions which will get you working right away.
  63. However, depending on your node installation this may not work due to dependencies for node.js not being in the expected location.
  64. To fix this, you will need to update your NODE_PATH environment variable to point to the correct location.
  65. =head3 Node Versions
  66. playwright itself tends to need the latest version of node to work properly.
  67. It is recommended that you use nvm to get a hold of this:
  68. L<https://github.com/nvm-sh/nvm>
  69. From there it's recommended you use the latest version of node:
  70. nvm install node
  71. nvm use node
  72. =head2 Documentation for Playwright Subclasses
  73. The documentation and names for the subclasses of Playwright follow the spec strictly:
  74. Playwright::BrowserContext => L<https://playwright.dev/docs/api/class-browsercontext>
  75. Playwright::Page => L<https://playwright.dev/docs/api/class-page>
  76. Playwright::ElementHandle => L<https://playwright.dev/docs/api/class-elementhandle>
  77. ...And so on. These classes are automatically generated during module build based on the spec hash built by playwright.
  78. See generate_api_json.sh and generate_perl_modules.pl if you are interested in how this sausage is made.
  79. You can check what methods are installed for each subclass by doing the following:
  80. use Data::Dumper;
  81. print Dumper($instance->{spec});
  82. There are two major exceptions in how things work versus the upstream Playwright documentation, detailed below in the C<Selectors> section.
  83. =head2 Selectors
  84. The selector functions have to be renamed from starting with $ for obvious reasons.
  85. The renamed functions are as follows:
  86. =over 4
  87. =item $ => select
  88. =item $$ => selectMulti
  89. =item $eval => evaluate
  90. =item $$eval => evalMulti
  91. =back
  92. These functions are present as part of the Page, Frame and ElementHandle classes.
  93. =head2 Scripts
  94. The evaluate() and evaluateHandle() functions can only be run in string mode.
  95. To maximize the usefulness of these, I have wrapped the string passed with the following function:
  96. const fun = new Function (toEval);
  97. args = [
  98. fun,
  99. ...args
  100. ];
  101. As such you can effectively treat the script string as a function body.
  102. The same restriction on only being able to pass one arg remains from the upstream:
  103. L<https://playwright.dev/docs/api/class-page#pageevalselector-pagefunction-arg>
  104. You will have to refer to the arguments array as described here:
  105. L<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments>
  106. You can also pass Playwright::ElementHandle objects as returned by the select() and selectMulti() routines.
  107. They will be correctly translated into DOMNodes as you would get from the querySelector() javascript functions.
  108. Calling evaluate() and evaluateHandle() on Playwright::Element objects will automatically pass the DOMNode as the first argument to your script.
  109. See below for an example of doing this.
  110. =head3 example of evaluate()
  111. # Read the console
  112. $page->on('console',"return [...arguments]");
  113. my $promise = $page->waitForEvent('console');
  114. #TODO This request can race, the server framework I use to host the playwright spec is *not* FIFO (YET)
  115. sleep 1;
  116. $page->evaluate("console.log('hug')");
  117. my $console_log = $handle->await( $promise );
  118. print "Logged to console: '".$console_log->text()."'\n";
  119. # Convenient usage of evaluate on ElementHandles
  120. # We pass the element itself as the first argument to the JS arguments array for you
  121. $element->evaluate('arguments[0].style.backgroundColor = "#FF0000"; return 1;');
  122. =head2 Asynchronous operations
  123. The waitFor* methods defined on various classes fork and exec, waiting on the promise to complete.
  124. You will need to wait on the result of the backgrounded action with the await() method documented below.
  125. # Assuming $handle is a Playwright object
  126. my $async = $page->waitForEvent('console');
  127. $page->evaluate('console.log("whee")');
  128. my $result = $handle->await( $async );
  129. my $logged = $result->text();
  130. =head2 Getting Object parents
  131. Some things, like elements naturally are children of the pages in which they are found.
  132. Sometimes this can get confusing when you are using multiple pages, especially if you let the ref to the page go out of scope.
  133. Don't worry though, you can access the parent attribute on most Playwright::* objects:
  134. # Assuming $element is a Playwright::ElementHandle
  135. my $page = $element->{parent};
  136. =head2 Chrome Specific features
  137. You can pass the parameter 'cdp_uri' to the constructor to connect to a running browser with a ChromeDevTools server running.
  138. Example:
  139. ws://wegotussomebrowsers.test:666?user=fred&token=Y4BBAD4B3AD00
  140. This appears to be what the large scale playwright-as-a-service shops are using to expose browsers to their customers.
  141. For the curious as to how this actually works:
  142. Similar to the playwright_server binary this module ships, they use some kind of web service to wrap browser.newBrowserCDPSession().
  143. Alternatively, they wrap running `chromium-browser --remote-debugging-port=7779311` instead of touching pw, because complexity demon BAD.
  144. See the CDP: block in example.pl with this distribution (read: in the TLD of its repo) for how to do precisely that.
  145. It's nothing all that complicated, other than the hulking swarm of services which integrate that into a userland that can charge your credit card!
  146. Oh, and monitoring/balancing/scaling it all so that it doesn't fall over because you crammed 10 billion clients onto one box.
  147. Gotta stay right on the edge of utilization madness, that's the sweet spot as far as margin is concerned.
  148. =head2 Firefox Specific concerns
  149. By default, firefox will open PDFs in a pdf.js window.
  150. To suppress this behavior (such as in the event you are await()ing a download event), you will have to pass this option to launch():
  151. # Assuming $handle is a Playwright object
  152. my $browser = $handle->launch( type => 'firefox', firefoxUserPrefs => { 'pdfjs.disabled' => JSON::true } );
  153. =head2 Leaving browsers alive for manual debugging
  154. Passing the cleanup => 0 parameter to new() will prevent DESTROY() from cleaning up the playwright server when a playwright object goes out of scope.
  155. Be aware that this will prevent debug => 1 from printing extra messages from playwright_server itself, as we redirect the output streams in this case so as not to fill your current session with prints later.
  156. A convenience script has been provided to clean up these orphaned instances, `reap_playwright_servers` which will kill all extant `playwright_server` processes.
  157. =head2 Running multiple clients against the same playwright server
  158. To save on memory, this is a good idea. Pass the 'port' argument to the constructor, and we'll re-use anything listening on that port locally, and be sure to use it when starting up.
  159. This will also set the cleanup flag to false, so be sure you run `reap_playwright_servers` when you are sure that all testing on this server is done.
  160. =head2 Running against remote playwright servers
  161. Pass the 'host' along with the 'port' argument to the constructor in order to use an instance of playwright_server running on another host.
  162. This will naturally set the cleanup flag to false; it is the server operator's responsibility to reap the server when complete.
  163. A systemd service file, and Makefile are provided in the service/ folder of this module's git repository which will install playwright_server as a user-mode service on the PORT variable.
  164. =head2 Taking videos, Making Downloads
  165. We spawn browsers via BrowserType.launchServer() and then connect to them over websocket.
  166. This means you can't just set paths up front and have videos recorded, the Video.path() method will throw.
  167. Instead you will need to call the Video.saveAs() method after closing a page to record video:
  168. # Do stuff
  169. ...
  170. # Save video
  171. my $video = $page->video;
  172. $page->close();
  173. $video->saveAs('video/example.webm');
  174. It's a similar story with Download classes:
  175. # Do stuff
  176. ...
  177. # Wait on Download
  178. my $promise = $page->waitForEvent('download')
  179. # Do some thing triggering a download
  180. ...
  181. my $download = $handle->await( $promise );
  182. $download->saveAs('somefile.extension');
  183. Remember when doing an await() with playwright-perl you are waiting on a remote process on a server to complete, which can time out.
  184. You may wish to spawn a subprocess using a different tool to download very large files.
  185. If this is not an option, consider increasing the timeout on the LWP object used by the Playwright object (it's the 'ua' member of the class).
  186. =head2 Doing arbitrary requests
  187. When you either want to test APIs (or not look like a scraper/crawler) you'll want to issue arbitrary requests, such as POST/HEAD/DELETE et cetera.
  188. Here's how you go about that:
  189. print "HEAD http://google.com : \n";
  190. my $fr = $page->request();
  191. my $resp = $fr->fetch("http://google.com", { method => "HEAD" });
  192. print Dumper($resp->headers());
  193. print "200 OK\n" if $resp->status() == 200;
  194. The request() method will give you a Playwright::APIRequestContext object, which you can then call whichever methods you like upon.
  195. When you call fetch (or get, post, etc) you will then be returned a Playwright::APIResponse object.
  196. =head3 Differences in behavior from Selenium::Remote::Driver
  197. By default selenium has its selector methods obeying a timeout and waits for an element to appear.
  198. It then explodes when and element can't be found.
  199. To replicate this mode of operation, we have provided the try_until helper:
  200. # Args are $object, $method, @args
  201. my $element = Playwright::try_until($page, 'select', $selector) or die ...;
  202. This will use the timeouts described by pusht/popt (see below).
  203. =head2 Perl equivalents for playwright-test
  204. This section is intended to be read alongside the playwright-test documentation to aid understanding of common browser testing techniques.
  205. The relevant documentation section will be linked for each section.
  206. =head3 Annotations
  207. L<https://playwright.dev/docs/test-annotations/>
  208. Both L<Test::More> and L<Test2::V0> provide an equivalent to all the annotations but slow():
  209. =over 4
  210. =item B<skip or fixme> - Test::More::skip or Test2::Tools::Basic::skip handle both needs
  211. =item B<fail> - Test::More TODO blocks and Test2::Tools::Basic::todo
  212. =item B<slow> - Has no equivalent off the shelf. Playwright::pusht() and Playwright::popt() are here to help.
  213. # Examples assume you have a $page object.
  214. # Timeouts are in milliseconds
  215. Playwright::pusht($page,5000);
  216. # Do various things...
  217. ...
  218. Playwright::popt($page);
  219. See L<https://playwright.dev/docs/api/class-browsercontext#browser-context-set-default-timeout> for more on setting default timeouts in playwright.
  220. By default we assume the timeout to be 30s.
  221. =back
  222. =head3 Assertions
  223. As with before, most of the functionality here is satisfied with perl's default testing libraries.
  224. In particular, like() and cmp_bag() will do most of what you want here.
  225. =head3 Authentication
  226. Much of the callback functionality used in these sections is provided by L<Test::Class> and it's fixtures.
  227. =head3 Command Line
  228. Both C<prove> and C<yath> have similar functionality, save for retrying flaky tests.
  229. That said, you shouldn't do that; good tests don't flake.
  230. =head3 Configuration
  231. All the configuration here can simply be passed to launch(), newPage() or other methods directly.
  232. =head3 Page Objects
  233. This is basically what L<Test::Class> was written for specifically; so that you could subclass testing of common components across pages.
  234. =head3 Parallelizing Tests
  235. Look into L<Test::Class::Moose>'s Parallel runmode, C<prove>'s -j option, or L<Test2::Aggregate>.
  236. =head3 Reporters
  237. When using C<prove>, consider L<Test::Reporter> coupled with App::Prove::Plugins using custom TAP::Formatters.
  238. Test2 as of this writing (October 2012) supports formatters and plugins, but no formatter plugins have been uploaded to CPAN.
  239. See L<Test2::Manual::Tooling::Formatter> on writing a formatter yourself, and then a L<Test2::Plugin> using it.
  240. =head3 Test Retry
  241. C<prove> supports tests in sequence via the --rules option.
  242. It's also got the handy --state options to further micromanage test execution over multiple iterations.
  243. You can use this to retry flaking tests, but it's not a great idea in practice.
  244. =head3 Visual Comparisons
  245. Use L<Image::Compare>.
  246. =head3 Advanced Configuration
  247. This yet again can be handled when instantiating the various playwright objects.
  248. =head3 Fixtures
  249. L<Test::Class> and it's many variants cover the subject well.
  250. =head1 INSTALLATION NOTE
  251. If you install this module from CPAN, you will likely encounter a croak() telling you to install node module dependencies.
  252. Follow the instructions and things should be just fine.
  253. If you aren't, please file a bug!
  254. =head1 CONSTRUCTOR
  255. =head2 new(HASH) = (Playwright)
  256. Creates a new browser and returns a handle to interact with it.
  257. =head3 INPUT
  258. debug (BOOL) : Print extra messages from the Playwright server process. Default: false
  259. timeout (INTEGER) : Seconds to wait for the playwright server to spin up and down. Default: 30s
  260. cleanup (BOOL) : Whether or not to clean up the playwright server when this object goes out of scope. Default: true
  261. =cut
  262. our ( $spec, $server_bin, $node_bin, %mapper );
  263. sub _check_node {
  264. # Check that node is installed
  265. $node_bin = File::Which::which('node');
  266. confess("node must exist, be in your PATH and executable") unless $node_bin && -x $node_bin;
  267. my $path2here = File::Basename::dirname( Cwd::abs_path( $INC{'Playwright.pm'} ) );
  268. # Make sure it's possible to start the server
  269. $server_bin = File::Which::which('playwright_server');
  270. confess("Can't locate playwright_server!
  271. Please ensure it is installed in your PATH.
  272. If you installed this module from CPAN, it should already be.")
  273. unless $server_bin && -x $server_bin;
  274. # Attempt to start the server. If we can't do this, we almost certainly have dependency issues.
  275. my $output = '';
  276. if (IS_WIN) {
  277. $output = 'OK';
  278. } else {
  279. ($output) = capture_merged { system($node_bin, $server_bin, '--check') };
  280. }
  281. return if $output =~ m/OK/;
  282. warn $output if $output;
  283. confess( "playwright_server could not run successfully.
  284. See the above error message for why.
  285. It's likely to be unmet dependencies, or a NODE_PATH issue.
  286. Install of node dependencies must be done manually.
  287. Run the following:
  288. npm i express playwright uuid
  289. sudo npx playwright install-deps
  290. export NODE_PATH=\"\$(pwd)/node_modules\".
  291. If you still experience issues, run the following:
  292. NODE_DEBUG=module playwright_server --check
  293. This should tell you why node can't find the deps you have installed.
  294. ");
  295. }
  296. sub _build_classes {
  297. foreach my $class ( keys(%$spec) ) {
  298. $mapper{$class} = sub {
  299. my ( $self, $res ) = @_;
  300. my $class = "Playwright::$class";
  301. return $class->new(
  302. handle => $self,
  303. id => $res->{_guid},
  304. type => $class,
  305. parent => $self,
  306. );
  307. };
  308. }
  309. }
  310. sub BEGIN {
  311. our $SKIP_BEGIN;
  312. _check_node() unless $SKIP_BEGIN;
  313. }
  314. sub new ( $class, %options ) {
  315. #XXX yes, this is a race, so we need retries in _start_server
  316. my $port = $options{port} // Net::EmptyPort::empty_port();
  317. my $cdp_uri = $options{cdp_uri} // '';
  318. my $timeout = $options{timeout} // 30;
  319. my $self = bless(
  320. {
  321. ua => $options{ua} // LWP::UserAgent->new(),
  322. host => $options{host} // 'localhost',
  323. port => $port,
  324. cdp_uri => $cdp_uri,
  325. debug => $options{debug},
  326. cleanup => ( $options{cleanup} || !$options{port} || !$options{host} ) // 1,
  327. pid => $options{host} ? "REUSE" : _start_server( $port, $cdp_uri, $timeout, $options{debug}, $options{cleanup} // 1 ),
  328. parent => $$ // 'bogus', # Oh lawds, this can be undef sometimes
  329. timeout => $timeout,
  330. },
  331. $class,
  332. );
  333. $self->_check_and_build_spec();
  334. _build_classes();
  335. return $self;
  336. }
  337. sub _check_and_build_spec ($self) {
  338. return $spec if ref $spec eq 'HASH';
  339. $spec = Playwright::Util::request(
  340. 'GET', 'spec', $self->{host}, $self->{port}, $self->{ua},
  341. );
  342. confess("Could not retrieve Playwright specification. Check that your playwright installation is correct and complete.") unless ref $spec eq 'HASH';
  343. return $spec;
  344. }
  345. =head1 METHODS
  346. =head2 launch(HASH) = Playwright::Browser
  347. The Argument hash here is essentially those you'd see from browserType.launch(). See:
  348. L<https://playwright.dev/docs/api/class-browsertype#browsertypelaunchoptions>
  349. There is an additional "special" argument, that of 'type', which is used to specify what type of browser to use, e.g. 'firefox'.
  350. =cut
  351. sub launch ( $self, %args ) {
  352. Playwright::Base::_coerce(
  353. $spec->{BrowserType}{members},
  354. args => [ \%args ],
  355. command => 'launch'
  356. );
  357. delete $args{command};
  358. my $msg = Playwright::Util::request(
  359. 'POST', 'session', $self->{host}, $self->{port}, $self->{ua},
  360. type => delete $args{type},
  361. args => [ \%args ]
  362. );
  363. return $Playwright::mapper{ $msg->{_type} }->( $self, $msg )
  364. if ( ref $msg eq 'HASH' )
  365. && $msg->{_type}
  366. && exists $Playwright::mapper{ $msg->{_type} };
  367. return $msg;
  368. }
  369. =head2 server (HASH) = MIXED
  370. Call Playwright::BrowserServer methods on the server which launched your browser object.
  371. Parameters:
  372. browser : The Browser object you wish to call a server method upon.
  373. command : The BrowserServer method you wish to call
  374. The most common use for this is to get the PID of the underlying browser process:
  375. my $browser = $playwright->launch( browser => chrome );
  376. my $process = $playwright->server( browser => $browser, command => 'process' );
  377. print "Browser process PID: $process->{pid}\n";
  378. BrowserServer methods (at the time of writing) take no arguments, so they are not processed.
  379. =cut
  380. sub server ( $self, %args ) {
  381. return Playwright::Util::request(
  382. 'POST', 'server', $self->{host}, $self->{port}, $self->{ua},
  383. object => $args{browser}{guid},
  384. command => $args{command},
  385. );
  386. }
  387. =head2 await (HASH) = Object
  388. Waits for an asynchronous operation returned by the waitFor* methods to complete and returns the value.
  389. =cut
  390. sub await ( $self, $promise ) {
  391. my $obj = Playwright::Util::await($promise);
  392. return $obj unless $obj->{_type};
  393. my $class = "Playwright::$obj->{_type}";
  394. return $class->new(
  395. type => $obj->{_type},
  396. id => $obj->{_guid},
  397. handle => $self
  398. );
  399. }
  400. =head2 pusht(Playwright::Page, INTEGER timeout, BOOL navigation) = null
  401. Like pushd/popd, but for default timeouts used by a Playwright::Page object and it's children.
  402. If the 'navigation' option is high, we set the NavigationTimeout rather than the DefaultTimeout.
  403. By default 'navigation' is false.
  404. If we popt to the bottom of the stack, we will set the timeout back to 1 second.
  405. =cut
  406. sub pusht($object,$timeout, $navigation=0) {
  407. $object->{timeouts} //= [];
  408. push(@{$object->{timeouts}}, $timeout);
  409. return $object->setDefaultNavigationTimeout($timeout) if $navigation;
  410. return $object->setDefaultTimeout($timeout);
  411. }
  412. =head2 popt(Playwright::Page, BOOL navigation) = null
  413. The counterpart to pusht() which returns the timeout value to it's previous value.
  414. =cut
  415. sub popt ($object, $navigation=0) {
  416. $object->{timeouts} //= [];
  417. my $last_timeout = pop(@{$object->{timeouts}}) // 1000;
  418. return $object->setDefaultNavigationTimeout($last_timeout) if $navigation;
  419. return $object->setDefaultTimeout($last_timeout);
  420. }
  421. =head2 try_until(Object, STRING method, LIST args), try_until_die(...)
  422. Try to execute the provided method upon the provided Playwright::* object until it returns something truthy.
  423. Quits after the timeout (or 1s, if pusht is not used before this) defined on the object is reached.
  424. Use this for methods which *don't* support a timeout option, such as select().
  425. =cut
  426. sub try_until ($object, $method, @args) {
  427. my ($ctr, $result, $timeout) = (0);
  428. $timeout = $object->{timeouts}[-1] if ref $object->{timeouts} eq 'ARRAY';
  429. $timeout = $timeout / 1000 if $timeout;
  430. $timeout //= 1;
  431. while (!$result) {
  432. $result = $object->$method(@args);
  433. last if $result;
  434. sleep 1;
  435. $ctr++;
  436. last if $ctr >= $timeout;
  437. };
  438. return $result;
  439. }
  440. =head2 quit, DESTROY
  441. Terminate the browser session and wait for the Playwright server to terminate.
  442. Automatically called when the Playwright object goes out of scope.
  443. =cut
  444. sub quit ($self) {
  445. # Prevent double destroy after quit()
  446. return if $self->{killed};
  447. # Prevent destructor from firing in child processes so we can do things like async()
  448. # This should also prevent the waitpid below from deadlocking due to two processes waiting on the same pid.
  449. my $ppid = $$ // 'hokum'; # If $$ is undef both here and in the parent, let's just keep going
  450. return unless $ppid == $self->{parent};
  451. # Prevent destructor from firing in the event the caller instructs it to not fire
  452. return unless $self->{cleanup};
  453. # Make sure we don't mash the exit code of things like prove
  454. local $?;
  455. $self->{killed} = 1;
  456. print "Attempting to terminate server process...\n" if $self->{debug};
  457. Playwright::Util::request( 'GET', 'shutdown', $self->{host}, $self->{port}, $self->{ua} );
  458. return $self->_kill_playwright_server_windows() if IS_WIN;
  459. # 0 is always WCONTINUED, 1 is always WNOHANG, and POSIX is an expensive import
  460. # When 0 is returned, the process is still active, so it needs more persuasion
  461. foreach (0..3) {
  462. return unless waitpid( $self->{pid}, 1) == 0;
  463. sleep 1;
  464. }
  465. # Advanced persuasion
  466. print "Forcibly terminating server process...\n" if $self->{debug};
  467. kill('TERM', $self->{pid});
  468. #XXX unfortunately I can't just do a SIGALRM, because blocking system calls can't be intercepted on win32
  469. foreach (0..$self->{timeout}) {
  470. return unless waitpid( $self->{pid}, 1 ) == 0;
  471. sleep 1;
  472. }
  473. warn "Could not shut down playwright server!";
  474. return;
  475. }
  476. sub DESTROY ($self) {
  477. $self->quit();
  478. }
  479. sub _wait_port( $port, $timeout, $debug ) {
  480. # Check if the port is already live, and short-circuit if this is the case.
  481. if (IS_WIN) {
  482. my $result;
  483. for (0..$timeout) {
  484. my $result = qx{netstat -na | findstr "$port"};
  485. print "Waiting on port $port: $result\n" if $debug;
  486. last if $result;
  487. sleep 1;
  488. }
  489. return !!$result;
  490. }
  491. return Net::EmptyPort::wait_port( $port, $timeout )
  492. }
  493. sub _start_server ( $port, $cdp_uri, $timeout, $debug, $cleanup ) {
  494. $debug = $debug ? '--debug' : '';
  495. # Check if the port is already live, and short-circuit if this is the case.
  496. if ( _wait_port( $port, 1, $debug ) ) {
  497. print "Re-using playwright server on port $port...\n" if $debug;
  498. # Set the PID as something bogus, we don't really care as we won't kill it
  499. return "REUSE";
  500. }
  501. # On windows, the args will have to be handled slightly differently.
  502. my @args;
  503. if (IS_WIN) {
  504. push(@args, qq{"$node_bin"}, qq{"$server_bin"});
  505. } else {
  506. push(@args, $node_bin, $server_bin);
  507. }
  508. push(@args, ( "--port", $port ));
  509. push(@args, "--cdp", qq{"$cdp_uri"}) if $cdp_uri;
  510. push(@args, $debug) if $debug;
  511. $ENV{DEBUG} = 'pw:api' if $debug;
  512. return _start_server_windows( $port, $timeout, $debug, $cleanup, @args ) if IS_WIN;
  513. my $pid = fork // confess("Could not fork");
  514. if ($pid) {
  515. print "Waiting for playwright server on port $port to come up...\n" if $debug;
  516. Net::EmptyPort::wait_port( $port, $timeout )
  517. or confess("Server never came up after ".$timeout."s!");
  518. print "done\n" if $debug;
  519. return $pid;
  520. }
  521. # Orphan the process in the event that cleanup => 0
  522. if (!$cleanup) {
  523. print "Detaching child process...\n";
  524. chdir '/';
  525. require POSIX;
  526. die "Cannot detach playwright_server process for persistence" if POSIX::setsid() < 0;
  527. require Capture::Tiny;
  528. capture_merged { exec( @args ) };
  529. die("Could not exec!");
  530. }
  531. exec( @args );
  532. }
  533. sub _start_server_windows ( $port, $timeout, $debug, $cleanup, @args) {
  534. my $pid = qq/playwright-server:$port/;
  535. my @cmdprefix = ("start /MIN", qq{"$pid"});
  536. my $node_bin = File::Which::which('node');
  537. my $server_bin = File::Which::which('playwright_server');
  538. my $cmdstring = join(' ', @cmdprefix, @args );
  539. print "$cmdstring\n" if $debug;
  540. system($cmdstring);
  541. _wait_port( $port, $timeout, $debug );
  542. return $pid;
  543. }
  544. sub _kill_playwright_server_windows ($self) {
  545. my $killer = qq[taskkill /FI "WINDOWTITLE eq $self->{pid}"];
  546. print "$killer\n" if $self->{debug};
  547. system($killer);
  548. return 1;
  549. }
  550. 1;