Repository navigation
Expand file tree
/
Copy pathTaskLockBagMiddleware.php
More file actions
69 lines (55 loc) · 1.95 KB
/
Copy pathTaskLockBagMiddleware.php
File metadata and controls
69 lines (55 loc) · 1.95 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
<?php
declare(strict_types=1);
namespace SchedulerBundle\Middleware;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use SchedulerBundle\Exception\RuntimeException;
use SchedulerBundle\SchedulerInterface;
use SchedulerBundle\Task\TaskInterface;
use SchedulerBundle\TaskBag\AccessLockBag;
use SchedulerBundle\Worker\WorkerInterface;
use Symfony\Component\Lock\Key;
use Symfony\Component\Lock\LockFactory;
use function sprintf;
/**
* @author Guillaume Loulier <contact@guillaumeloulier.fr>
*/
final class TaskLockBagMiddleware implements PostExecutionMiddlewareInterface, OrderedMiddlewareInterface
{
private const TASK_LOCK_MASK = '_symfony_scheduler_foo_';
private LoggerInterface $logger;
public function __construct(
private LockFactory $lockFactory,
?LoggerInterface $logger = null
) {
$this->logger = $logger ?? new NullLogger();
}
/**
* {@inheritdoc}
*/
public function postExecute(TaskInterface $task, WorkerInterface $worker): void
{
$accessLockBag = $task->getAccessLockBag();
if (!$accessLockBag instanceof AccessLockBag) {
throw new RuntimeException(message: sprintf('The task "%s" must be linked to an access lock bag, consider using %s::execute() or %s::schedule()', $task->getName(), WorkerInterface::class, SchedulerInterface::class));
}
if (!$accessLockBag->getKey() instanceof Key) {
return;
}
$lock = $this->lockFactory->createLockFromKey(key: $accessLockBag->getKey());
$lock->release();
$this->logger->info(message: sprintf('The lock for task "%s" has been released', $task->getName()));
$task->setAccessLockBag();
}
/**
* {@inheritdoc}
*/
public function getPriority(): int
{
return 5;
}
public static function createKey(TaskInterface $task): Key
{
return new Key(resource: sprintf('%s_%s', self::TASK_LOCK_MASK, $task->getName()));
}
}