-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDraftController.php
More file actions
587 lines (506 loc) · 17.2 KB
/
DraftController.php
File metadata and controls
587 lines (506 loc) · 17.2 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
<?php
/**
* DraftController handles autosave draft persistence for the metadata editor.
*/
class DraftController
{
/**
* Absolute path to the directory where draft payloads are stored.
*
* @var string
*/
private string $storageRoot;
/**
* Number of days draft payloads are retained before being purged.
*
* @var int
*/
private int $retentionDays;
/**
* Creates the controller instance and resolves storage configuration.
*/
public function __construct()
{
$this->storageRoot = rtrim(getenv('ELMO_DRAFT_STORAGE') ?: (__DIR__ . '/../../../storage/drafts'), DIRECTORY_SEPARATOR);
$this->retentionDays = (int) (getenv('ELMO_DRAFT_RETENTION_DAYS') ?: 30);
}
/**
* Ensures the storage root directory exists and is writable.
*
* @throws \RuntimeException When the directory cannot be created or is not writable.
*/
private function ensureStorageRoot(): void
{
if (!is_dir($this->storageRoot)) {
// Suppress warning from race when another process creates the dir concurrently
if (!@mkdir($this->storageRoot, 0775, true) && !is_dir($this->storageRoot)) {
throw new \RuntimeException('DraftController: cannot create storage directory: ' . $this->storageRoot);
}
}
if (!is_writable($this->storageRoot)) {
throw new \RuntimeException('DraftController: storage directory is not writable: ' . $this->storageRoot);
}
}
/**
* Creates a new autosave draft for the active user session.
*
* @param array<mixed> $vars Route variables provided by the router.
* @param array<mixed>|null $body Optional parsed request payload for testing.
* @return void
*/
public function create(array $vars = [], ?array $body = null): void
{
$sessionId = $this->ensureSession();
$this->cleanupOldDrafts();
$payload = $body ?? $this->readJsonBody();
if (!$this->isValidPayload($payload)) {
$this->respond(422, ['error' => 'Invalid payload']);
return;
}
$draftId = bin2hex(random_bytes(16));
$record = $this->createRecord($draftId, $sessionId, $payload['payload']);
try {
$this->persistRecord($record);
} catch (\RuntimeException $e) {
error_log($e->getMessage());
$this->respond(500, ['error' => 'Failed to persist draft']);
return;
}
$this->respond(201, $this->responseMetadata($record));
}
/**
* Updates an existing autosave draft belonging to the current session.
*
* @param array<mixed> $vars Route variables containing the draft identifier.
* @param array<mixed>|null $body Optional parsed request payload for testing.
* @return void
*/
public function update(array $vars = [], ?array $body = null): void
{
$sessionId = $this->ensureSession();
$this->cleanupOldDrafts();
$payload = $body ?? $this->readJsonBody();
$draftId = $this->sanitizeDraftId($vars['id'] ?? '');
if (!$draftId) {
$this->respond(400, ['error' => 'Missing draft id']);
return;
}
if (!$this->isValidPayload($payload)) {
$this->respond(422, ['error' => 'Invalid payload']);
return;
}
$forbidden = false;
$record = $this->readRecord($sessionId, $draftId, $forbidden);
if ($forbidden) {
$this->respond(403, ['error' => 'Forbidden']);
return;
}
if (!$record) {
$this->respond(404, ['error' => 'Draft not found']);
return;
}
$record['payload'] = $payload['payload'];
$record['updatedAt'] = $this->now();
$record['checksum'] = $this->checksum($record['payload']);
try {
$this->persistRecord($record);
} catch (\RuntimeException $e) {
error_log($e->getMessage());
$this->respond(500, ['error' => 'Failed to persist draft']);
return;
}
$this->respond(200, $this->responseMetadata($record));
}
/**
* Retrieves the payload of the specified draft if it belongs to the session.
*
* @param array<mixed> $vars Route variables containing the draft identifier.
* @param array<mixed>|null $body Optional parsed request payload (unused).
* @return void
*/
public function get(array $vars = [], ?array $body = null): void
{
$sessionId = $this->ensureSession();
$draftId = $this->sanitizeDraftId($vars['id'] ?? '');
if (!$draftId) {
$this->respond(400, ['error' => 'Missing draft id']);
return;
}
$forbidden = false;
$record = $this->readRecord($sessionId, $draftId, $forbidden);
if ($forbidden) {
$this->respond(403, ['error' => 'Forbidden']);
return;
}
if (!$record) {
$this->respond(204, null);
return;
}
$this->respond(200, $this->exposeRecord($record));
}
/**
* Deletes the specified draft for the current session.
*
* @param array<mixed> $vars Route variables containing the draft identifier.
* @param array<mixed>|null $body Optional parsed request payload (unused).
* @return void
*/
public function delete(array $vars = [], ?array $body = null): void
{
$sessionId = $this->ensureSession();
$draftId = $this->sanitizeDraftId($vars['id'] ?? '');
if (!$draftId) {
$this->respond(400, ['error' => 'Missing draft id']);
return;
}
$path = $this->recordPath($sessionId, $draftId);
if (!is_file($path)) {
$this->respond(404, ['error' => 'Draft not found']);
return;
}
unlink($path);
$this->respond(204, null);
}
/**
* Returns the latest draft belonging to the current session, if available.
*
* @param array<mixed> $vars Route variables (unused).
* @param array<mixed>|null $body Optional parsed request payload (unused).
* @return void
*/
public function latestForSession(array $vars = [], ?array $body = null): void
{
$sessionId = $this->ensureSession();
$files = glob($this->sessionDirectory($sessionId) . DIRECTORY_SEPARATOR . '*.json');
if (!$files) {
$this->respond(204, null);
return;
}
$latestRecord = null;
$latestScore = -INF;
foreach ($files as $file) {
$contents = file_get_contents($file);
if ($contents === false) {
continue;
}
$record = json_decode($contents, true);
if (!is_array($record)) {
continue;
}
$score = $this->recordTimestampScore($record, $file);
if ($score > $latestScore) {
$latestScore = $score;
$latestRecord = $record;
continue;
}
if ($score === $latestScore && $latestRecord !== null) {
$latestRecord = $this->preferLatestRecord($latestRecord, $record);
}
}
if ($latestRecord === null) {
$this->respond(204, null);
return;
}
$this->respond(200, $this->exposeRecord($latestRecord));
}
/**
* Ensures a PHP session is active and returns its identifier.
*
* @return string
*/
private function ensureSession(): string
{
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
return session_id();
}
/**
* Reads and decodes the JSON request payload from the input stream.
*
* @return array<mixed>|null
*/
private function readJsonBody(): ?array
{
$raw = file_get_contents('php://input');
if ($raw === false || $raw === '') {
return null;
}
$data = json_decode($raw, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return null;
}
return $data;
}
/**
* Validates the autosave payload structure.
*
* @param array<mixed>|null $data Request payload to validate.
* @return bool
*/
private function isValidPayload(?array $data): bool
{
if (!$data || !isset($data['payload']) || !is_array($data['payload'])) {
return false;
}
return true;
}
/**
* Creates a new record array for persistence.
*
* @param string $draftId Generated draft identifier.
* @param string $sessionId Current session identifier.
* @param array<mixed> $payload Submitted payload data.
* @return array<mixed>
*/
private function createRecord(string $draftId, string $sessionId, array $payload): array
{
return [
'id' => $draftId,
'sessionId' => $sessionId,
'updatedAt' => $this->now(),
'payload' => $payload,
'checksum' => $this->checksum($payload)
];
}
/**
* Persists the provided record to disk.
*
* @param array<mixed> $record Draft record to store.
* @return void
*/
private function persistRecord(array $record): void
{
$this->ensureStorageRoot();
$dir = $this->sessionDirectory($record['sessionId']);
if (!is_dir($dir)) {
if (!@mkdir($dir, 0775, true) && !is_dir($dir)) {
throw new \RuntimeException('DraftController: cannot create session directory: ' . $dir);
}
}
$path = $this->recordPath($record['sessionId'], $record['id']);
try {
$json = json_encode($record, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new \RuntimeException('DraftController: failed to encode draft as JSON: ' . $e->getMessage());
}
$bytes = file_put_contents($path, $json);
if ($bytes === false) {
throw new \RuntimeException('DraftController: failed to write draft file: ' . $path);
}
}
/**
* Reads a draft record from disk when accessible to the session.
*
* @param string $sessionId Current session identifier.
* @param string $draftId Draft identifier to load.
* @param bool $forbidden Flag set to true when record belongs to another session.
* @return array<mixed>|null
*/
private function readRecord(string $sessionId, string $draftId, bool &$forbidden = false): ?array
{
$path = $this->recordPath($sessionId, $draftId);
if (!is_file($path)) {
if ($this->draftExistsElsewhere($draftId)) {
$forbidden = true;
}
return null;
}
$content = file_get_contents($path);
if ($content === false) {
return null;
}
$record = json_decode($content, true);
if (!is_array($record)) {
return null;
}
if (($record['sessionId'] ?? null) !== $sessionId) {
$forbidden = true;
return null;
}
return $record;
}
/**
* Determines whether the draft exists for a different session.
*
* @param string $draftId Draft identifier to check.
* @return bool
*/
private function draftExistsElsewhere(string $draftId): bool
{
$pattern = $this->storageRoot . DIRECTORY_SEPARATOR . '*' . DIRECTORY_SEPARATOR . $draftId . '.json';
$matches = glob($pattern) ?: [];
return !empty($matches);
}
/**
* Reduces a record to the fields exposed to API consumers.
*
* @param array<mixed> $record Draft record to expose.
* @return array<mixed>
*/
private function exposeRecord(array $record): array
{
return [
'id' => $record['id'],
'updatedAt' => $record['updatedAt'],
'payload' => $record['payload'],
'checksum' => $record['checksum']
];
}
/**
* Prepares metadata payload for create/update responses.
*
* @param array<mixed> $record Draft record to summarize.
* @return array<mixed>
*/
private function responseMetadata(array $record): array
{
return [
'id' => $record['id'],
'updatedAt' => $record['updatedAt'],
'checksum' => $record['checksum']
];
}
/**
* Validates that the provided draft ID is well-formed.
*
* @param string $draftId Draft identifier to validate.
* @return string
*/
private function sanitizeDraftId(string $draftId): string
{
return preg_match('/^[a-f0-9]{32}$/', $draftId) ? $draftId : '';
}
/**
* Computes the file path for a draft belonging to the provided session.
*
* @param string $sessionId Current session identifier.
* @param string $draftId Draft identifier.
* @return string
*/
private function recordPath(string $sessionId, string $draftId): string
{
return $this->sessionDirectory($sessionId) . DIRECTORY_SEPARATOR . $draftId . '.json';
}
/**
* Returns the directory path for a given session identifier.
*
* @param string $sessionId Current session identifier.
* @return string
*/
private function sessionDirectory(string $sessionId): string
{
return $this->storageRoot . DIRECTORY_SEPARATOR . $sessionId;
}
/**
* Provides the current timestamp in ISO 8601 format.
*
* @return string
*/
private function now(): string
{
$microtime = microtime(true);
$date = \DateTimeImmutable::createFromFormat('U.u', sprintf('%.6F', $microtime), new \DateTimeZone('UTC'));
if ($date === false) {
return gmdate('c');
}
return $date->format('Y-m-d\\TH:i:s.u\\Z');
}
/**
* Computes a checksum to track payload changes.
*
* @param array<mixed> $payload Payload to hash.
* @return string
*/
private function checksum(array $payload): string
{
return hash('sha256', json_encode($payload));
}
/**
* Calculates a comparable timestamp score for a persisted record.
*
* @param array<mixed> $record Draft record to evaluate.
* @param string $filePath Path to the record file used for fallbacks.
* @return float
*/
private function recordTimestampScore(array $record, string $filePath): float
{
$timestamp = $record['updatedAt'] ?? null;
if (is_string($timestamp)) {
$date = \DateTimeImmutable::createFromFormat('Y-m-d\\TH:i:s.u\\Z', $timestamp, new \DateTimeZone('UTC'));
if ($date === false) {
try {
$date = new \DateTimeImmutable($timestamp, new \DateTimeZone('UTC'));
} catch (\Exception $exception) {
$date = false;
}
}
if ($date !== false) {
return (float) $date->format('U.u');
}
}
return (float) filemtime($filePath);
}
/**
* Determines which record should win when timestamp scores are identical.
*
* @param array<mixed> $current Currently selected record.
* @param array<mixed> $candidate Candidate record being evaluated.
* @return array<mixed>
*/
private function preferLatestRecord(array $current, array $candidate): array
{
$currentUpdated = $current['updatedAt'] ?? '';
$candidateUpdated = $candidate['updatedAt'] ?? '';
if ($candidateUpdated > $currentUpdated) {
return $candidate;
}
if ($candidateUpdated < $currentUpdated) {
return $current;
}
$currentId = $current['id'] ?? '';
$candidateId = $candidate['id'] ?? '';
return $candidateId > $currentId ? $candidate : $current;
}
/**
* Removes expired draft files from storage.
*
* @return void
*/
private function cleanupOldDrafts(): void
{
if ($this->retentionDays <= 0) {
return;
}
$threshold = time() - ($this->retentionDays * 86400);
$directories = glob($this->storageRoot . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR) ?: [];
foreach ($directories as $directory) {
$files = glob($directory . DIRECTORY_SEPARATOR . '*.json') ?: [];
foreach ($files as $file) {
if (filemtime($file) < $threshold) {
@unlink($file);
}
}
$remaining = glob($directory . DIRECTORY_SEPARATOR . '*.json') ?: [];
if (empty($remaining)) {
@rmdir($directory);
}
}
}
/**
* Sends a JSON response with the provided HTTP status code.
*
* @param int $status HTTP status code to send.
* @param array<mixed>|null $payload Response payload.
* @return void
*/
private function respond(int $status, ?array $payload): void
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
if ($payload === null) {
return;
}
echo json_encode($payload);
}
}