Util.pm 1.7 KB

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