Repository navigation
Expand file tree
/
Copy pathignition.php
More file actions
765 lines (645 loc) · 21.6 KB
/
Copy pathignition.php
File metadata and controls
765 lines (645 loc) · 21.6 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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
<?php
/*
* Nytris Ignition
* Copyright (c) Dan Phillimore (asmblah)
* https://github.com/nytris/ignition/
*
* Released under the MIT license.
* https://github.com/nytris/ignition/raw/main/MIT-LICENSE.txt
*/
declare(strict_types=1);
/*
* Entrypoint for Nytris Ignition.
*
* Intended to be included as the very first statement in an entrypoint PHP script,
* e.g. a front controller, followed by a call to ::start(...) - see README for details.
*
* Contains core classes required in the pre-Composer-autoloader environment,
* caching filesystem hits and also defining a minimal autoloader of its own.
*/
namespace Nytris\Ignition\Filesystem {
use Nytris\Ignition\Ignition;
use RuntimeException;
/**
* Class StreamWrapper.
*
* A stream wrapper that records filesystem stats during early Nytris boot.
*
* @author Dan Phillimore <dan@ovms.co>
*/
class StreamWrapper
{
public const PROTOCOL = 'file';
/**
* @var resource|null
*/
public $context;
private ?string $path = null;
/**
* @var resource|null
*/
private $wrappedResource;
public static function register(): void
{
stream_wrapper_unregister(static::PROTOCOL);
stream_wrapper_register(static::PROTOCOL, static::class);
}
/**
* @return resource|false
*/
public function stream_cast(int $cast_as)
{
return false;
}
public function stream_close(): void
{
if (!$this->wrappedResource) {
return;
}
fclose($this->wrappedResource);
$this->path = null;
$this->wrappedResource = null;
}
public function stream_eof(): bool
{
if (!$this->wrappedResource) {
return false;
}
return feof($this->wrappedResource);
}
public function stream_flush(): bool
{
if (!$this->wrappedResource) {
return false;
}
return fflush($this->wrappedResource);
}
public function stream_open(
string $path,
string $mode,
int $options,
?string &$openedPath
): bool {
$useIncludePath = (bool)($options & STREAM_USE_PATH);
$stream = $this->unwrapped(fn () => fopen($path, $mode, use_include_path: $useIncludePath));
if ($stream === false) {
return false;
}
$this->path = $path;
$this->wrappedResource = $stream;
if ($useIncludePath) {
$metaData = stream_get_meta_data($stream);
$openedPath = $metaData['uri'];
}
return true;
}
public function stream_read(int $count): string|false
{
if (!$this->wrappedResource) {
return false;
}
return fread($this->wrappedResource, $count);
}
public function stream_seek(int $offset, int $whence = SEEK_SET): bool
{
if (!$this->wrappedResource) {
return false;
}
return fseek($this->wrappedResource, $offset, $whence) !== -1;
}
public function stream_set_option(int $option, int $arg1, int|null $arg2): bool
{
if (!$this->wrappedResource) {
return false;
}
return $this->unwrapped(
fn () => match ($option) {
STREAM_OPTION_BLOCKING => stream_set_blocking($this->wrappedResource, (bool) $arg1),
STREAM_OPTION_READ_TIMEOUT => stream_set_timeout($this->wrappedResource, $arg1, $arg2),
STREAM_OPTION_WRITE_BUFFER => stream_set_write_buffer($this->wrappedResource, $arg1) === 0,
STREAM_OPTION_READ_BUFFER => stream_set_read_buffer($this->wrappedResource, $arg1) === 0,
default => false,
}
);
}
/**
* Retrieves information about an open file resource.
*
* @see {@link https://www.php.net/manual/en/streamwrapper.stream-stat.php}
*
* @return array<mixed>|false
*/
public function stream_stat(): array|false
{
if (!$this->wrappedResource) {
return false;
}
$stat = Ignition::getCachedStat($this->path);
if ($stat !== null) {
return $stat;
}
$stat = fstat($this->wrappedResource);
Ignition::cacheStat($this->path, $stat);
return $stat;
}
public function stream_tell(): int|false
{
if (!$this->wrappedResource) {
return false;
}
return ftell($this->wrappedResource);
}
public function stream_truncate(int $newSize): bool
{
if (!$this->wrappedResource) {
return false;
}
return ftruncate($this->wrappedResource, $newSize);
}
public function stream_write(string $data): int|false
{
if (!$this->wrappedResource) {
return false;
}
return fwrite($this->wrappedResource, $data);
}
public function unlink(string $path): bool
{
return $this->unwrapped(fn () => unlink($path));
}
public static function unregister(): void
{
@stream_wrapper_restore(static::PROTOCOL);
}
/**
* Disables the stream wrapper while the given callback is executed,
* allowing the native file:// protocol stream wrapper to be used for actual filesystem access.
*/
public function unwrapped(callable $callback): mixed
{
static::unregister();
try {
return $callback();
} finally {
// Note that if we do not unregister again first following the above restore,
// a segfault will be raised.
static::register();
}
}
/**
* Retrieves information about a file from its path.
*
* @see {@link https://www.php.net/manual/en/streamwrapper.url-stat.php}
*
* @return array<mixed>|false
*/
public function url_stat(string $path, int $flags): array|false
{
$stat = Ignition::getCachedStat($path);
if ($stat !== null) {
return $stat;
}
$link = (bool)($flags & STREAM_URL_STAT_LINK);
$quiet = (bool)($flags & STREAM_URL_STAT_QUIET);
/*
* This additional call to file_exists(...) should not cause an additional native filesystem stat,
* due to PHP's stat cache, which keeps the most recent file status,
* and so will be reused below by stat(...)/lstat(...) if the file does exist.
*
* This prevents the (l)stat call from raising a warning whose suppression below
* is then potentially overridden by a custom error handler.
*/
if ($quiet && !$this->unwrapped(static fn () => file_exists($path))) {
return false;
}
// Use lstat(...) for links but stat() for other files.
$doStat = static function () use ($link, $path) {
try {
return $link ?
lstat($path) :
stat($path);
} catch (RuntimeException) {
/*
* Stream wrapper must have been invoked by SplFileInfo::__construct(),
* which raises RuntimeExceptions in place of warnings
* such as `RuntimeException: stat(): stat failed for .../non_existent.txt`.
*/
return false;
}
};
// Suppress warnings/notices if quiet flag is set.
$stat = $this->unwrapped(
$quiet ?
static fn () => @$doStat() :
$doStat
);
Ignition::cacheStat($path, $stat);
return $stat;
}
}
}
namespace Nytris\Ignition\Storage {
/**
* Interface StorageInterface.
*
* Stores the filesystem stat cache for Ignition.
*
* @author Dan Phillimore <dan@ovms.co>
*/
interface StorageInterface
{
/**
* Fetches the stat cache from the backing store, if it has been stored yet.
*
* @return array<mixed>|null
*/
public function fetchStatCache(): ?array;
/**
* Determines whether the storage mechanism is supported.
*/
public function isSupported(): bool;
/**
* Stores a new stat cache to the backing store.
*
* @param array<mixed> $statCache
*/
public function saveStatCache(array $statCache): void;
}
/**
* Class ApcuStorage.
*
* Stores the filesystem stat cache for Ignition in APCu.
*
* @author Dan Phillimore <dan@ovms.co>
*/
class ApcuStorage implements StorageInterface
{
public function __construct(
private readonly string $apcuNamespace = 'nytris.ignition.stat'
) {
}
/**
* @inheritDoc
*/
public function fetchStatCache(): ?array
{
$statCache = apcu_fetch($this->apcuNamespace, success: $success);
return $success ? $statCache : null;
}
/**
* @inheritDoc
*/
public function isSupported(): bool
{
return function_exists('apcu_enabled') && apcu_enabled();
}
/**
* @inheritDoc
*/
public function saveStatCache(array $statCache): void
{
if (apcu_store($this->apcuNamespace, $statCache) === false) {
trigger_error('Failed to save Nytris Ignition cache in APCu', E_USER_ERROR);
}
}
}
}
namespace Nytris\Ignition\Choke {
use Asmblah\PhpCodeShift\Shifter\Stream\Native\StreamWrapper as ShiftStreamWrapper;
use Closure;
use LogicException;
use Nytris\Ignition\Autoloader\EarlyAutoloaderInterface;
use Nytris\Ignition\Filesystem\StreamWrapper;
use Nytris\Ignition\Storage\StorageInterface;
/**
* Interface ChokeInterface.
*
* Caches filesystem stats during early Nytris ignition and then boot.
*
* @author Dan Phillimore <dan@ovms.co>
*/
interface ChokeInterface
{
/**
* Adds a path to the stat cache.
*
* @param string $path
* @param array<mixed>|false $stat
*/
public function cacheStat(string $path, array|false $stat): void;
/**
* Fetches a stat from the stat cache.
*
* @param string $path
* @return array<mixed>|false|null Returns array on success, false when cached as non-accessible or null on miss.
*/
public function getCachedStat(string $path): array|false|null;
/**
* Fetches the in-memory contents of the stat cache.
*
* @return array<string, array<mixed>|false>
*/
public function getStatCache(): array;
/**
* Turns off choke.
*/
public function turnOff(): void;
/**
* Turns on choke.
*/
public function turnOn(): void;
}
/**
* Class Choke.
*
* Caches filesystem stats during early Nytris ignition and then boot.
*
* @author Dan Phillimore <dan@ovms.co>
*/
class Choke implements ChokeInterface
{
private ?EarlyAutoloaderInterface $earlyAutoloader;
private bool $isOn = false;
/**
* @var array<string, array<mixed>|false>
*/
private array $statCache;
private bool $statCacheIsDirty = false;
public function __construct(
private readonly StorageInterface $storage,
private readonly Closure $earlyAutoloaderProvider
) {
$this->statCache = $storage->fetchStatCache() ?? [];
}
/**
* @inheritDoc
*/
public function cacheStat(string $path, array|false $stat): void
{
$this->statCache[$path] = $stat;
$this->statCacheIsDirty = true;
}
/**
* @inheritDoc
*/
public function getCachedStat(string $path): array|false|null
{
return $this->statCache[$path] ?? null;
}
/**
* @inheritDoc
*/
public function getStatCache(): array
{
return $this->statCache;
}
/**
* @inheritDoc
*/
public function turnOff(): void
{
if (!$this->isOn) {
throw new LogicException('Nytris Ignition choke is not currently on');
}
if (!class_exists(ShiftStreamWrapper::class) || !ShiftStreamWrapper::isRegistered()) {
@stream_wrapper_restore('file');
}
if ($this->statCacheIsDirty) {
$this->storage->saveStatCache($this->statCache);
$this->statCacheIsDirty = false;
}
$this->statCache = [];
$this->earlyAutoloader->unregister();
$this->isOn = false;
}
/**
* @inheritDoc
*/
public function turnOn(): void
{
StreamWrapper::register();
// With the stream wrapper installed, the autoloader modules are now safe to require.
$this->earlyAutoloader = ($this->earlyAutoloaderProvider)();
$this->earlyAutoloader->register();
$this->isOn = true;
}
}
}
namespace Nytris\Ignition\Implementation {
use Closure;
use Nytris\Ignition\Autoloader\EarlyAutoloader;
use Nytris\Ignition\Choke\Choke;
use Nytris\Ignition\Choke\ChokeInterface;
use Nytris\Ignition\Config\ConfigResolver;
use Nytris\Ignition\Includer\Includer;
use Nytris\Ignition\Preflight\Preflighter;
use Nytris\Ignition\Preflight\PreflighterInterface;
use Nytris\Ignition\Storage\StorageInterface;
/**
* Interface ImplementationInterface.
*
* Defines the implementation of Nytris Ignition.
*
* @author Dan Phillimore <dan@ovms.co>
*/
interface ImplementationInterface
{
/**
* Fetches the Choke implementation.
*/
public function getChoke(string $rootProjectPath): ChokeInterface;
/**
* Fetches the Preflighter implementation.
*/
public function getPreflighter(): PreflighterInterface;
}
/**
* Class DefaultImplementation.
*
* Defines the default implementation of Nytris Ignition.
*
* @author Dan Phillimore <dan@ovms.co>
*/
class DefaultImplementation implements ImplementationInterface
{
public function __construct(
private readonly StorageInterface $storage,
private ?ChokeInterface $choke = null,
private ?PreflighterInterface $preflighter = null
) {
}
/**
* @inheritDoc
*/
public function getChoke(string $rootProjectPath): ChokeInterface
{
$this->choke ??= new Choke(
$this->storage,
function () use ($rootProjectPath) {
// With the stream wrapper installed, these are now safe to require.
// After this point, the early autoloader can then take over.
require_once __DIR__ . '/src/Autoloader/EarlyAutoloaderInterface.php';
require_once __DIR__ . '/src/Autoloader/EarlyAutoloader.php';
$psr4MappingsPath = $rootProjectPath . '/vendor/composer/autoload_psr4.php';
$psr4Mappings = file_exists($psr4MappingsPath) ?
// Note we cannot use Includer here due to a catch-22.
Closure::bind(static fn () => require $psr4MappingsPath, null, null)() :
[
'Nytris\\Ignition\\' => [__DIR__ . '/src'],
];
// TODO: Optimise mappings structure and cache optimised structure via configured Storage e.g. APCu.
return new EarlyAutoloader($psr4Mappings);
}
);
return $this->choke;
}
/**
* @inheritDoc
*/
public function getPreflighter(): PreflighterInterface
{
$this->preflighter ??= new Preflighter(new ConfigResolver(new Includer()));
return $this->preflighter;
}
}
}
namespace Nytris\Ignition {
use Closure;
use LogicException;
use Nytris\Ignition\Choke\ChokeInterface;
use Nytris\Ignition\Implementation\DefaultImplementation;
use Nytris\Ignition\Storage\ApcuStorage;
use Nytris\Ignition\Storage\StorageInterface;
/**
* Class Ignition.
*
* Initial entrypoint for the library.
*
* @author Dan Phillimore <dan@ovms.co>
*/
class Ignition
{
private static bool $autoHandoffEnabled = true;
private static ?ChokeInterface $choke = null;
private static bool $isStarted = false;
/**
* Adds a path to the stat cache.
*
* @param string $path
* @param array<mixed>|false $stat
*/
public static function cacheStat(string $path, array|false $stat): void
{
if (self::$choke === null) {
throw new LogicException('Nytris Ignition choke is not currently on');
}
self::$choke->cacheStat($path, $stat);
}
/**
* Disables auto-handoff.
*/
public static function disableAutoHandoff(): void
{
self::$autoHandoffEnabled = false;
}
/**
* Fetches a stat from the stat cache.
*
* @param string $path
* @return array<mixed>|false|null Returns array on success, false when cached as non-accessible or null on miss.
*/
public static function getCachedStat(string $path): array|false|null
{
if (self::$choke === null) {
throw new LogicException('Nytris Ignition choke is not currently on');
}
return self::$choke->getCachedStat($path);
}
/**
* Fetches the in-memory contents of the stat cache.
*
* @return array<string, array<mixed>|false>
*/
public static function getStatCache(): array
{
if (self::$choke === null) {
throw new LogicException('Nytris Ignition choke is not currently on');
}
return self::$choke->getStatCache();
}
/**
* Hands off from Ignition.
*/
public static function handOff(): void
{
if (!self::$isStarted) {
throw new LogicException('Nytris Ignition has not been started');
}
if (self::$choke === null) {
throw new LogicException('Nytris Ignition choke is not currently on');
}
self::$choke->turnOff();
self::$choke = null;
}
/**
* Fetches whether auto-handoff is currently on.
*/
public static function isAutoHandoffEnabled(): bool
{
return self::$autoHandoffEnabled;
}
/**
* Fetches whether choke is currently on.
*/
public static function isChokeOn(): bool
{
return self::$choke !== null;
}
/**
* Fetches whether Ignition has been started.
*/
public static function isStarted(): bool
{
return self::$isStarted;
}
/**
* Turns on choke - starts caching filesystem stats.
*/
public static function start(
string $rootProjectPath,
StorageInterface $storage = new ApcuStorage(),
?Closure $implementationProvider = null
): void {
if (self::$isStarted) {
throw new LogicException('Nytris Ignition already started');
}
self::$isStarted = true;
if (!$storage->isSupported()) {
// Storage is not supported, so we cannot start Ignition.
// e.g. when running under CLI and APCu is not enabled for CLI.
return;
}
$implementation = $implementationProvider ?
$implementationProvider($storage) :
new DefaultImplementation($storage);
self::$choke = $implementation->getChoke($rootProjectPath);
self::$choke->turnOn();
$implementation->getPreflighter()->runPreflights($rootProjectPath);
if (self::$autoHandoffEnabled) {
self::handOff();
}
}
/**
* Switches off Nytris Ignition. Differs from ->handOff() in that choke does not need to be on first.
*/
public static function switchOff(): void
{
if (!self::$isStarted) {
throw new LogicException('Nytris Ignition has not been started');
}
self::$choke?->turnOff();
self::$choke = null;
self::$isStarted = false;
}
}
}