Skip to content

Commit 55325fe

Browse files
committed
Make run-tests.php check for tcp fwrite edge cases
When the recipient is busy or the payload is large, fwrite can block or return a value smaller than the length of the stream. workers in run-tests.php communicates over tcp sockets with the manager. https://cirrus-ci.com/task/5315675320221696?logs=tests#L130 showed notices for fwrite/unserialize This is a similar approach to that used in https://github.com/phan/phan/blob/v5/src/Phan/LanguageServer/ProtocolStreamWriter.php for the tcp language server writing.
1 parent 3331832 commit 55325fe

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

run-tests.php

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1645,11 +1645,46 @@ function run_all_tests_parallel(array $test_files, array $env, $redir_tested): v
16451645
}
16461646
}
16471647

1648+
/**
1649+
* Calls fwrite and retries when network writes fail with errors such as "Resource temporarily unavailable"
1650+
*
1651+
* @param resource $stream the stream to fwrite to
1652+
* @param string $data
1653+
* @return int|false
1654+
*/
1655+
function safe_fwrite($stream, string $data)
1656+
{
1657+
// safe_fwrite was tested by adding $message['unused'] = str_repeat('a', 20_000_000); in send_message()
1658+
// fwrites on tcp sockets can return false or less than strlen if the recipient is busy.
1659+
// (e.g. fwrite(): Send of 577 bytes failed with errno=35 Resource temporarily unavailable)
1660+
$bytes_written = 0;
1661+
$retry_attempts = 0;
1662+
while ($bytes_written < strlen($data)) {
1663+
$n = @fwrite($stream, substr($data, $bytes_written));
1664+
if ($n === false) {
1665+
if ($retry_attempts >= 10) {
1666+
echo "ERROR: send_message() Failed to write chunk after 10 retries: " . error_get_last()['message'] . "\n";
1667+
return false;
1668+
}
1669+
$write_streams = [$stream];
1670+
$read_streams = [];
1671+
$except_streams = [];
1672+
/* Wait for a second and retry up to 10 times. Use a finite timeout and retry count in case stream_select returns inaccurate values or returns immediately. */
1673+
stream_select($read_streams, $write_streams, $except_streams, 1);
1674+
$retry_attempts++;
1675+
continue;
1676+
}
1677+
$bytes_written += $n;
1678+
$retry_attempts = 0;
1679+
}
1680+
return $bytes_written;
1681+
}
1682+
16481683
function send_message($stream, array $message): void
16491684
{
16501685
$blocking = stream_get_meta_data($stream)["blocked"];
16511686
stream_set_blocking($stream, true);
1652-
fwrite($stream, base64_encode(serialize($message)) . "\n");
1687+
safe_fwrite($stream, base64_encode(serialize($message)) . "\n");
16531688
stream_set_blocking($stream, $blocking);
16541689
}
16551690

0 commit comments

Comments
 (0)