<?php
/**
* Encodes queue output with a timeout for hypothesis validation.
*
* @param callable $queue_callback A callable representing the queue processing function.
* @param int $timeout Timeout in seconds.
* @return array|false An array containing the output or false on timeout.
*/
function encodeQueueOutputWithTimeout(callable $queue_callback, int $timeout): array|false
{
$handle = proc_open(
'php ' . escapeshellarg(__FILE__) . ' encode_queue_output', // Execute this script as a separate process
[
0 => ['pipe', 'r'], // stdin
1 => ['pipe', 'w'], // stdout
2 => ['pipe', 'w'], // stderr
],
$pipes
);
if ($handle === false) {
return false; // Error creating process
}
// Send the queue processing arguments to the subprocess
fwrite($pipes[0], serialize($queue_callback)); // Pass the queue callback as a serialized string
fclose($pipes[0]);
$startTime = time();
$output = '';
while ($line = fgets($pipes[1])) {
$output .= $line;
if (time() - $startTime > $timeout) {
fclose($pipes[1]);
break; // Timeout reached
}
}
fclose($pipes[1]);
fclose($pipes[2]);
$return_value = proc_close($handle);
if ($return_value !== 0) {
return false; //Process failed
}
return unserialize($output); // Return the decoded output
}
/**
* Helper function to encode queue output.
* This function is executed in a separate process.
*
* @param mixed $queue_callback The queue processing function (serialized).
* @return string|false The encoded output or false on error.
*/
function encode_queue_output($queue_callback)
{
// Execute the queue callback. Capture output.
$result = $queue_callback();
if ($result === false) {
return false;
}
// Encode the result to JSON
$encoded_output = json_encode($result, JSON_PRETTY_PRINT);
if ($encoded_output === false) {
return false; //JSON encoding error
}
return $encoded_output;
}
?>
Add your comment