-
-
Notifications
You must be signed in to change notification settings - Fork 87
/
Worker.php
315 lines (260 loc) · 11.4 KB
/
Worker.php
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
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Messenger;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Clock\Clock;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;
use Symfony\Component\Messenger\Event\WorkerMessageHandledEvent;
use Symfony\Component\Messenger\Event\WorkerMessageReceivedEvent;
use Symfony\Component\Messenger\Event\WorkerRateLimitedEvent;
use Symfony\Component\Messenger\Event\WorkerRunningEvent;
use Symfony\Component\Messenger\Event\WorkerStartedEvent;
use Symfony\Component\Messenger\Event\WorkerStoppedEvent;
use Symfony\Component\Messenger\Exception\EnvelopeAwareExceptionInterface;
use Symfony\Component\Messenger\Exception\RejectRedeliveredMessageException;
use Symfony\Component\Messenger\Exception\RuntimeException;
use Symfony\Component\Messenger\Stamp\AckStamp;
use Symfony\Component\Messenger\Stamp\ConsumedByWorkerStamp;
use Symfony\Component\Messenger\Stamp\FlushBatchHandlersStamp;
use Symfony\Component\Messenger\Stamp\NoAutoAckStamp;
use Symfony\Component\Messenger\Stamp\ReceivedStamp;
use Symfony\Component\Messenger\Stamp\TransportMessageIdStamp;
use Symfony\Component\Messenger\Transport\Receiver\KeepaliveReceiverInterface;
use Symfony\Component\Messenger\Transport\Receiver\QueueReceiverInterface;
use Symfony\Component\Messenger\Transport\Receiver\ReceiverInterface;
use Symfony\Component\RateLimiter\LimiterInterface;
/**
* @author Samuel Roze <[email protected]>
* @author Tobias Schultze <http://tobion.de>
*
* @final
*/
class Worker
{
private bool $shouldStop = false;
private WorkerMetadata $metadata;
private array $acks = [];
private \SplObjectStorage $unacks;
/**
* @var \SplObjectStorage<object, array{0: string, 1: Envelope}>
*/
private \SplObjectStorage $keepalives;
/**
* @param ReceiverInterface[] $receivers Where the key is the transport name
*/
public function __construct(
private array $receivers,
private MessageBusInterface $bus,
private ?EventDispatcherInterface $eventDispatcher = null,
private ?LoggerInterface $logger = null,
private ?array $rateLimiters = null,
private ClockInterface $clock = new Clock(),
) {
$this->metadata = new WorkerMetadata([
'transportNames' => array_keys($receivers),
]);
$this->unacks = new \SplObjectStorage();
$this->keepalives = new \SplObjectStorage();
}
/**
* Receive the messages and dispatch them to the bus.
*
* Valid options are:
* * sleep (default: 1000000): Time in microseconds to sleep after no messages are found
* * queues: The queue names to consume from, instead of consuming from all queues. When this is used, all receivers must implement the QueueReceiverInterface
*/
public function run(array $options = []): void
{
$options = array_merge([
'sleep' => 1000000,
], $options);
$queueNames = $options['queues'] ?? null;
$this->metadata->set(['queueNames' => $queueNames]);
$this->eventDispatcher?->dispatch(new WorkerStartedEvent($this));
if ($queueNames) {
// if queue names are specified, all receivers must implement the QueueReceiverInterface
foreach ($this->receivers as $transportName => $receiver) {
if (!$receiver instanceof QueueReceiverInterface) {
throw new RuntimeException(\sprintf('Receiver for "%s" does not implement "%s".', $transportName, QueueReceiverInterface::class));
}
}
}
while (!$this->shouldStop) {
$envelopeHandled = false;
$envelopeHandledStart = $this->clock->now();
foreach ($this->receivers as $transportName => $receiver) {
if ($queueNames) {
$envelopes = $receiver->getFromQueues($queueNames);
} else {
$envelopes = $receiver->get();
}
foreach ($envelopes as $envelope) {
$envelopeHandled = true;
if ($receiver instanceof KeepaliveReceiverInterface) {
$this->keepalives[$envelope->getMessage()] = [$transportName, $envelope];
}
$this->rateLimit($transportName);
$this->handleMessage($envelope, $transportName);
$this->eventDispatcher?->dispatch(new WorkerRunningEvent($this, false));
if ($this->shouldStop) {
break 2;
}
}
// after handling a single receiver, quit and start the loop again
// this should prevent multiple lower priority receivers from
// blocking too long before the higher priority are checked
if ($envelopeHandled) {
gc_collect_cycles();
break;
}
}
if (!$envelopeHandled && $this->flush(false)) {
continue;
}
if (!$envelopeHandled) {
$this->eventDispatcher?->dispatch(new WorkerRunningEvent($this, true));
if (0 < $sleep = (int) ($options['sleep'] - 1e6 * ($this->clock->now()->format('U.u') - $envelopeHandledStart->format('U.u')))) {
$this->clock->sleep($sleep / 1e6);
}
}
}
$this->flush(true);
$this->eventDispatcher?->dispatch(new WorkerStoppedEvent($this));
}
private function handleMessage(Envelope $envelope, string $transportName): void
{
$event = new WorkerMessageReceivedEvent($envelope, $transportName);
$this->eventDispatcher?->dispatch($event);
$envelope = $event->getEnvelope();
if (!$event->shouldHandle()) {
return;
}
$acked = false;
$ack = function (Envelope $envelope, ?\Throwable $e = null) use ($transportName, &$acked) {
$acked = true;
$this->acks[] = [$transportName, $envelope, $e];
};
try {
$e = null;
$envelope = $this->bus->dispatch($envelope->with(new ReceivedStamp($transportName), new ConsumedByWorkerStamp(), new AckStamp($ack)));
} catch (\Throwable $e) {
}
$noAutoAckStamp = $envelope->last(NoAutoAckStamp::class);
if (!$acked && !$noAutoAckStamp) {
$this->acks[] = [$transportName, $envelope, $e];
} elseif ($noAutoAckStamp) {
$this->unacks[$noAutoAckStamp->getHandlerDescriptor()->getBatchHandler()] = [$envelope->withoutAll(AckStamp::class), $transportName];
}
$this->ack();
}
private function ack(): bool
{
$acks = $this->acks;
$this->acks = [];
foreach ($acks as [$transportName, $envelope, $e]) {
$receiver = $this->receivers[$transportName];
if (null !== $e) {
if ($rejectFirst = $e instanceof RejectRedeliveredMessageException) {
// redelivered messages are rejected first so that continuous failures in an event listener or while
// publishing for retry does not cause infinite redelivery loops
unset($this->keepalives[$envelope->getMessage()]);
$receiver->reject($envelope);
}
if ($e instanceof EnvelopeAwareExceptionInterface && null !== $e->getEnvelope()) {
$envelope = $e->getEnvelope();
}
$failedEvent = new WorkerMessageFailedEvent($envelope, $transportName, $e);
$this->eventDispatcher?->dispatch($failedEvent);
$envelope = $failedEvent->getEnvelope();
if (!$rejectFirst) {
unset($this->keepalives[$envelope->getMessage()]);
$receiver->reject($envelope);
}
continue;
}
$handledEvent = new WorkerMessageHandledEvent($envelope, $transportName);
$this->eventDispatcher?->dispatch($handledEvent);
$envelope = $handledEvent->getEnvelope();
if (null !== $this->logger) {
$message = $envelope->getMessage();
$context = [
'class' => $message::class,
'message_id' => $envelope->last(TransportMessageIdStamp::class)?->getId(),
];
$this->logger->info('{class} was handled successfully (acknowledging to transport).', $context);
}
unset($this->keepalives[$envelope->getMessage()]);
$receiver->ack($envelope);
}
return (bool) $acks;
}
private function rateLimit(string $transportName): void
{
if (!$this->rateLimiters) {
return;
}
if (!\array_key_exists($transportName, $this->rateLimiters)) {
return;
}
/** @var LimiterInterface $rateLimiter */
$rateLimiter = $this->rateLimiters[$transportName]->create();
if ($rateLimiter->consume()->isAccepted()) {
return;
}
$this->logger?->info('Transport {transport} is being rate limited, waiting for token to become available...', ['transport' => $transportName]);
$this->eventDispatcher?->dispatch(new WorkerRateLimitedEvent($rateLimiter, $transportName));
$rateLimiter->reserve()->wait();
$rateLimiter->consume();
}
private function flush(bool $force): bool
{
$unacks = $this->unacks;
if (!$unacks->count()) {
return false;
}
$this->unacks = new \SplObjectStorage();
foreach ($unacks as $batchHandler) {
[$envelope, $transportName] = $unacks[$batchHandler];
try {
$this->bus->dispatch($envelope->with(new FlushBatchHandlersStamp($force)));
$envelope = $envelope->withoutAll(NoAutoAckStamp::class);
unset($unacks[$batchHandler], $batchHandler);
} catch (\Throwable $e) {
$this->acks[] = [$transportName, $envelope, $e];
}
}
return $this->ack();
}
public function stop(): void
{
$this->logger?->info('Stopping worker.', ['transport_names' => $this->metadata->getTransportNames()]);
$this->shouldStop = true;
}
public function keepalive(?int $seconds): void
{
foreach ($this->keepalives as $message) {
[$transportName, $envelope] = $this->keepalives[$message];
if (!$this->receivers[$transportName] instanceof KeepaliveReceiverInterface) {
throw new RuntimeException(\sprintf('Receiver for "%s" does not implement "%s".', $transportName, KeepaliveReceiverInterface::class));
}
$this->logger?->info('Sending keepalive request.', [
'transport' => $transportName,
'message_id' => $envelope->last(TransportMessageIdStamp::class)?->getId(),
]);
$this->receivers[$transportName]->keepalive($envelope, $seconds);
}
}
public function getMetadata(): WorkerMetadata
{
return $this->metadata;
}
}