forked from symfony/amqp-messenger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnection.php
614 lines (518 loc) · 21.9 KB
/
Connection.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
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
609
610
611
612
613
614
<?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\Bridge\Amqp\Transport;
use Symfony\Component\Messenger\Exception\InvalidArgumentException;
use Symfony\Component\Messenger\Exception\LogicException;
use Symfony\Component\Messenger\Exception\TransportException;
/**
* An AMQP connection.
*
* @author Samuel Roze <[email protected]>
*
* @final
*/
class Connection
{
private const ARGUMENTS_AS_INTEGER = [
'x-delay',
'x-expires',
'x-max-length',
'x-max-length-bytes',
'x-max-priority',
'x-message-ttl',
];
/**
* @see https://github.com/php-amqp/php-amqp/blob/master/amqp_connection_resource.h
*/
private const AVAILABLE_OPTIONS = [
'host',
'port',
'vhost',
'user',
'login',
'password',
'queues',
'exchange',
'delay',
'auto_setup',
'prefetch_count',
'retry',
'persistent',
'frame_max',
'channel_max',
'heartbeat',
'read_timeout',
'write_timeout',
'confirm_timeout',
'connect_timeout',
'rpc_timeout',
'cacert',
'cert',
'key',
'verify',
'sasl_method',
];
private const AVAILABLE_QUEUE_OPTIONS = [
'binding_keys',
'binding_arguments',
'flags',
'arguments',
];
private const AVAILABLE_EXCHANGE_OPTIONS = [
'name',
'type',
'default_publish_routing_key',
'flags',
'arguments',
];
private $connectionOptions;
private $exchangeOptions;
private $queuesOptions;
private $amqpFactory;
private $autoSetupExchange;
private $autoSetupDelayExchange;
/**
* @var \AMQPChannel|null
*/
private $amqpChannel;
/**
* @var \AMQPExchange|null
*/
private $amqpExchange;
/**
* @var \AMQPQueue[]|null
*/
private $amqpQueues = [];
/**
* @var \AMQPExchange|null
*/
private $amqpDelayExchange;
/**
* @var int
*/
private $lastActivityTime = 0;
public function __construct(array $connectionOptions, array $exchangeOptions, array $queuesOptions, ?AmqpFactory $amqpFactory = null)
{
if (!\extension_loaded('amqp')) {
throw new LogicException(sprintf('You cannot use the "%s" as the "amqp" extension is not installed.', __CLASS__));
}
$this->connectionOptions = array_replace_recursive([
'delay' => [
'exchange_name_pattern' => 'delay_%exchange_name%',
'queue_name_pattern' => 'delay_%exchange_name%',
'queue_expires' => 0,
],
], $connectionOptions);
$this->autoSetupExchange = $this->autoSetupDelayExchange = $connectionOptions['auto_setup'] ?? true;
$this->exchangeOptions = $exchangeOptions;
$this->queuesOptions = $queuesOptions;
$this->amqpFactory = $amqpFactory ?? new AmqpFactory();
}
/**
* Creates a connection based on the DSN and options.
*
* Available options:
*
* * host: Hostname of the AMQP service
* * port: Port of the AMQP service
* * vhost: Virtual Host to use with the AMQP service
* * user|login: Username to use to connect the AMQP service
* * password: Password to use to connect to the AMQP service
* * read_timeout: Timeout in for income activity. Note: 0 or greater seconds. May be fractional.
* * write_timeout: Timeout in for outcome activity. Note: 0 or greater seconds. May be fractional.
* * connect_timeout: Connection timeout. Note: 0 or greater seconds. May be fractional.
* * confirm_timeout: Timeout in seconds for confirmation, if none specified transport will not wait for message confirmation. Note: 0 or greater seconds. May be fractional.
* * queues[name]: An array of queues, keyed by the name
* * binding_keys: The binding keys (if any) to bind to this queue
* * binding_arguments: Arguments to be used while binding the queue.
* * flags: Queue flags (Default: AMQP_DURABLE)
* * arguments: Extra arguments
* * exchange:
* * name: Name of the exchange
* * type: Type of exchange (Default: fanout)
* * default_publish_routing_key: Routing key to use when publishing, if none is specified on the message
* * flags: Exchange flags (Default: AMQP_DURABLE)
* * arguments: Extra arguments
* * delay:
* * exchange_name_pattern: Pattern to use to create the delay exchange (Default: "delay_%exchange_name%")
* * queue_name_pattern: Pattern to use to create the delay queues (Default: "delay_%exchange_name%")
* * queue_expires: Controls for how long a delay queue can be unused before it is automatically deleted. Note: 0 or greater milliseconds.
* * auto_setup: Enable or not the auto-setup of queues and exchanges (Default: true)
*
* * Connection tuning options (see http://www.rabbitmq.com/amqp-0-9-1-reference.html#connection.tune for details):
* * channel_max: Specifies highest channel number that the server permits. 0 means standard extension limit
* (see PHP_AMQP_MAX_CHANNELS constant)
* * frame_max: The largest frame size that the server proposes for the connection, including frame header
* and end-byte. 0 means standard extension limit (depends on librabbimq default frame size limit)
* * heartbeat: The delay, in seconds, of the connection heartbeat that the server wants.
* 0 means the server does not want a heartbeat. Note, librabbitmq has limited heartbeat support,
* which means heartbeats checked only during blocking calls.
*
* TLS support (see https://www.rabbitmq.com/ssl.html for details):
* * cacert: Path to the CA cert file in PEM format.
* * cert: Path to the client certificate in PEM format.
* * key: Path to the client key in PEM format.
* * verify: Enable or disable peer verification. If peer verification is enabled then the common name in the
* server certificate must match the server name. Peer verification is enabled by default.
*/
public static function fromDsn(string $dsn, array $options = [], ?AmqpFactory $amqpFactory = null): self
{
if (false === $params = parse_url($dsn)) {
// this is a valid URI that parse_url cannot handle when you want to pass all parameters as options
if (!\in_array($dsn, ['amqp://', 'amqps://'])) {
throw new InvalidArgumentException('The given AMQP DSN is invalid.');
}
$params = [];
}
$useAmqps = 0 === strpos($dsn, 'amqps://');
$pathParts = isset($params['path']) ? explode('/', trim($params['path'], '/')) : [];
$exchangeName = $pathParts[1] ?? 'messages';
parse_str($params['query'] ?? '', $parsedQuery);
$port = $useAmqps ? 5671 : 5672;
$amqpOptions = array_replace_recursive([
'host' => $params['host'] ?? 'localhost',
'port' => $params['port'] ?? $port,
'vhost' => isset($pathParts[0]) ? urldecode($pathParts[0]) : '/',
'exchange' => [
'name' => $exchangeName,
],
], $options, $parsedQuery);
self::validateOptions($amqpOptions);
if (isset($params['user'])) {
$amqpOptions['login'] = rawurldecode($params['user']);
}
if (isset($params['pass'])) {
$amqpOptions['password'] = rawurldecode($params['pass']);
}
if (!isset($amqpOptions['queues'])) {
$amqpOptions['queues'][$exchangeName] = [];
}
$exchangeOptions = $amqpOptions['exchange'];
$queuesOptions = $amqpOptions['queues'];
unset($amqpOptions['queues'], $amqpOptions['exchange']);
if (isset($amqpOptions['auto_setup'])) {
$amqpOptions['auto_setup'] = filter_var($amqpOptions['auto_setup'], \FILTER_VALIDATE_BOOLEAN);
}
$queuesOptions = array_map(function ($queueOptions) {
if (!\is_array($queueOptions)) {
$queueOptions = [];
}
if (\is_array($queueOptions['arguments'] ?? false)) {
$queueOptions['arguments'] = self::normalizeQueueArguments($queueOptions['arguments']);
}
return $queueOptions;
}, $queuesOptions);
if (!$useAmqps) {
unset($amqpOptions['cacert'], $amqpOptions['cert'], $amqpOptions['key'], $amqpOptions['verify']);
}
if ($useAmqps && !self::hasCaCertConfigured($amqpOptions)) {
throw new InvalidArgumentException('No CA certificate has been provided. Set "amqp.cacert" in your php.ini or pass the "cacert" parameter in the DSN to use SSL. Alternatively, you can use amqp:// to use without SSL.');
}
return new self($amqpOptions, $exchangeOptions, $queuesOptions, $amqpFactory);
}
private static function validateOptions(array $options): void
{
if (0 < \count($invalidOptions = array_diff(array_keys($options), self::AVAILABLE_OPTIONS))) {
trigger_deprecation('symfony/messenger', '5.1', 'Invalid option(s) "%s" passed to the AMQP Messenger transport. Passing invalid options is deprecated.', implode('", "', $invalidOptions));
}
if (isset($options['prefetch_count'])) {
trigger_deprecation('symfony/messenger', '5.3', 'The "prefetch_count" option passed to the AMQP Messenger transport has no effect and should not be used.');
}
if (\is_array($options['queues'] ?? false)) {
foreach ($options['queues'] as $queue) {
if (!\is_array($queue)) {
continue;
}
if (0 < \count($invalidQueueOptions = array_diff(array_keys($queue), self::AVAILABLE_QUEUE_OPTIONS))) {
trigger_deprecation('symfony/messenger', '5.1', 'Invalid queue option(s) "%s" passed to the AMQP Messenger transport. Passing invalid queue options is deprecated.', implode('", "', $invalidQueueOptions));
}
}
}
if (\is_array($options['exchange'] ?? false)
&& 0 < \count($invalidExchangeOptions = array_diff(array_keys($options['exchange']), self::AVAILABLE_EXCHANGE_OPTIONS))) {
trigger_deprecation('symfony/messenger', '5.1', 'Invalid exchange option(s) "%s" passed to the AMQP Messenger transport. Passing invalid exchange options is deprecated.', implode('", "', $invalidExchangeOptions));
}
}
private static function normalizeQueueArguments(array $arguments): array
{
foreach (self::ARGUMENTS_AS_INTEGER as $key) {
if (!\array_key_exists($key, $arguments)) {
continue;
}
if (!is_numeric($arguments[$key])) {
throw new InvalidArgumentException(sprintf('Integer expected for queue argument "%s", "%s" given.', $key, get_debug_type($arguments[$key])));
}
$arguments[$key] = (int) $arguments[$key];
}
return $arguments;
}
private static function hasCaCertConfigured(array $amqpOptions): bool
{
return (isset($amqpOptions['cacert']) && '' !== $amqpOptions['cacert']) || '' !== \ini_get('amqp.cacert');
}
/**
* @throws \AMQPException
*/
public function publish(string $body, array $headers = [], int $delayInMs = 0, ?AmqpStamp $amqpStamp = null): void
{
$this->clearWhenDisconnected();
if (0 !== $delayInMs) {
$this->publishWithDelay($body, $headers, $delayInMs, $amqpStamp);
return;
}
$this->publishNow($body, $headers, $amqpStamp);
}
/**
* Returns an approximate count of the messages in defined queues.
*/
public function countMessagesInQueues(): int
{
return array_sum(array_map(function ($queueName) {
return $this->queue($queueName)->declareQueue();
}, $this->getQueueNames()));
}
/**
* @throws \AMQPException
*/
private function publishWithDelay(string $body, array $headers, int $delay, ?AmqpStamp $amqpStamp = null): void
{
if ($this->autoSetupDelayExchange) {
$this->setupDelayExchangeAndQueues();
}
$attributes = $this->getPublishAttributes($headers, $amqpStamp);
$attributes['expiration'] = $delay;
$this->publishOnExchange(
$this->delayExchange(),
$body,
$this->getRoutingKeyForMessage($amqpStamp),
$this->getPublishFlags($amqpStamp),
$attributes
);
}
/**
* @throws \AMQPException
*/
private function publishNow(string $body, array $headers, ?AmqpStamp $amqpStamp = null): void
{
if ($this->autoSetupExchange) {
$this->setupExchangeAndQueues();
}
$this->publishOnExchange(
$this->exchange(),
$body,
$this->getRoutingKeyForMessage($amqpStamp),
$this->getPublishFlags($amqpStamp),
$this->getPublishAttributes($headers, $amqpStamp)
);
}
private function getPublishAttributes(array $headers = [], ?AmqpStamp $amqpStamp = null): array
{
$attributes = $amqpStamp ? $amqpStamp->getAttributes() : [];
$attributes['headers'] = array_merge($attributes['headers'] ?? [], $headers);
$attributes['delivery_mode'] = $attributes['delivery_mode'] ?? 2;
$attributes['timestamp'] = $attributes['timestamp'] ?? time();
return $attributes;
}
private function getPublishFlags(?AmqpStamp $amqpStamp = null): int
{
return $amqpStamp ? $amqpStamp->getFlags() : \AMQP_NOPARAM;
}
private function publishOnExchange(\AMQPExchange $exchange, string $body, ?string $routingKey = null, int $flags = \AMQP_NOPARAM, array $attributes = []): void
{
$this->lastActivityTime = time();
$exchange->publish($body, $routingKey, $flags, $attributes);
if ('' !== ($this->connectionOptions['confirm_timeout'] ?? '')) {
$this->channel()->waitForConfirm((float) $this->connectionOptions['confirm_timeout']);
}
}
private function delayExchange(): \AMQPExchange
{
if (!isset($this->amqpDelayExchange)) {
$this->amqpDelayExchange = $this->amqpFactory->createExchange($this->channel());
$this->amqpDelayExchange->setName($this->getDelayExchangeName());
$this->amqpDelayExchange->setType(\AMQP_EX_TYPE_FANOUT);
$this->amqpDelayExchange->setFlags(\AMQP_DURABLE);
}
return $this->amqpDelayExchange;
}
private function getDelayExchangeName(): string
{
return str_replace(
'%exchange_name%',
$this->exchangeOptions['name'],
$this->connectionOptions['delay']['exchange_name_pattern']
);
}
/**
* Creates a delay queue that will delay for a certain amount of time.
*
* This works by setting message TTL (expiration argument) for the delay and pointing
* the dead letter exchange to the original exchange. The result
* is that after the TTL, the message is sent to the dead-letter-exchange,
* which is the original exchange, resulting on it being put back into
* the original queue.
*/
private function createDelayQueue(): \AMQPQueue
{
$queue = $this->amqpFactory->createQueue($this->channel());
$queue->setName($this->getDelayQueueName());
$queue->setFlags(\AMQP_DURABLE);
$expires = (int)($this->connectionOptions['delay']['queue_expires'] ?? 0);
$arguments = ['x-dead-letter-exchange' => $this->exchangeOptions['name']];
if ($expires > 0) {
$arguments['x-expires'] = $expires;
}
$queue->setArguments($arguments);
return $queue;
}
private function getDelayQueueName(): string
{
return str_replace(
'%exchange_name%',
$this->exchangeOptions['name'],
$this->connectionOptions['delay']['queue_name_pattern']
);
}
/**
* Gets a message from the specified queue.
*
* @throws \AMQPException
*/
public function get(string $queueName): ?\AMQPEnvelope
{
$this->clearWhenDisconnected();
if ($this->autoSetupExchange) {
$this->setupExchangeAndQueues();
}
if (false !== $message = $this->queue($queueName)->get()) {
return $message;
}
return null;
}
public function ack(\AMQPEnvelope $message, string $queueName): bool
{
return $this->queue($queueName)->ack($message->getDeliveryTag()) ?? true;
}
public function nack(\AMQPEnvelope $message, string $queueName, int $flags = \AMQP_NOPARAM): bool
{
return $this->queue($queueName)->nack($message->getDeliveryTag(), $flags) ?? true;
}
public function setup(): void
{
$this->setupExchangeAndQueues();
$this->setupDelayExchangeAndQueues();
}
private function setupExchangeAndQueues(): void
{
$this->exchange()->declareExchange();
foreach ($this->queuesOptions as $queueName => $queueConfig) {
$this->queue($queueName)->declareQueue();
foreach ($queueConfig['binding_keys'] ?? [null] as $bindingKey) {
$this->queue($queueName)->bind($this->exchangeOptions['name'], $bindingKey, $queueConfig['binding_arguments'] ?? []);
}
}
$this->autoSetupExchange = false;
}
private function setupDelayExchangeAndQueues(): void
{
$this->delayExchange()->declareExchange();
$queue = $this->createDelayQueue();
$queue->declareQueue();
$queue->bind($this->getDelayExchangeName());
$this->autoSetupDelayExchange = false;
}
/**
* @return string[]
*/
public function getQueueNames(): array
{
return array_keys($this->queuesOptions);
}
public function channel(): \AMQPChannel
{
if (!isset($this->amqpChannel)) {
$connection = $this->amqpFactory->createConnection($this->connectionOptions);
$connectMethod = 'true' === ($this->connectionOptions['persistent'] ?? 'false') ? 'pconnect' : 'connect';
try {
$connection->{$connectMethod}();
} catch (\AMQPConnectionException $e) {
throw new \AMQPException('Could not connect to the AMQP server. Please verify the provided DSN.', 0, $e);
}
$this->amqpChannel = $this->amqpFactory->createChannel($connection);
if ('' !== ($this->connectionOptions['confirm_timeout'] ?? '')) {
$this->amqpChannel->confirmSelect();
$this->amqpChannel->setConfirmCallback(
static function (): bool {
return false;
},
static function () {
throw new TransportException('Message publication failed due to a negative acknowledgment (nack) from the broker.');
}
);
}
$this->lastActivityTime = time();
} elseif (0 < ($this->connectionOptions['heartbeat'] ?? 0) && time() > $this->lastActivityTime + 2 * $this->connectionOptions['heartbeat']) {
$disconnectMethod = 'true' === ($this->connectionOptions['persistent'] ?? 'false') ? 'pdisconnect' : 'disconnect';
$this->amqpChannel->getConnection()->{$disconnectMethod}();
}
return $this->amqpChannel;
}
public function queue(string $queueName): \AMQPQueue
{
if (!isset($this->amqpQueues[$queueName])) {
$queueConfig = $this->queuesOptions[$queueName] ?? [];
$amqpQueue = $this->amqpFactory->createQueue($this->channel());
$amqpQueue->setName($queueName);
$amqpQueue->setFlags($queueConfig['flags'] ?? \AMQP_DURABLE);
if (isset($queueConfig['arguments'])) {
$amqpQueue->setArguments($queueConfig['arguments']);
}
$this->amqpQueues[$queueName] = $amqpQueue;
}
return $this->amqpQueues[$queueName];
}
public function exchange(): \AMQPExchange
{
if (!isset($this->amqpExchange)) {
$this->amqpExchange = $this->amqpFactory->createExchange($this->channel());
$this->amqpExchange->setName($this->exchangeOptions['name']);
$this->amqpExchange->setType($this->exchangeOptions['type'] ?? \AMQP_EX_TYPE_FANOUT);
$this->amqpExchange->setFlags($this->exchangeOptions['flags'] ?? \AMQP_DURABLE);
if (isset($this->exchangeOptions['arguments'])) {
$this->amqpExchange->setArguments($this->exchangeOptions['arguments']);
}
}
return $this->amqpExchange;
}
private function clearWhenDisconnected(): void
{
if (!$this->channel()->isConnected()) {
unset($this->amqpChannel, $this->amqpExchange, $this->amqpDelayExchange);
$this->amqpQueues = [];
}
}
private function getDefaultPublishRoutingKey(): ?string
{
return $this->exchangeOptions['default_publish_routing_key'] ?? null;
}
public function purgeQueues(): void
{
foreach ($this->getQueueNames() as $queueName) {
$this->queue($queueName)->purge();
}
}
private function getRoutingKeyForMessage(?AmqpStamp $amqpStamp): ?string
{
return (null !== $amqpStamp ? $amqpStamp->getRoutingKey() : null) ?? $this->getDefaultPublishRoutingKey();
}
}
if (!class_exists(\Symfony\Component\Messenger\Transport\AmqpExt\Connection::class, false)) {
class_alias(Connection::class, \Symfony\Component\Messenger\Transport\AmqpExt\Connection::class);
}