-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducer.php
More file actions
203 lines (171 loc) · 6.35 KB
/
Copy pathProducer.php
File metadata and controls
203 lines (171 loc) · 6.35 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
<?php
namespace Tests\Support\Helper;
use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
class Producer implements \ADT\BackgroundQueue\Broker\Producer
{
public ?AMQPStreamConnection $connection = null;
public ?AMQPChannel $channel = null;
private array $initQueues = [];
/**
* Zprávy se zpožděnou recirkulací (publikované s "expiration", tj. postponeBy).
* Reálný Producer je posílá do TTL fronty "<prioritní_fronta>_<expiration>" s dead-letter zpět do prioritní
* fronty, takže se v ní objeví až po uplynutí "expiration" ms. Tady to modelujeme deterministicky in-memory:
* zpožděná zpráva se nevydá, dokud jsou k dispozici okamžité zprávy. Bez toho by se nekonečně recirkulující
* _processWaitingJobs (běží na nejvyšší prioritě) okamžitě vracel do své fronty a zablokoval consume() smyčku
* (livelock). V produkci k tomu nedochází právě díky tomuto zpoždění, ne přes skutečné AMQP TTL fronty
* (ty by mezi testy protékaly a nafukovaly getMessageCount).
*
* @var array<int, array{queue: string, priority: int, id: string}>
*/
private array $delayedMessages = [];
/**
* Priorita se v RabbitMQ modeluje jako samostatná fronta "<queue>_<priority>"
* (viz reálný Producer / Manager::getQueueWithPriority). Helper to napodobuje,
* aby šel otestovat prioritní routing i konzumace v pořadí priorit.
*/
public function publish(string $id, string $queue, int $priority, ?int $expiration = null): void
{
// Zpožděné doručení (postponeBy): nevkládáme do prioritní fronty hned, ale do zpožděného bufferu,
// odkud se zpráva vydá až když nejsou žádné okamžité zprávy (viz $delayedMessages a consume()).
if ($expiration) {
$this->delayedMessages[] = ['queue' => $queue, 'priority' => $priority, 'id' => $id];
return;
}
$queueWithPriority = $queue . '_' . $priority;
$this->initQueue($queueWithPriority);
$this->getChannel()->basic_publish(new AMQPMessage($id), $queueWithPriority, '', true);
$this->getChannel()->wait_for_pending_acks();
}
public function publishDie(string $queue): void
{
}
public function publishNoop(): void
{
}
/**
* Zkonzumuje jednu zprávu z prioritních front základní fronty "general"
* v pořadí priorit (nižší číslo dřív), stejně jako reálný Consumer.
* Vrátí tělo zprávy (ID jobu) nebo null, pokud žádná není k dispozici.
*/
public function consume(?string $queue = null): ?string
{
$base = $queue ?? 'general';
// Nejdřív okamžité zprávy v pořadí priorit (nižší číslo dřív), stejně jako reálný Consumer.
foreach ($this->getSortedPriorityQueues($base) as $priorityQueue) {
$message = $this->getChannel()->basic_get($priorityQueue, true);
if ($message !== null) {
return $message->getBody();
}
}
// Žádná okamžitá zpráva -> "uplynulo zpoždění recirkulace", vydáme nejprioritnější zpožděnou zprávu.
return $this->popDelayedMessage($base);
}
public function purge(string $queue): void
{
$this->initQueue($queue);
$this->getChannel()->queue_purge($queue);
}
/**
* Vrátí počet zpráv ve frontě. Pokud je zadána základní fronta (např. "general"),
* sečte všechny její prioritní podfronty ("general_1", "general_2", ...).
*/
public function getMessageCount(string $queue): int
{
$total = 0;
foreach (array_keys($this->initQueues) as $declared) {
if ($this->matchesBaseQueue($declared, $queue)) {
list(, $messageCount,) = $this->getChannel()->queue_declare($declared, true);
$total += (int) $messageCount;
}
}
// Zpožděné zprávy jsou taky "v systému" (čekají na recirkulaci), takže je započítáme.
foreach ($this->delayedMessages as $message) {
if ($this->matchesBaseQueue($message['queue'] . '_' . $message['priority'], $queue)) {
$total++;
}
}
return $total;
}
/**
* Vydá (a odebere) nejprioritnější zpožděnou zprávu pro danou základní frontu, nebo null pokud žádná není.
*/
private function popDelayedMessage(string $base): ?string
{
$bestIndex = null;
foreach ($this->delayedMessages as $index => $message) {
if (!$this->matchesBaseQueue($message['queue'] . '_' . $message['priority'], $base)) {
continue;
}
if ($bestIndex === null || $message['priority'] < $this->delayedMessages[$bestIndex]['priority']) {
$bestIndex = $index;
}
}
if ($bestIndex === null) {
return null;
}
$id = $this->delayedMessages[$bestIndex]['id'];
unset($this->delayedMessages[$bestIndex]);
$this->delayedMessages = array_values($this->delayedMessages);
return $id;
}
private function matchesBaseQueue(string $declared, string $base): bool
{
return $declared === $base || str_starts_with($declared, $base . '_');
}
/**
* Seřadí dosud inicializované prioritní podfronty dané základní fronty vzestupně podle priority.
*
* @return string[]
*/
private function getSortedPriorityQueues(string $base): array
{
$queues = [];
foreach (array_keys($this->initQueues) as $declared) {
if (preg_match('/^' . preg_quote($base, '/') . '_(\d+)$/', $declared, $matches)) {
$queues[(int) $matches[1]] = $declared;
}
}
ksort($queues);
return array_values($queues);
}
private function initQueue($queue)
{
if (isset($this->initQueues[$queue])) {
return;
}
$exchange = $queue = $queue ?: 'general';
$args = [];
if ($queue === 'waiting') {
$args = new AMQPTable([
'x-dead-letter-exchange' => 'general',
]);
}
$this->getChannel()->queue_declare($queue, false, true, false, false, false, $args);
$this->getChannel()->exchange_declare($exchange, 'direct', false, true, false);
$this->getChannel()->queue_bind($queue, $exchange);
$this->initQueues[$queue] = true;
}
private function getConnection(): AMQPStreamConnection
{
if (!$this->connection) {
$this->connection = new AMQPStreamConnection($_ENV['PROJECT_RABBITMQ_HOST'], $_ENV['PROJECT_RABBITMQ_PORT'], $_ENV['PROJECT_RABBITMQ_USER'], $_ENV['PROJECT_RABBITMQ_PASSWORD']);
}
return $this->connection;
}
private function getChannel(): AMQPChannel
{
if (!$this->channel) {
$this->channel = $this->getConnection()->channel();
$this->channel->confirm_select();
}
return $this->channel;
}
public function __destruct()
{
$this->channel->close();
$this->connection->close();
}
}