forked from cakephp/queue
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkerCommand.php
More file actions
245 lines (215 loc) · 8.23 KB
/
WorkerCommand.php
File metadata and controls
245 lines (215 loc) · 8.23 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
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org/)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org/)
* @link https://cakephp.org CakePHP(tm) Project
* @since 0.1.0
* @license https://opensource.org/licenses/MIT MIT License
*/
namespace Cake\Queue\Command;
use Cake\Command\Command;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Cake\Console\ConsoleOptionParser;
use Cake\Core\Configure;
use Cake\Core\ContainerInterface;
use Cake\Log\Log;
use Cake\Queue\Consumption\LimitAttemptsExtension;
use Cake\Queue\Consumption\LimitConsumedMessagesExtension;
use Cake\Queue\Consumption\RemoveUniqueJobIdFromCacheExtension;
use Cake\Queue\Listener\FailedJobsListener;
use Cake\Queue\Queue\Processor;
use Cake\Queue\QueueManager;
use DateTime;
use Enqueue\Consumption\ChainExtension;
use Enqueue\Consumption\Extension\LimitConsumptionTimeExtension;
use Enqueue\Consumption\Extension\LoggerExtension;
use Enqueue\Consumption\ExtensionInterface;
use Interop\Queue\Processor as InteropProcessor;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Worker command.
*/
class WorkerCommand extends Command
{
/**
* @var \Cake\Core\ContainerInterface|null
*/
protected ?ContainerInterface $container = null;
/**
* @param \Cake\Core\ContainerInterface|null $container DI container instance
*/
public function __construct(?ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* Get the command name.
*
* @return string
*/
public static function defaultName(): string
{
return 'queue worker';
}
/**
* Gets the option parser instance and configures it.
*
* @return \Cake\Console\ConsoleOptionParser
*/
public function getOptionParser(): ConsoleOptionParser
{
$parser = parent::getOptionParser();
$parser->addOption('config', [
'default' => 'default',
'help' => 'Name of a queue config to use',
'short' => 'c',
]);
$parser->addOption('queue', [
'help' => 'Name of queue to bind to. Defaults to the queue config (--config).',
'short' => 'Q',
]);
$parser->addOption('processor', [
'help' => 'Name of processor to bind to',
'default' => null,
'short' => 'p',
]);
$parser->addOption('logger', [
'help' => 'Name of a configured logger',
'default' => 'stdout',
'short' => 'l',
]);
$parser->addOption('max-jobs', [
'help' => 'Maximum number of jobs to process. Worker will exit after limit is reached.',
'default' => null,
'short' => 'i',
]);
$parser->addOption('max-runtime', [
'help' => 'Maximum number of seconds worker will run. Worker will exit after limit is reached.',
'default' => null,
'short' => 'r',
]);
$parser->addOption('max-attempts', [
'help' => 'Maximum number of times each job will be attempted.'
. ' Maximum attempts defined on a job will override this value.',
'default' => null,
'short' => 'a',
]);
$parser->setDescription(
'Runs a queue worker that consumes from the named queue.',
);
return $parser;
}
/**
* Creates and returns a QueueExtension object
*
* @param \Cake\Console\Arguments $args Arguments
* @param \Psr\Log\LoggerInterface $logger Logger instance.
* @return \Enqueue\Consumption\ExtensionInterface
*/
protected function getQueueExtension(Arguments $args, LoggerInterface $logger): ExtensionInterface
{
$limitAttempsExtension = new LimitAttemptsExtension((int)$args->getOption('max-attempts') ?: null);
$limitAttempsExtension->getEventManager()->on(new FailedJobsListener());
$configKey = (string)$args->getOption('config');
$config = QueueManager::getConfig($configKey);
$extensions = [
new LoggerExtension($logger),
$limitAttempsExtension,
];
if (!is_null($args->getOption('max-jobs'))) {
$maxJobs = (int)$args->getOption('max-jobs');
$extensions[] = new LimitConsumedMessagesExtension($maxJobs);
}
if (!is_null($args->getOption('max-runtime'))) {
$endTime = new DateTime(sprintf('+%d seconds', (int)$args->getOption('max-runtime')));
$extensions[] = new LimitConsumptionTimeExtension($endTime);
}
if (isset($config['uniqueCacheKey'])) {
$extensions[] = new RemoveUniqueJobIdFromCacheExtension($config['uniqueCacheKey']);
}
return new ChainExtension($extensions);
}
/**
* Creates and returns a LoggerInterface object
*
* @param \Cake\Console\Arguments $args Arguments
* @return \Psr\Log\LoggerInterface
*/
protected function getLogger(Arguments $args): LoggerInterface
{
$logger = null;
if (!empty($args->getOption('verbose'))) {
$logger = Log::engine((string)$args->getOption('logger'));
}
return $logger ?? new NullLogger();
}
/**
* Creates and returns a Processor object
*
* @param \Cake\Console\Arguments $args Arguments
* @param \Cake\Console\ConsoleIo $io ConsoleIo
* @param \Psr\Log\LoggerInterface $logger Logger instance
* @return \Interop\Queue\Processor
*/
protected function getProcessor(Arguments $args, ConsoleIo $io, LoggerInterface $logger): InteropProcessor
{
$configKey = (string)$args->getOption('config');
$config = QueueManager::getConfig($configKey);
$processorClass = $config['processor'] ?? Processor::class;
if (!class_exists($processorClass)) {
$io->error(sprintf(sprintf('Processor class %s not found', $processorClass)));
$this->abort();
}
if (!is_subclass_of($processorClass, InteropProcessor::class)) {
$io->error(sprintf(sprintf('Processor class %s must implement Interop\Queue\Processor', $processorClass)));
$this->abort();
}
return new $processorClass($logger, $this->container);
}
/**
* @param \Cake\Console\Arguments $args Arguments
* @param \Cake\Console\ConsoleIo $io ConsoleIo
* @return int
*/
public function execute(Arguments $args, ConsoleIo $io): int
{
$config = (string)$args->getOption('config');
if (!Configure::check(sprintf('Queue.%s', $config))) {
$io->error(sprintf('Configuration key "%s" was not found', $config));
$this->abort();
}
$logger = $this->getLogger($args);
$processor = $this->getProcessor($args, $io, $logger);
$extension = $this->getQueueExtension($args, $logger);
$hasListener = Configure::check(sprintf('Queue.%s.listener', $config));
if ($hasListener) {
$listenerClassName = Configure::read(sprintf('Queue.%s.listener', $config));
if (!class_exists($listenerClassName)) {
$io->error(sprintf('Listener class %s not found', $listenerClassName));
$this->abort();
}
/** @var \Cake\Event\EventListenerInterface $listener */
$listener = new $listenerClassName();
if ($processor instanceof Processor) {
$processor->getEventManager()->on($listener);
}
}
$client = QueueManager::engine($config);
$queue = $args->getOption('queue')
? (string)$args->getOption('queue')
: Configure::read("Queue.{$config}.queue", 'default');
$processorName = $args->getOption('processor') ? (string)$args->getOption('processor') : 'default';
$client->bindTopic($queue, $processor, $processorName);
$client->consume($extension);
return self::CODE_SUCCESS;
}
}