-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathJobQueue.php
More file actions
608 lines (526 loc) · 17.2 KB
/
Copy pathJobQueue.php
File metadata and controls
608 lines (526 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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
<?php
/**
* @package Grav\Common\Scheduler
*
* @copyright Copyright (c) 2015 - 2026 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common\Scheduler;
use Grav\Common\Security;
use RocketTheme\Toolbox\File\JsonFile;
use RuntimeException;
/**
* File-based job queue implementation
*
* @package Grav\Common\Scheduler
*/
class JobQueue
{
/** @var string */
protected $queuePath;
/** @var string */
protected $lockFile;
/** @var array Priority levels */
const PRIORITY_HIGH = 'high';
const PRIORITY_NORMAL = 'normal';
const PRIORITY_LOW = 'low';
/**
* JobQueue constructor
*
* @param string $queuePath
*/
public function __construct(string $queuePath)
{
$this->queuePath = $queuePath;
$this->lockFile = $queuePath . '/.lock';
// Create queue directories
$this->initializeDirectories();
}
/**
* Initialize queue directories
*
* @return void
*/
protected function initializeDirectories(): void
{
$dirs = [
$this->queuePath . '/pending',
$this->queuePath . '/processing',
$this->queuePath . '/failed',
$this->queuePath . '/completed',
];
foreach ($dirs as $dir) {
if (!file_exists($dir)) {
mkdir($dir, 0755, true);
}
}
}
/**
* Push a job to the queue
*
* @param Job $job
* @param string $priority
* @return string Job queue ID
*/
public function push(Job $job, string $priority = self::PRIORITY_NORMAL): string
{
$queueId = $this->generateQueueId($job);
$timestamp = microtime(true);
$queueItem = [
'id' => $queueId,
'job_id' => $job->getId(),
'command' => is_string($job->getCommand()) ? $job->getCommand() : 'Closure',
'arguments' => method_exists($job, 'getRawArguments') ? $job->getRawArguments() : $job->getArguments(),
'priority' => $priority,
'timestamp' => $timestamp,
'attempts' => 0,
'max_attempts' => method_exists($job, 'getMaxAttempts') ? $job->getMaxAttempts() : 1,
'created_at' => date('c'),
'scheduled_for' => null,
'metadata' => [],
];
// Always serialize the job to preserve its full state. The blob is HMAC-signed
// with the per-site nonce key so that a tampered queue file cannot be used to
// smuggle a forged Job (which would gain RCE via Job::exec → call_user_func_array).
// GHSA-vj3m-2g9h-vm4p (#1).
$serialized = serialize($job);
$queueItem['serialized_job'] = base64_encode($serialized);
$queueItem['serialized_job_hmac'] = hash_hmac('sha256', $serialized, Security::getNonceKey());
$this->writeQueueItem($queueItem, 'pending');
return $queueId;
}
/**
* Push a job for delayed execution
*
* @param Job $job
* @param \DateTime $scheduledFor
* @param string $priority
* @return string
*/
public function pushDelayed(Job $job, \DateTime $scheduledFor, string $priority = self::PRIORITY_NORMAL): string
{
$queueId = $this->push($job, $priority);
// Update the scheduled time
$item = $this->getQueueItem($queueId, 'pending');
if ($item) {
$item['scheduled_for'] = $scheduledFor->format('c');
$this->writeQueueItem($item, 'pending');
}
return $queueId;
}
/**
* Pop the next job from the queue
*
* @return Job|null
*/
public function pop(): ?Job
{
if (!$this->lock()) {
return null;
}
try {
// Get all pending items
$items = $this->getPendingItems();
if (empty($items)) {
$this->unlock();
return null;
}
// Sort by priority and timestamp
usort($items, function($a, $b) {
$priorityOrder = [
self::PRIORITY_HIGH => 0,
self::PRIORITY_NORMAL => 1,
self::PRIORITY_LOW => 2,
];
$aPriority = $priorityOrder[$a['priority']] ?? 1;
$bPriority = $priorityOrder[$b['priority']] ?? 1;
if ($aPriority !== $bPriority) {
return $aPriority - $bPriority;
}
return $a['timestamp'] <=> $b['timestamp'];
});
// Get the first item that's ready to run
$now = new \DateTime();
foreach ($items as $item) {
if ($item['scheduled_for']) {
$scheduledTime = new \DateTime($item['scheduled_for']);
if ($scheduledTime > $now) {
continue; // Skip items not yet due
}
}
// Move to processing
$this->moveQueueItem($item['id'], 'pending', 'processing');
// Reconstruct the job
$job = $this->reconstructJob($item);
$this->unlock();
return $job;
}
$this->unlock();
return null;
} catch (\Exception $e) {
$this->unlock();
throw $e;
}
}
/**
* Pop a job from the queue with its queue ID
*
* @return array|null Array with 'job' and 'id' keys
*/
public function popWithId(): ?array
{
if (!$this->lock()) {
return null;
}
try {
// Get all pending items
$items = $this->getPendingItems();
if (empty($items)) {
$this->unlock();
return null;
}
// Sort by priority and timestamp
usort($items, function($a, $b) {
$priorityOrder = [
self::PRIORITY_HIGH => 0,
self::PRIORITY_NORMAL => 1,
self::PRIORITY_LOW => 2,
];
$aPriority = $priorityOrder[$a['priority']] ?? 1;
$bPriority = $priorityOrder[$b['priority']] ?? 1;
if ($aPriority !== $bPriority) {
return $aPriority - $bPriority;
}
return $a['timestamp'] <=> $b['timestamp'];
});
// Get the first item that's ready to run
$now = new \DateTime();
foreach ($items as $item) {
if ($item['scheduled_for']) {
$scheduledTime = new \DateTime($item['scheduled_for']);
if ($scheduledTime > $now) {
continue; // Skip items not yet due
}
}
// Reconstruct the job first before moving it
$job = $this->reconstructJob($item);
if (!$job) {
// Failed to reconstruct, skip this item
continue;
}
// Move to processing only if we can reconstruct the job
$this->moveQueueItem($item['id'], 'pending', 'processing');
$this->unlock();
return ['job' => $job, 'id' => $item['id']];
}
$this->unlock();
return null;
} catch (\Exception $e) {
$this->unlock();
throw $e;
}
}
/**
* Mark a job as completed
*
* @param string $queueId
* @return void
*/
public function complete(string $queueId): void
{
$this->moveQueueItem($queueId, 'processing', 'completed');
// Clean up old completed items
$this->cleanupCompleted();
}
/**
* Mark a job as failed
*
* @param string $queueId
* @param string $error
* @return void
*/
public function fail(string $queueId, string $error = ''): void
{
$item = $this->getQueueItem($queueId, 'processing');
if ($item) {
$item['attempts']++;
$item['last_error'] = $error;
$item['failed_at'] = date('c');
if ($item['attempts'] < $item['max_attempts']) {
// Move back to pending for retry
$item['retry_at'] = $this->calculateRetryTime($item['attempts']);
$item['scheduled_for'] = $item['retry_at'];
$this->writeQueueItem($item, 'pending');
$this->deleteQueueItem($queueId, 'processing');
} else {
// Move to failed (dead letter queue)
$this->writeQueueItem($item, 'failed');
$this->deleteQueueItem($queueId, 'processing');
}
}
}
/**
* Get queue size
*
* @return int
*/
public function size(): int
{
return count($this->getPendingItems());
}
/**
* Check if queue is empty
*
* @return bool
*/
public function isEmpty(): bool
{
return $this->size() === 0;
}
/**
* Get queue statistics
*
* @return array
*/
public function getStatistics(): array
{
return [
'pending' => count($this->getPendingItems()),
'processing' => count($this->getItemsInDirectory('processing')),
'failed' => count($this->getItemsInDirectory('failed')),
'completed_today' => $this->countCompletedToday(),
];
}
/**
* Generate a unique queue ID
*
* @param Job $job
* @return string
*/
protected function generateQueueId(Job $job): string
{
return $job->getId() . '_' . uniqid('', true);
}
/**
* Write queue item to disk
*
* @param array $item
* @param string $directory
* @return void
*/
protected function writeQueueItem(array $item, string $directory): void
{
$path = $this->queuePath . '/' . $directory . '/' . $item['id'] . '.json';
$file = JsonFile::instance($path);
$file->save($item);
}
/**
* Read queue item from disk
*
* @param string $queueId
* @param string $directory
* @return array|null
*/
protected function getQueueItem(string $queueId, string $directory): ?array
{
$path = $this->queuePath . '/' . $directory . '/' . $queueId . '.json';
if (!file_exists($path)) {
return null;
}
$file = JsonFile::instance($path);
return $file->content();
}
/**
* Delete queue item
*
* @param string $queueId
* @param string $directory
* @return void
*/
protected function deleteQueueItem(string $queueId, string $directory): void
{
$path = $this->queuePath . '/' . $directory . '/' . $queueId . '.json';
if (file_exists($path)) {
unlink($path);
}
}
/**
* Move queue item between directories
*
* @param string $queueId
* @param string $fromDir
* @param string $toDir
* @return void
*/
protected function moveQueueItem(string $queueId, string $fromDir, string $toDir): void
{
$fromPath = $this->queuePath . '/' . $fromDir . '/' . $queueId . '.json';
$toPath = $this->queuePath . '/' . $toDir . '/' . $queueId . '.json';
if (file_exists($fromPath)) {
rename($fromPath, $toPath);
}
}
/**
* Get all pending items
*
* @return array
*/
protected function getPendingItems(): array
{
return $this->getItemsInDirectory('pending');
}
/**
* Get items in a specific directory
*
* @param string $directory
* @return array
*/
protected function getItemsInDirectory(string $directory): array
{
$items = [];
$path = $this->queuePath . '/' . $directory;
if (!is_dir($path)) {
return $items;
}
$files = glob($path . '/*.json');
foreach ($files as $file) {
$jsonFile = JsonFile::instance($file);
$items[] = $jsonFile->content();
}
return $items;
}
/**
* Reconstruct a job from queue item
*
* @param array $item
* @return Job|null
*/
protected function reconstructJob(array $item): ?Job
{
// GHSA-vj3m-2g9h-vm4p (#1): refuse to unserialize a queue item whose
// HMAC is missing or doesn't match — a tampered or attacker-planted
// queue file could otherwise inject a forged Job for direct RCE.
if (isset($item['serialized_job'], $item['serialized_job_hmac'])) {
$serialized = base64_decode((string) $item['serialized_job'], true);
if ($serialized !== false) {
$expected = hash_hmac('sha256', $serialized, Security::getNonceKey());
if (hash_equals((string) $item['serialized_job_hmac'], $expected)) {
try {
// Defense in depth: the HMAC check above already rejects
// tampered items, but restrict deserialization to Job to
// avoid instantiating arbitrary classes (PHP Object Injection).
$job = unserialize($serialized, ['allowed_classes' => [Job::class]]);
if ($job instanceof Job) {
return $job;
}
} catch (\Exception) {
return null;
}
}
}
// HMAC missing/mismatched/decode failed — fall through to the
// structured-fields rebuild below so legitimate queue items
// written before this fix still run, but without trusting their
// serialized state.
}
// Create a new job from command
if (isset($item['command'])) {
$args = $item['arguments'] ?? [];
$job = new Job($item['command'], $args, $item['job_id']);
return $job;
}
return null;
}
/**
* Calculate retry time with exponential backoff
*
* @param int $attempts
* @return string
*/
protected function calculateRetryTime(int $attempts): string
{
$backoffSeconds = min(2 ** $attempts * 60, 3600); // Max 1 hour
$retryTime = new \DateTime();
$retryTime->modify("+{$backoffSeconds} seconds");
return $retryTime->format('c');
}
/**
* Clean up old completed items
*
* @return void
*/
protected function cleanupCompleted(): void
{
$items = $this->getItemsInDirectory('completed');
$cutoff = new \DateTime('-24 hours');
foreach ($items as $item) {
if (isset($item['created_at'])) {
$createdAt = new \DateTime($item['created_at']);
if ($createdAt < $cutoff) {
$this->deleteQueueItem($item['id'], 'completed');
}
}
}
}
/**
* Count completed jobs today
*
* @return int
*/
protected function countCompletedToday(): int
{
$items = $this->getItemsInDirectory('completed');
$today = new \DateTime('today');
$count = 0;
foreach ($items as $item) {
if (isset($item['created_at'])) {
$createdAt = new \DateTime($item['created_at']);
if ($createdAt >= $today) {
$count++;
}
}
}
return $count;
}
/**
* Acquire lock for queue operations
*
* @return bool
*/
protected function lock(): bool
{
$attempts = 0;
$maxAttempts = 50; // 5 seconds total
while ($attempts < $maxAttempts) {
// Check if lock file exists and is stale (older than 30 seconds)
if (file_exists($this->lockFile)) {
$lockAge = time() - filemtime($this->lockFile);
if ($lockAge > 30) {
// Stale lock, remove it
@unlink($this->lockFile);
}
}
// Try to acquire lock atomically
$handle = @fopen($this->lockFile, 'x');
if ($handle !== false) {
fclose($handle);
return true;
}
$attempts++;
usleep(100000); // 100ms
}
// Could not acquire lock
return false;
}
/**
* Release queue lock
*
* @return void
*/
protected function unlock(): void
{
if (file_exists($this->lockFile)) {
unlink($this->lockFile);
}
}
}