Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use lock to fix race condition in cache #8240

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 32 additions & 2 deletions src/Psalm/Internal/Provider/ParserCacheProvider.php
Expand Up @@ -8,9 +8,14 @@
use RuntimeException;

use function error_log;
use function fclose;
use function file_get_contents;
use function file_put_contents;
use function filemtime;
use function filesize;
use function flock;
use function fopen;
use function fread;
use function gettype;
use function igbinary_serialize;
use function igbinary_unserialize;
Expand All @@ -28,9 +33,12 @@
use function trigger_error;
use function unlink;
use function unserialize;
use function usleep;

use const DIRECTORY_SEPARATOR;
use const E_USER_ERROR;
use const LOCK_EX;
use const LOCK_SH;
use const SCANDIR_SORT_NONE;

/**
Expand Down Expand Up @@ -184,7 +192,28 @@ private function getExistingFileContentHashes(): array
$file_hashes_path = $root_cache_directory . DIRECTORY_SEPARATOR . self::FILE_HASHES;

if ($root_cache_directory && is_readable($file_hashes_path)) {
$hashes_encoded = (string) file_get_contents($file_hashes_path);
$fp = fopen($file_hashes_path, 'r');
$max_wait_cycles = 5;
$has_lock = false;
while ($max_wait_cycles > 0) {
if (flock($fp, LOCK_SH)) {
$has_lock = true;
break;
}
$max_wait_cycles--;
usleep(50000);
}

if (!$has_lock) {
fclose($fp);
error_log('Could not acquire lock for content hashes file');
$this->existing_file_content_hashes = [];

return [];
}

$hashes_encoded = fread($fp, filesize($file_hashes_path));
fclose($fp);

if (!$hashes_encoded) {
error_log('Unexpected value when loading from file content hashes');
Expand Down Expand Up @@ -281,7 +310,8 @@ public function saveFileContentHashes(): void

file_put_contents(
$file_hashes_path,
json_encode($file_content_hashes)
json_encode($file_content_hashes),
LOCK_EX
);
}

Expand Down