Util.pm 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package Playwright::Util;
  2. use strict;
  3. use warnings;
  4. use v5.28;
  5. use JSON::MaybeXS();
  6. use Carp qw{confess};
  7. use Sereal::Encoder;
  8. use Sereal::Decoder;
  9. use File::Temp;
  10. use POSIX();
  11. #ABSTRACT: Common utility functions for the Playwright module
  12. no warnings 'experimental';
  13. use feature qw{signatures};
  14. =head2 request(STRING method, STRING url, INTEGER port, LWP::UserAgent ua, HASH args) = HASH
  15. De-duplicates request logic in the Playwright Modules.
  16. =cut
  17. sub request ( $method, $url, $port, $ua, %args ) {
  18. my $fullurl = "http://localhost:$port/$url";
  19. my $request = HTTP::Request->new( $method, $fullurl );
  20. $request->header( 'Content-type' => 'application/json' );
  21. $request->content( JSON::MaybeXS::encode_json( \%args ) );
  22. my $response = $ua->request($request);
  23. my $content = $response->decoded_content();
  24. my $decoded = JSON::MaybeXS::decode_json($content);
  25. my $msg = $decoded->{message};
  26. confess($msg) if $decoded->{error};
  27. return $msg;
  28. }
  29. sub arr2hash ($array,$primary_key) {
  30. my $inside_out = {};
  31. @$inside_out{map { $_->{$primary_key} } @$array} = @$array;
  32. return $inside_out;
  33. }
  34. # Serialize a subprocess because NOTHING ON CPAN DOES THIS GRRRRR
  35. sub async ($subroutine) {
  36. # The fork would result in the tmpdir getting whacked when it terminates.
  37. my (undef, $filename) = File::Temp::tempfile();
  38. my $pid = fork() // die "Could not fork";
  39. _child($filename, $subroutine) unless $pid;
  40. return { pid => $pid, file => $filename };
  41. }
  42. sub _child ($filename,$subroutine) {
  43. Sereal::Encoder->encode_to_file($filename,$subroutine->());
  44. # Prevent destructors from firing due to exiting instantly
  45. POSIX::_exit(0);
  46. }
  47. sub await ($to_wait) {
  48. waitpid($to_wait->{pid},0);
  49. return Sereal::Decoder->decode_from_file($to_wait->{file});
  50. }
  51. 1;