-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathFileStorage.php
374 lines (296 loc) · 8.4 KB
/
FileStorage.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Caching\Storages;
use Nette;
use Nette\Caching\Cache;
/**
* Cache file storage.
*/
class FileStorage implements Nette\Caching\Storage
{
/**
* Atomic thread safe logic:
*
* 1) reading: open(r+b), lock(SH), read
* - delete?: delete*, close
* 2) deleting: delete*
* 3) writing: open(r+b || wb), lock(EX), truncate*, write data, write meta, close
*
* delete* = try unlink, if fails (on NTFS) { lock(EX), truncate, close, unlink } else close (on ext3)
*/
/** @internal cache file structure: meta-struct size + serialized meta-struct + data */
private const
MetaHeaderLen = 6,
// meta structure: array of
MetaTime = 'time', // timestamp
MetaSerialized = 'serialized', // is content serialized?
MetaExpire = 'expire', // expiration timestamp
MetaDelta = 'delta', // relative (sliding) expiration
MetaItems = 'di', // array of dependent items (file => timestamp)
MetaCallbacks = 'callbacks'; // array of callbacks (function, args)
/** additional cache structure */
private const
File = 'file',
Handle = 'handle';
/** probability that the clean() routine is started */
public static float $gcProbability = 0.001;
private string $dir;
private ?Journal $journal;
private array $locks;
public function __construct(string $dir, ?Journal $journal = null)
{
if (!is_dir($dir) || !Nette\Utils\FileSystem::isAbsolute($dir)) {
throw new Nette\DirectoryNotFoundException("Directory '$dir' not found or is not absolute.");
}
$this->dir = $dir;
$this->journal = $journal;
if (mt_rand() / mt_getrandmax() < static::$gcProbability) {
$this->clean([]);
}
}
public function read(string $key): mixed
{
$meta = $this->readMetaAndLock($this->getCacheFile($key), LOCK_SH);
return $meta && $this->verify($meta)
? $this->readData($meta) // calls fclose()
: null;
}
/**
* Verifies dependencies.
*/
private function verify(array $meta): bool
{
do {
if (!empty($meta[self::MetaDelta])) {
// meta[file] was added by readMetaAndLock()
if (filemtime($meta[self::File]) + $meta[self::MetaDelta] < time()) {
break;
}
touch($meta[self::File]);
} elseif (!empty($meta[self::MetaExpire]) && $meta[self::MetaExpire] < time()) {
break;
}
if (!empty($meta[self::MetaCallbacks]) && !Cache::checkCallbacks($meta[self::MetaCallbacks])) {
break;
}
if (!empty($meta[self::MetaItems])) {
foreach ($meta[self::MetaItems] as $depFile => $time) {
$m = $this->readMetaAndLock($depFile, LOCK_SH);
if (($m[self::MetaTime] ?? null) !== $time || ($m && !$this->verify($m))) {
break 2;
}
}
}
return true;
} while (false);
$this->delete($meta[self::File], $meta[self::Handle]); // meta[handle] & meta[file] was added by readMetaAndLock()
return false;
}
public function lock(string $key): void
{
$cacheFile = $this->getCacheFile($key);
if (!is_dir($dir = dirname($cacheFile))) {
@mkdir($dir); // @ - directory may already exist
}
$handle = fopen($cacheFile, 'c+b');
if (!$handle) {
return;
}
$this->locks[$key] = $handle;
flock($handle, LOCK_EX);
}
public function write(string $key, $data, array $dp): void
{
$meta = [
self::MetaTime => microtime(),
];
if (isset($dp[Cache::Expire])) {
if (empty($dp[Cache::Sliding])) {
$meta[self::MetaExpire] = $dp[Cache::Expire] + time(); // absolute time
} else {
$meta[self::MetaDelta] = (int) $dp[Cache::Expire]; // sliding time
}
}
if (isset($dp[Cache::Items])) {
foreach ($dp[Cache::Items] as $item) {
$depFile = $this->getCacheFile($item);
$m = $this->readMetaAndLock($depFile, LOCK_SH);
$meta[self::MetaItems][$depFile] = $m[self::MetaTime] ?? null;
unset($m);
}
}
if (isset($dp[Cache::Callbacks])) {
$meta[self::MetaCallbacks] = $dp[Cache::Callbacks];
}
if (!isset($this->locks[$key])) {
$this->lock($key);
if (!isset($this->locks[$key])) {
return;
}
}
$handle = $this->locks[$key];
unset($this->locks[$key]);
$cacheFile = $this->getCacheFile($key);
if (isset($dp[Cache::Tags]) || isset($dp[Cache::Priority])) {
if (!$this->journal) {
throw new Nette\InvalidStateException('CacheJournal has not been provided.');
}
$this->journal->write($cacheFile, $dp);
}
ftruncate($handle, 0);
if (!is_string($data)) {
$data = serialize($data);
$meta[self::MetaSerialized] = true;
}
$head = serialize($meta);
$head = str_pad((string) strlen($head), 6, '0', STR_PAD_LEFT) . $head;
$headLen = strlen($head);
do {
if (fwrite($handle, str_repeat("\x00", $headLen)) !== $headLen) {
break;
}
if (fwrite($handle, $data) !== strlen($data)) {
break;
}
fseek($handle, 0);
if (fwrite($handle, $head) !== $headLen) {
break;
}
flock($handle, LOCK_UN);
fclose($handle);
return;
} while (false);
$this->delete($cacheFile, $handle);
}
public function remove(string $key): void
{
unset($this->locks[$key]);
$this->delete($this->getCacheFile($key));
}
public function clean(array $conditions): void
{
$all = !empty($conditions[Cache::All]);
$collector = empty($conditions);
$namespaces = $conditions[Cache::Namespaces] ?? null;
// cleaning using file iterator
if ($all || $collector) {
$now = time();
foreach (Nette\Utils\Finder::find('_*')->from($this->dir)->childFirst() as $entry) {
$path = (string) $entry;
if ($entry->isDir()) { // collector: remove empty dirs
@rmdir($path); // @ - removing dirs is not necessary
continue;
}
if ($all) {
$this->delete($path);
} else { // collector
$meta = $this->readMetaAndLock($path, LOCK_SH);
if (!$meta) {
continue;
}
if ((!empty($meta[self::MetaDelta]) && filemtime($meta[self::File]) + $meta[self::MetaDelta] < $now)
|| (!empty($meta[self::MetaExpire]) && $meta[self::MetaExpire] < $now)
) {
$this->delete($path, $meta[self::Handle]);
continue;
}
flock($meta[self::Handle], LOCK_UN);
fclose($meta[self::Handle]);
}
}
if ($this->journal) {
$this->journal->clean($conditions);
}
return;
} elseif ($namespaces) {
foreach ($namespaces as $namespace) {
$dir = $this->dir . '/_' . urlencode($namespace);
if (!is_dir($dir)) {
continue;
}
foreach (Nette\Utils\Finder::findFiles('_*')->in($dir) as $entry) {
$this->delete((string) $entry);
}
@rmdir($dir); // may already contain new files
}
}
// cleaning using journal
if ($this->journal) {
foreach ($this->journal->clean($conditions) as $file) {
$this->delete($file);
}
}
}
/**
* Reads cache data from disk.
*/
protected function readMetaAndLock(string $file, int $lock): ?array
{
$handle = @fopen($file, 'r+b'); // @ - file may not exist
if (!$handle) {
return null;
}
flock($handle, $lock);
$size = (int) stream_get_contents($handle, self::MetaHeaderLen);
if ($size) {
$meta = stream_get_contents($handle, $size, self::MetaHeaderLen);
$meta = unserialize($meta);
$meta[self::File] = $file;
$meta[self::Handle] = $handle;
return $meta;
}
flock($handle, LOCK_UN);
fclose($handle);
return null;
}
/**
* Reads cache data from disk and closes cache file handle.
*/
protected function readData(array $meta): mixed
{
$data = stream_get_contents($meta[self::Handle]);
flock($meta[self::Handle], LOCK_UN);
fclose($meta[self::Handle]);
return empty($meta[self::MetaSerialized]) ? $data : unserialize($data);
}
/**
* Returns file name.
*/
protected function getCacheFile(string $key): string
{
$file = urlencode($key);
if ($a = strrpos($file, '%00')) { // %00 = urlencode(Nette\Caching\Cache::NamespaceSeparator)
$file = substr_replace($file, '/_', $a, 3);
}
return $this->dir . '/_' . $file;
}
/**
* Deletes and closes file.
* @param resource $handle
*/
private static function delete(string $file, $handle = null): void
{
if (@unlink($file)) { // @ - file may not already exist
if ($handle) {
flock($handle, LOCK_UN);
fclose($handle);
}
return;
}
if (!$handle) {
$handle = @fopen($file, 'r+'); // @ - file may not exist
}
if (!$handle) {
return;
}
flock($handle, LOCK_EX);
ftruncate($handle, 0);
flock($handle, LOCK_UN);
fclose($handle);
@unlink($file); // @ - file may not already exist
}
}