Repository navigation
Expand file tree
/
Copy pathFileReader.php
More file actions
493 lines (454 loc) · 18.3 KB
/
Copy pathFileReader.php
File metadata and controls
493 lines (454 loc) · 18.3 KB
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
<?php
declare(strict_types=1);
namespace Componenta\Stdlib;
use Componenta\Stdlib\Exception\FileExceptionInterface;
use Componenta\Stdlib\Exception\FileCloseException;
use Componenta\Stdlib\Exception\FileLineSizeLimitException;
use Componenta\Stdlib\Exception\FileLockException;
use Componenta\Stdlib\Exception\FileReadException;
use Componenta\Stdlib\Exception\FileSizeLimitException;
use Componenta\Stdlib\Exception\FileUnavailableException;
use Componenta\Stdlib\Exception\InvalidFileException;
use Componenta\Stdlib\Exception\ResourceStreamReadException;
use Componenta\Stdlib\Exception\ResourceStreamReadSizeLimitException;
use Componenta\Stdlib\Exception\ResourceStreamReadLineSizeLimitException;
final class FileReader
{
private const int READ_CHUNK_BYTES = 65536;
private function __construct()
{
}
/**
* Read the entire file, or fail if it exceeds an explicitly supplied limit.
* Null means no caller-imposed byte limit.
*
* @throws FileExceptionInterface
* @throws \InvalidArgumentException If the limit is negative.
*/
public static function read(
string $path,
?int $maxBytes = null,
FileReadLock $lock = FileReadLock::None,
): string {
return self::collect(self::readChunks($path, maxBytes: $maxBytes, lock: $lock));
}
/**
* Read at most the requested number of bytes from the beginning.
*
* @throws FileExceptionInterface
* @throws \InvalidArgumentException If the limit is negative.
*/
public static function readPrefix(
string $path,
int $maxBytes,
FileReadLock $lock = FileReadLock::None,
): string {
return self::readRange($path, 0, $maxBytes, $lock);
}
/**
* Read a probe, then optionally extend it in bounded stages on the same opened file.
* The callback receives each complete prefix before maxBytes is reached.
* false stops, true reads the rest of the budget, an integer requests a
* strictly greater total prefix length not exceeding maxBytes.
* Do not acquire a conflicting lock in the callback.
*
* @param callable(string): (bool|int) $requiresMore
* @throws \InvalidArgumentException If a probe size or requested extent is invalid.
* @throws FileExceptionInterface
*/
public static function readAdaptivePrefix(
string $path,
int $probeBytes,
int $maxBytes,
callable $requiresMore,
FileReadLock $lock = FileReadLock::None,
): string {
if ($probeBytes < 1 || $probeBytes > $maxBytes) {
throw new \InvalidArgumentException('Probe size must be positive and no greater than the prefix budget.');
}
$target = $probeBytes;
$chunks = self::withFile(
$path,
$lock,
static function ($handle, int $size) use (&$target): \Generator {
$read = 0;
while ($read < $target) {
$end = $target;
$chunk = ResourceStreamReader::readPrefix($handle, $end - $read, ResourceStreamReadMode::Consume);
$read += strlen($chunk);
yield $chunk;
if ($read < $end) {
return;
}
}
},
);
$prefix = '';
foreach ($chunks as $chunk) {
$prefix .= $chunk;
if (strlen($prefix) === $target && $target < $maxBytes) {
try {
$decision = $requiresMore($prefix);
if (is_int($decision)) {
if ($decision <= $target || $decision > $maxBytes) {
throw new \InvalidArgumentException('Requested prefix must grow within the byte budget.');
}
$target = $decision;
} elseif ($decision) {
$target = $maxBytes;
}
} catch (\Throwable $error) {
// Preserve consumer failure if cleanup fails as well.
$chunks->throw($error);
throw $error;
}
}
}
return $prefix;
}
/**
* Read up to length bytes from a zero-based offset; a positive offset at
* or beyond the opened file's reported size returns an empty string.
*
* @throws FileExceptionInterface
* @throws \InvalidArgumentException If the offset or length is negative.
*/
public static function readRange(
string $path,
int $offset,
int $length,
FileReadLock $lock = FileReadLock::None,
): string {
self::requireNonnegative($offset);
self::requireNonnegative($length);
return self::collect(self::withFile(
$path,
$lock,
static function ($handle, int $size) use ($offset, $length): \Generator {
if ($length === 0 || ($offset > 0 && $offset >= $size)) {
return;
}
yield $offset > 0
? ResourceStreamReader::readRange($handle, $offset, $length, ResourceStreamReadMode::Consume)
: ResourceStreamReader::readPrefix($handle, $length, ResourceStreamReadMode::Consume);
},
));
}
/**
* Read at most length bytes ending at the opened file's reported size.
* Concurrent changes are not an atomic snapshot.
*
* @throws FileExceptionInterface
* @throws \InvalidArgumentException If the length is negative.
*/
public static function readTail(
string $path,
int $length,
FileReadLock $lock = FileReadLock::None,
): string {
self::requireNonnegative($length);
return self::collect(self::withFile(
$path,
$lock,
static function ($handle, int $size) use ($length): \Generator {
$length = min($size, $length);
if ($length === 0) {
return;
}
yield $size > $length
? ResourceStreamReader::readRange($handle, $size - $length, $length, ResourceStreamReadMode::Consume)
: ResourceStreamReader::readPrefix($handle, $length, ResourceStreamReadMode::Consume);
},
));
}
/**
* Lazily read the complete file in nonempty chunks. All except the last
* have exactly chunkSize bytes. A total byte limit is enforced throughout.
* The one-shot generator owns its handle and any lock until exhaustion or destruction.
*
* @return \Generator<int, string, mixed, void>
* @throws \InvalidArgumentException If the chunk size is not positive or the limit is negative.
* @throws FileExceptionInterface During iteration.
*/
public static function readChunks(
string $path,
int $chunkSize = self::READ_CHUNK_BYTES,
?int $maxBytes = null,
FileReadLock $lock = FileReadLock::None,
): \Generator {
if ($chunkSize < 1) {
throw new \InvalidArgumentException('The chunk size must be positive.');
}
self::requireNonnegative($maxBytes);
return self::withFile(
$path,
$lock,
static function ($handle, int $size) use ($chunkSize, $maxBytes): \Generator {
self::checkSize($size, $maxBytes);
return ResourceStreamReader::readChunks($handle, $chunkSize, $maxBytes, ResourceStreamReadMode::Consume, readAhead: true);
},
);
}
/**
* Lazily read the complete file as LF-delimited binary lines. LF and CRLF
* terminators are retained. A final unterminated line is returned as-is.
* Line limits include terminators; null means no caller-imposed limit.
*
* @return \Generator<int, string, mixed, void>
* @throws \InvalidArgumentException If either limit is negative.
* @throws FileExceptionInterface During iteration.
*/
public static function readLines(
string $path,
?int $maxBytes = null,
?int $maxLineBytes = null,
FileReadLock $lock = FileReadLock::None,
): \Generator {
self::requireNonnegative($maxBytes);
self::requireNonnegative($maxLineBytes);
return self::withFile(
$path,
$lock,
static function ($handle, int $size) use ($maxBytes, $maxLineBytes): \Generator {
self::checkSize($size, $maxBytes);
return ResourceStreamReader::readLines($handle, $maxBytes, $maxLineBytes, ResourceStreamReadMode::Consume);
},
);
}
/** @throws \InvalidArgumentException */
private static function requireNonnegative(?int $value): void
{
if ($value !== null && $value < 0) {
throw new \InvalidArgumentException('Byte counts and offsets must be nonnegative.');
}
}
/** @throws FileSizeLimitException */
private static function checkSize(int $size, ?int $maxBytes): void
{
if ($maxBytes !== null && $size > $maxBytes) {
throw new FileSizeLimitException($maxBytes);
}
}
/** @param iterable<int, string> $chunks */
private static function collect(iterable $chunks): string
{
$content = '';
foreach ($chunks as $chunk) {
$content .= $chunk;
}
return $content;
}
/**
* The handler is installed only around native calls, never around a yield.
*
* @param \Closure(resource, int): \Generator<int, string, mixed, void> $consume
* @return \Generator<int, string, mixed, void>
* @throws FileExceptionInterface
*/
private static function withFile(string $path, FileReadLock $lock, \Closure $consume): \Generator
{
if ($path === '' || str_contains($path, "\0") || str_contains($path, '://')
|| strncasecmp($path, 'data:', 5) === 0) {
throw new InvalidFileException('Expected a local file path.');
}
// Native PHP function availability is fixed for the process.
static $capabilitiesChecked = false;
if (!$capabilitiesChecked) {
foreach (['fopen', 'fstat', 'stat', 'realpath', 'clearstatcache', 'fclose',
'set_error_handler', 'restore_error_handler'] as $function) {
if (!function_exists($function)) {
throw new FileReadException('Required native file function is unavailable: ' . $function);
}
}
$capabilitiesChecked = true;
}
$handle = null;
$failure = null;
try {
set_error_handler(self::nativeWarning(...), E_WARNING | E_NOTICE);
try {
[$resolved, $device, $inode] = self::resolve($path);
// Nonblocking open on POSIX avoids blocking on a substituted FIFO.
$handle = fopen($resolved, PHP_OS_FAMILY === 'Windows' ? 'rb' : 'rbn');
if ($handle === false) {
throw new FileReadException('Unable to open file.');
}
$size = self::inspect($handle, $device, $inode);
if ($lock !== FileReadLock::None) {
self::acquireLock($handle, $lock);
// A cooperating writer may have changed the file while we
// waited. Reinspect the locked handle, never the path.
$size = self::inspect($handle, $device, $inode);
}
} catch (\ErrorException|\ValueError $error) {
throw new FileReadException('Unable to open or inspect file.', previous: $error);
} finally {
restore_error_handler();
}
try {
foreach ($consume($handle, $size) as $key => $chunk) {
try {
yield $key => $chunk;
} catch (\Throwable $error) {
// Exceptions injected by the consumer are not native read
// failures, even when they implement the dependency contract.
$failure = $error;
throw $error;
}
}
} catch (ResourceStreamReadSizeLimitException|ResourceStreamReadLineSizeLimitException|ResourceStreamReadException $error) {
if ($failure === $error) {
throw $error;
}
throw match (true) {
$error instanceof ResourceStreamReadSizeLimitException => new FileSizeLimitException($error->maxBytes),
$error instanceof ResourceStreamReadLineSizeLimitException => new FileLineSizeLimitException($error->maxLineBytes),
// Keep the original native cause, without exposing a new
// dependency exception as part of the public file contract.
default => new FileReadException($error->getMessage(), previous: $error->getPrevious()),
};
}
} catch (\Throwable $error) {
$failure = $error;
throw $error;
} finally {
if (is_resource($handle)) {
self::close($handle, $failure);
}
}
}
/**
* Called inside the native warning scope of withFile().
*
* @param resource $handle
* @return non-negative-int
* @throws FileExceptionInterface
*/
private static function inspect($handle, int $device, int $inode): int
{
$stat = fstat($handle);
if ($stat === false) {
throw new FileReadException('Unable to inspect opened file.');
}
if (($stat['mode'] & 0170000) !== 0100000) {
throw new InvalidFileException('Source is not a regular file.');
}
if ($stat['dev'] !== $device || $stat['ino'] !== $inode) {
throw new FileReadException('File changed during opening.');
}
return max(0, $stat['size']);
}
/**
* Called inside the native warning scope of withFile().
* Closing the owned descriptor releases its lock.
*
* @param resource $handle
* @throws FileLockException
*/
private static function acquireLock($handle, FileReadLock $lock): void
{
$operation = match ($lock) {
FileReadLock::None => 0,
FileReadLock::Shared => LOCK_SH,
FileReadLock::SharedNonBlocking => LOCK_SH | LOCK_NB,
};
if ($operation === 0) {
return;
}
// Locking is optional. A disabled native function must not break
// unlocked reads or leak an undefined-function Error to the caller.
if (!function_exists('flock')) {
throw new FileLockException();
}
$wouldBlock = 0;
try {
$acquired = flock($handle, $operation, $wouldBlock);
} catch (\ErrorException|\ValueError $error) {
throw new FileLockException(previous: $error);
}
if (!$acquired) {
throw new FileLockException(
wouldBlock: $lock === FileReadLock::SharedNonBlocking && $wouldBlock === 1,
);
}
}
/**
* @param resource $handle
* @throws FileCloseException
*/
private static function close($handle, ?\Throwable $failure): void
{
set_error_handler(self::nativeWarning(...), E_WARNING | E_NOTICE);
try {
$closed = fclose($handle);
} catch (\Throwable $error) {
if ($failure !== null || $error instanceof \ErrorException || $error instanceof \ValueError) {
throw new FileCloseException('Unable to close file.', previous: $error, readFailure: $failure);
}
throw $error;
} finally {
restore_error_handler();
}
if (!$closed) {
throw new FileCloseException('Unable to close file.', readFailure: $failure);
}
}
private static function nativeWarning(int $severity, string $message): never
{
throw new \ErrorException($message, 0, $severity);
}
/**
* @return array{string, int, int} Resolved path, device and inode.
* @throws FileExceptionInterface
*/
private static function resolve(string $path): array
{
// stat() checks the requested path rather than a cached canonical path.
clearstatcache(true, $path);
try {
$stat = stat($path);
if ($stat === false) {
throw new FileUnavailableException('File does not exist or cannot be accessed.');
}
} catch (\ErrorException|\ValueError $error) {
throw new FileUnavailableException('File does not exist or cannot be accessed.', previous: $error);
}
if (($stat['mode'] & 0170000) !== 0100000) {
throw new InvalidFileException('Source is not a regular file.');
}
$device = $stat['dev'];
$inode = $stat['ino'];
if ($inode === 0) {
// Some filesystems do not provide useful inode identifiers.
clearstatcache(true);
}
try {
$resolved = self::resolveMatchingPath($path, $device, $inode);
} catch (FileUnavailableException) {
// An ancestor symlink can remain cached after clearing the exact path.
clearstatcache(true);
$resolved = self::resolveMatchingPath($path, $device, $inode);
}
return [$resolved, $device, $inode];
}
/** @throws FileUnavailableException */
private static function resolveMatchingPath(string $path, int $device, int $inode): string
{
try {
$resolved = realpath($path);
if ($resolved === false) {
throw new FileUnavailableException('File does not exist or cannot be accessed.');
}
if ($resolved !== $path) {
$stat = stat($resolved);
if ($stat === false || ($stat['mode'] & 0170000) !== 0100000
|| $stat['dev'] !== $device || $stat['ino'] !== $inode) {
throw new FileUnavailableException('File changed during path resolution.');
}
}
} catch (\ErrorException|\ValueError $error) {
throw new FileUnavailableException('File does not exist or cannot be accessed.', previous: $error);
}
return $resolved;
}
}