Skip to content

Commit cc72614

Browse files
authored
fix: race condition for file writes (GoogleCloudPlatform#1461)
1 parent 31f5423 commit cc72614

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

functions/tips_scopes/index.php

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,19 @@ function scopeDemo(ServerRequestInterface $request): string
4242

4343
$response = '';
4444
if (file_exists($cachePath)) {
45-
// Read cached value from file
45+
// Read cached value from file, using file locking to prevent race
46+
// conditions between function executions.
4647
$response .= "Reading cached value." . PHP_EOL;
47-
$instanceVar = file_get_contents($cachePath);
48+
$fh = fopen($cachePath, 'r');
49+
flock($fh, LOCK_EX);
50+
$instanceVar = stream_get_contents($fh);
51+
flock($fh, LOCK_UN);
4852
} else {
49-
// Compute cached value + write to file
53+
// Compute cached value + write to file, using file locking to prevent
54+
// race conditions between function executions.
5055
$response .= "Cache empty, computing value." . PHP_EOL;
5156
$instanceVar = _heavyComputation();
52-
file_put_contents($cachePath, $instanceVar);
57+
file_put_contents($cachePath, $instanceVar, LOCK_EX);
5358
}
5459

5560
// Lighter computations can re-run on each function invocation.

0 commit comments

Comments
 (0)