Repository navigation
Expand file tree
/
Copy pathSnapshotStore.php
More file actions
796 lines (664 loc) · 22.6 KB
/
Copy pathSnapshotStore.php
File metadata and controls
796 lines (664 loc) · 22.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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
<?php
declare(strict_types=1);
namespace PHPForge\Debug\Storage;
use JsonException;
use PHPForge\Debug\Exception\Message;
use Throwable;
use function array_key_exists;
use function array_keys;
use function array_reverse;
use function count;
use function fclose;
use function glob;
use function is_array;
use function is_dir;
use function is_file;
use function is_string;
use function json_decode;
use function json_encode;
use function mkdir;
use function pathinfo;
use function preg_match;
use function usort;
/**
* Provides JSON filesystem storage, manifest locking, atomic writes, and snapshot garbage collection.
*/
final class SnapshotStore
{
/**
* Names the manifest index file.
*/
private const string INDEX_FILE = 'index.json';
/**
* Defines flags used for deterministic JSON encoding.
*/
private const int JSON_FLAGS = JSON_THROW_ON_ERROR
| JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
| JSON_PRESERVE_ZERO_FRACTION;
/**
* Names the manifest lock file.
*/
private const string LOCK_FILE = 'index.lock';
/**
* Names the transaction journal file.
*/
private const string TRANSACTION_FILE = '.debug-transaction.json';
/**
* Identifies the transaction journal format version.
*/
private const int TRANSACTION_VERSION = 1;
/**
* Creates a filesystem store with directory and file permission modes.
*
* @param string $path Storage directory path.
* @param int $dirMode Directory permissions used when creating the storage path.
* @param int|null $fileMode File permissions or `null` to preserve the system default.
*/
public function __construct(
private readonly string $path,
private readonly int $dirMode,
private readonly int|null $fileMode,
) {}
/**
* Removes stored manifests, snapshots, and temporary files.
*/
public function clear(): void
{
$this->initialize();
$lock = $this->acquireLock(LOCK_EX);
try {
$patterns = [
"{$this->path}/*.json",
"{$this->path}/.debug-*",
];
foreach ($patterns as $pattern) {
$files = glob($pattern);
foreach ($files === false ? [] : $files as $file) {
if (is_file($file) && !@unlink($file)) {
throw new StorageException(
Message::DATA_FILE_REMOVE_FAILED->getMessage($file),
);
}
}
}
} finally {
fclose($lock);
}
}
/**
* Returns manifest entries ordered from newest to oldest.
*
* @return array<string, RequestSummary> Newest entries first.
*/
public function loadManifest(): array
{
return $this->loadManifestResult()->entries;
}
/**
* Returns manifest entries and preserves any read diagnostic for observable error handling.
*
* @return ManifestReadResult Newest entries first plus an optional storage failure.
*/
public function loadManifestResult(): ManifestReadResult
{
if (!is_dir($this->path)) {
return new ManifestReadResult([], $this->directoryMissingError());
}
try {
$lock = $this->acquireLock(LOCK_EX);
} catch (StorageException $error) {
return new ManifestReadResult([], $error);
}
try {
$this->recoverTransaction();
$file = $this->indexFile();
if (!is_file($file)) {
return new ManifestReadResult([], null);
}
$manifest = Manifest::fromArray(
self::decode(self::readRequiredFile($file, Message::MANIFEST_READ_FAILED, Message::MANIFEST_EMPTY)),
);
return new ManifestReadResult(array_reverse($manifest->entries, true), null);
} catch (Throwable $failure) {
$error = $failure instanceof StorageException
? $failure
: new StorageException(
Message::MANIFEST_READ_ERROR->getMessage(),
0,
$failure,
);
return new ManifestReadResult([], $error);
} finally {
fclose($lock);
}
}
/**
* Returns a stored snapshot or `null` when the tag or persisted payload is invalid.
*
* @param string $tag Snapshot tag.
*
* @return DebugSnapshot|null Hydrated snapshot or `null` when the stored value is unavailable or invalid.
*/
public function readSnapshot(string $tag): DebugSnapshot|null
{
return $this->readSnapshotResult($tag)->snapshot;
}
/**
* Returns a stored snapshot and preserves any read diagnostic for observable error handling.
*
* @param string $tag Snapshot tag.
*
* @return SnapshotReadResult Snapshot, missing state, or storage failure.
*/
public function readSnapshotResult(string $tag): SnapshotReadResult
{
if (!self::isValidTag($tag)) {
return new SnapshotReadResult(
null,
new StorageException(
Message::SNAPSHOT_TAG_INVALID->getMessage($tag),
),
);
}
if (!is_dir($this->path)) {
return new SnapshotReadResult(null, $this->directoryMissingError());
}
try {
$lock = $this->acquireLock(LOCK_EX);
} catch (StorageException $error) {
return new SnapshotReadResult(null, $error);
}
try {
$this->recoverTransaction();
$file = $this->snapshotFile($tag);
if (!is_file($file)) {
return new SnapshotReadResult(null, null);
}
$snapshot = DebugSnapshot::fromArray(
self::decode(self::readRequiredFile($file, Message::SNAPSHOT_READ_FAILED, Message::SNAPSHOT_EMPTY)),
);
if ($snapshot->summary->tag !== $tag) {
throw new StorageException(
Message::SNAPSHOT_TAG_MISMATCH->getMessage($file),
);
}
return new SnapshotReadResult($snapshot, null);
} catch (Throwable $failure) {
$error = $failure instanceof StorageException
? $failure
: new StorageException(
Message::SNAPSHOT_READ_FAILED->getMessage($tag),
0,
$failure,
);
return new SnapshotReadResult(null, $error);
} finally {
fclose($lock);
}
}
/**
* Writes a snapshot, updates the manifest, and runs garbage collection under one exclusive lock.
*
* @param DebugSnapshot $snapshot Snapshot to persist.
* @param int $historySize Maximum number of retained entries.
*
* @return list<RequestSummary> Entries evicted from the manifest.
*/
public function writeSnapshot(DebugSnapshot $snapshot, int $historySize): array
{
return $this->writeSnapshotResult($snapshot, $historySize)->removed;
}
/**
* Writes a snapshot and returns the already-hydrated committed manifest together with evicted entries.
*
* Adapters that need the resulting manifest can consume this result without acquiring the lock and decoding the
* index a second time.
*
* @param DebugSnapshot $snapshot Snapshot to persist.
* @param int $historySize Maximum number of retained entries.
*
* @return SnapshotWriteResult Committed manifest and entries evicted from it.
*/
public function writeSnapshotResult(DebugSnapshot $snapshot, int $historySize): SnapshotWriteResult
{
self::assertValidHistorySize($historySize);
$tag = $snapshot->summary->tag;
$snapshotFile = $this->snapshotFile($tag);
$snapshotJson = self::encode($snapshot);
$this->initialize();
$lock = $this->acquireLock(LOCK_EX);
try {
$this->recoverTransaction();
[$manifest, $manifestBefore] = $this->readManifestFile();
$entries = ($manifest ?? $this->rebuildManifest())->entries;
unset($entries[$tag]);
$entries[$tag] = $snapshot->summary;
$removed = $this->collectGarbage($entries, $historySize);
$transaction = [
'version' => self::TRANSACTION_VERSION,
'state' => 'prepared',
'tag' => $tag,
'snapshotBefore' => $this->readExistingFile($snapshotFile),
'manifestBefore' => $manifestBefore,
];
$this->atomicWrite($this->transactionFile(), self::encode($transaction));
try {
if ($entries !== []) {
$this->atomicWrite($snapshotFile, $snapshotJson);
}
$this->atomicWrite($this->indexFile(), self::encode(new Manifest($entries)));
$transaction['state'] = 'committed';
$this->atomicWrite($this->transactionFile(), self::encode($transaction));
@unlink($this->transactionFile());
} catch (Throwable $failure) {
try {
$this->recoverTransaction();
} catch (Throwable) {
// Preserve the write failure; the journal remains available for a later recovery attempt.
}
throw $failure;
}
$this->removeStaleSnapshots($entries);
return new SnapshotWriteResult(array_reverse($entries, true), $removed);
} finally {
fclose($lock);
}
}
/**
* Opens and acquires a checked filesystem lock.
*
* @param int<0, 7> $operation Lock operation passed to {@see flock()}.
*
* @return resource Acquired lock handle.
*/
private function acquireLock(int $operation): mixed
{
$lockFile = $this->lockFile();
$lock = @fopen($lockFile, 'c+');
if ($lock === false) {
throw new StorageException(
Message::LOCK_FILE_OPEN_FAILED->getMessage($lockFile),
);
}
if (!@flock($lock, $operation)) {
fclose($lock);
throw new StorageException(
Message::LOCK_ACQUIRE_FAILED->getMessage($lockFile),
);
}
return $lock;
}
/**
* Validates a manifest history size.
*
* @param int $historySize Maximum number of retained entries.
*/
private static function assertValidHistorySize(int $historySize): void
{
if ($historySize < 0) {
throw new StorageException(
Message::HISTORY_SIZE_INVALID->getMessage($historySize),
);
}
}
/**
* Replaces a target file through a temporary file in the same directory.
*
* @param string $file Target file path.
* @param string $contents JSON contents to write.
*/
private function atomicWrite(string $file, string $contents): void
{
$temporary = @tempnam($this->path, '.debug-');
if ($temporary === false) {
throw new StorageException(
Message::TEMPORARY_FILE_WRITE_FAILED->getMessage($file),
);
}
if (file_put_contents($temporary, $contents) === false) {
@unlink($temporary);
throw new StorageException(
Message::TEMPORARY_FILE_WRITE_FAILED->getMessage($file),
);
}
if ($this->fileMode !== null) {
if (!@chmod($temporary, $this->fileMode)) {
@unlink($temporary);
throw new StorageException(
Message::DATA_FILE_MODE_FAILED->getMessage($file),
);
}
}
if (!@rename($temporary, $file)) {
@unlink($temporary);
throw new StorageException(
Message::DATA_FILE_REPLACE_FAILED->getMessage($file),
);
}
}
/**
* Removes expired manifest entries.
*
* @param array<string, RequestSummary> $entries Manifest entries, updated in place.
* @param int $historySize Maximum number of retained entries.
*
* @return list<RequestSummary> Removed manifest entries.
*/
private function collectGarbage(array &$entries, int $historySize): array
{
if (count($entries) <= $historySize) {
return [];
}
$remaining = count($entries) - $historySize;
$removed = [];
foreach (array_keys($entries) as $tag) {
$removed[] = $entries[$tag];
unset($entries[$tag]);
if (--$remaining <= 0) {
break;
}
}
return $removed;
}
/**
* Decodes JSON and throws when the payload is invalid.
*
* @param string $json JSON document to decode.
*
* @throws JsonException if the JSON is invalid.
*
* @return mixed Decoded JSON value.
*/
private static function decode(string $json): mixed
{
return json_decode($json, true, flags: JSON_THROW_ON_ERROR);
}
/**
* Returns the diagnostic for a storage path that exists but is not a directory, or `null` when it is simply absent.
*
* @return StorageException|null Path diagnostic or `null`.
*/
private function directoryMissingError(): StorageException|null
{
return is_file($this->path)
? new StorageException(
Message::DATA_PATH_NOT_DIRECTORY->getMessage($this->path),
)
: null;
}
/**
* Encodes a value as deterministic JSON.
*
* @param mixed $value Value to encode.
*
* @throws JsonException if the value cannot be encoded.
*
* @return string Encoded JSON document.
*/
private static function encode(mixed $value): string
{
return json_encode($value, self::JSON_FLAGS);
}
/**
* Returns the manifest file path.
*
* @return string Manifest file path.
*/
private function indexFile(): string
{
return "{$this->path}/" . self::INDEX_FILE;
}
/**
* Creates the storage directory when it does not exist.
*/
private function initialize(): void
{
$created = false;
if (!is_dir($this->path)) {
$created = @mkdir($this->path, $this->dirMode, true);
}
if (!is_dir($this->path)) {
throw new StorageException(
Message::DATA_DIRECTORY_CREATE_FAILED->getMessage($this->path),
);
}
if ($created && !@chmod($this->path, $this->dirMode)) {
throw new StorageException(
Message::DATA_DIRECTORY_MODE_FAILED->getMessage($this->path),
);
}
}
/**
* Determines whether a tag can form a safe snapshot filename.
*
* @param string $tag Snapshot tag to validate.
*
* @return bool Whether the tag is safe for a filename.
*/
private static function isValidTag(string $tag): bool
{
return $tag !== 'index'
&& preg_match('/\A(?!-?(?:0|[1-9][0-9]*)\z)[A-Za-z0-9_-][A-Za-z0-9._-]*\z/', $tag) === 1;
}
/**
* Returns the manifest lock file path.
*
* @return string Manifest lock file path.
*/
private function lockFile(): string
{
return "{$this->path}/" . self::LOCK_FILE;
}
/**
* Reads an existing transaction target for rollback, or `null` when it does not exist.
*/
private function readExistingFile(string $file): string|null
{
if (!is_file($file)) {
return null;
}
$contents = @file_get_contents($file);
if ($contents === false) {
throw new StorageException(
Message::DATA_FILE_READ_FAILED->getMessage($file),
);
}
return $contents;
}
/**
* Reads the manifest or returns `null` when persisted JSON is invalid.
*
* @return array{Manifest|null, string|null} Hydrated manifest and its raw rollback payload.
*/
private function readManifestFile(): array
{
$file = $this->indexFile();
if (!is_file($file)) {
return [new Manifest([]), null];
}
$raw = @file_get_contents($file);
if ($raw === false) {
throw new StorageException(
Message::MANIFEST_READ_FAILED->getMessage($file),
);
}
if ($raw === '') {
return [null, $raw];
}
try {
return [Manifest::fromArray(self::decode($raw)), $raw];
} catch (Throwable) {
return [null, $raw];
}
}
/**
* Reads a stored document that must exist and carry content.
*
* @param string $file Document path.
* @param Message $failed Diagnostic used when the read fails.
* @param Message $empty Diagnostic used when the document is empty.
*
* @return string Raw document contents.
*/
private static function readRequiredFile(string $file, Message $failed, Message $empty): string
{
$raw = @file_get_contents($file);
if ($raw === false) {
throw new StorageException(
$failed->getMessage($file),
);
}
if ($raw === '') {
throw new StorageException(
$empty->getMessage($file),
);
}
return $raw;
}
/**
* Rebuilds a corrupt manifest from valid snapshot envelopes in deterministic request-time order.
*/
private function rebuildManifest(): Manifest
{
$summaries = [];
$files = glob("{$this->path}/*.json");
foreach ($files === false ? [] : $files as $file) {
if ($file === $this->indexFile()) {
continue;
}
$tag = pathinfo($file, PATHINFO_FILENAME);
if (!self::isValidTag($tag)) {
continue;
}
$raw = @file_get_contents($file);
if ($raw === false || $raw === '') {
continue;
}
try {
$snapshot = DebugSnapshot::fromArray(self::decode($raw));
} catch (Throwable) {
continue;
}
if ($snapshot->summary->tag === $tag) {
$summaries[] = $snapshot->summary;
}
}
usort(
$summaries,
static fn(RequestSummary $left, RequestSummary $right): int => [$left->time, $left->tag]
<=> [$right->time, $right->tag],
);
$entries = [];
foreach ($summaries as $summary) {
$entries[$summary->tag] = $summary;
}
return new Manifest($entries);
}
/**
* Recovers a prepared multi-file write or clears a committed journal left behind by a crash.
*/
private function recoverTransaction(): void
{
$file = $this->transactionFile();
$raw = @file_get_contents($file);
if ($raw === false || $raw === '') {
return;
}
try {
$transaction = self::decode($raw);
} catch (JsonException $exception) {
throw new StorageException(
Message::TRANSACTION_JOURNAL_INVALID->getMessage($file),
0,
$exception,
);
}
if (
!is_array($transaction)
|| ($transaction['version'] ?? null) !== self::TRANSACTION_VERSION
|| !is_string($transaction['state'] ?? null)
|| !is_string($transaction['tag'] ?? null)
|| !self::isValidTag($transaction['tag'])
|| (!isset($transaction['snapshotBefore']) && !array_key_exists('snapshotBefore', $transaction))
|| (!isset($transaction['manifestBefore']) && !array_key_exists('manifestBefore', $transaction))
|| $transaction['snapshotBefore'] !== null && !is_string($transaction['snapshotBefore'])
|| $transaction['manifestBefore'] !== null && !is_string($transaction['manifestBefore'])
) {
throw new StorageException(Message::TRANSACTION_JOURNAL_INVALID->getMessage($file));
}
if ($transaction['state'] === 'committed') {
@unlink($file);
return;
}
if ($transaction['state'] !== 'prepared') {
throw new StorageException(
Message::TRANSACTION_JOURNAL_INVALID->getMessage($file),
);
}
$snapshotFile = $this->snapshotFile($transaction['tag']);
if ($transaction['snapshotBefore'] === null) {
$this->removeTransactionTarget($snapshotFile);
} else {
$this->atomicWrite($snapshotFile, $transaction['snapshotBefore']);
}
if ($transaction['manifestBefore'] === null) {
$this->removeTransactionTarget($this->indexFile());
} else {
$this->atomicWrite($this->indexFile(), $transaction['manifestBefore']);
}
@unlink($file);
}
/**
* Removes snapshot files whose tags no longer appear in the manifest.
*
* @param array<string, RequestSummary> $entries Retained manifest entries.
*/
private function removeStaleSnapshots(array $entries): void
{
$files = glob("{$this->path}/*.json");
foreach ($files === false ? [] : $files as $file) {
if ($file === $this->indexFile()) {
continue;
}
$tag = pathinfo($file, PATHINFO_FILENAME);
if (!array_key_exists($tag, $entries)) {
@unlink($file);
}
}
}
/**
* Removes a target created by an interrupted first write without discarding the journal on failure.
*/
private function removeTransactionTarget(string $file): void
{
if (is_file($file) && !@unlink($file)) {
throw new StorageException(
Message::DATA_FILE_ROLLBACK_FAILED->getMessage($file),
);
}
}
/**
* Returns the snapshot file path for a validated tag.
*
* @param string $tag Snapshot tag.
*
* @return string Snapshot file path.
*/
private function snapshotFile(string $tag): string
{
if (!self::isValidTag($tag)) {
throw new StorageException(
Message::SNAPSHOT_TAG_INVALID->getMessage($tag),
);
}
return $this->path . "/{$tag}.json";
}
/**
* Returns the multi-file write journal path.
*/
private function transactionFile(): string
{
return "{$this->path}/" . self::TRANSACTION_FILE;
}
}