1. <?php
  2. /**
  3. * Encodes queue output with a timeout for hypothesis validation.
  4. *
  5. * @param callable $queue_callback A callable representing the queue processing function.
  6. * @param int $timeout Timeout in seconds.
  7. * @return array|false An array containing the output or false on timeout.
  8. */
  9. function encodeQueueOutputWithTimeout(callable $queue_callback, int $timeout): array|false
  10. {
  11. $handle = proc_open(
  12. 'php ' . escapeshellarg(__FILE__) . ' encode_queue_output', // Execute this script as a separate process
  13. [
  14. 0 => ['pipe', 'r'], // stdin
  15. 1 => ['pipe', 'w'], // stdout
  16. 2 => ['pipe', 'w'], // stderr
  17. ],
  18. $pipes
  19. );
  20. if ($handle === false) {
  21. return false; // Error creating process
  22. }
  23. // Send the queue processing arguments to the subprocess
  24. fwrite($pipes[0], serialize($queue_callback)); // Pass the queue callback as a serialized string
  25. fclose($pipes[0]);
  26. $startTime = time();
  27. $output = '';
  28. while ($line = fgets($pipes[1])) {
  29. $output .= $line;
  30. if (time() - $startTime > $timeout) {
  31. fclose($pipes[1]);
  32. break; // Timeout reached
  33. }
  34. }
  35. fclose($pipes[1]);
  36. fclose($pipes[2]);
  37. $return_value = proc_close($handle);
  38. if ($return_value !== 0) {
  39. return false; //Process failed
  40. }
  41. return unserialize($output); // Return the decoded output
  42. }
  43. /**
  44. * Helper function to encode queue output.
  45. * This function is executed in a separate process.
  46. *
  47. * @param mixed $queue_callback The queue processing function (serialized).
  48. * @return string|false The encoded output or false on error.
  49. */
  50. function encode_queue_output($queue_callback)
  51. {
  52. // Execute the queue callback. Capture output.
  53. $result = $queue_callback();
  54. if ($result === false) {
  55. return false;
  56. }
  57. // Encode the result to JSON
  58. $encoded_output = json_encode($result, JSON_PRETTY_PRINT);
  59. if ($encoded_output === false) {
  60. return false; //JSON encoding error
  61. }
  62. return $encoded_output;
  63. }
  64. ?>

Add your comment