-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathQueue.php
More file actions
189 lines (157 loc) · 6.18 KB
/
Queue.php
File metadata and controls
189 lines (157 loc) · 6.18 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
<?php
declare(strict_types=1);
namespace Yiisoft\Queue;
use BackedEnum;
use Psr\Log\LoggerInterface;
use Yiisoft\Queue\Adapter\AdapterInterface;
use Yiisoft\Queue\Adapter\ImmediateProcessingAdapterInterface;
use Yiisoft\Queue\Cli\LoopInterface;
use Yiisoft\Queue\Exception\AdapterConfiguration\AdapterNotConfiguredException;
use Yiisoft\Queue\Message\MessageInterface;
use Yiisoft\Queue\Middleware\Push\AdapterPushHandler;
use Yiisoft\Queue\Middleware\Push\MessageHandlerPushInterface;
use Yiisoft\Queue\Middleware\Push\MiddlewarePushInterface;
use Yiisoft\Queue\Middleware\Push\PushMiddlewareDispatcher;
use Yiisoft\Queue\Middleware\Push\PushRequest;
use Yiisoft\Queue\Worker\WorkerInterface;
use Yiisoft\Queue\Message\IdEnvelope;
use Yiisoft\Queue\Provider\QueueProviderInterface;
final class Queue implements QueueInterface
{
/**
* @var array|array[]|callable[]|MiddlewarePushInterface[]|string[]
*/
private array $middlewareDefinitions;
private AdapterPushHandler $adapterPushHandler;
private string $name;
public function __construct(
private readonly WorkerInterface $worker,
private readonly LoopInterface $loop,
private readonly LoggerInterface $logger,
private readonly PushMiddlewareDispatcher $pushMiddlewareDispatcher,
string|BackedEnum $name = QueueProviderInterface::DEFAULT_QUEUE,
private ?AdapterInterface $adapter = null,
MiddlewarePushInterface|callable|array|string ...$middlewareDefinitions,
) {
$this->name = StringNormalizer::normalize($name);
$this->middlewareDefinitions = $middlewareDefinitions;
$this->adapterPushHandler = new AdapterPushHandler();
}
public function getName(): string
{
return $this->name;
}
public function push(
MessageInterface $message,
MiddlewarePushInterface|callable|array|string ...$middlewareDefinitions,
): MessageInterface {
$this->checkAdapter();
$this->logger->debug(
'Preparing to push message with handler name "{handlerName}".',
['handlerName' => $message->getHandlerName()],
);
$request = new PushRequest($message, $this->adapter);
$request = $this->pushMiddlewareDispatcher
->dispatch($request, $this->createPushHandler(...$middlewareDefinitions));
$message = $request->getMessage();
/** @var string $messageId */
$messageId = $message->getMetadata()[IdEnvelope::MESSAGE_ID_KEY] ?? 'null';
$this->logger->info(
'Pushed message with handler name "{handlerName}" to the queue. Assigned ID #{id}.',
['handlerName' => $message->getHandlerName(), 'id' => $messageId],
);
if ($request->getAdapter() instanceof ImmediateProcessingAdapterInterface) {
$this->handle($message);
}
return $message;
}
public function run(int $max = 0): int
{
$this->checkAdapter();
$this->logger->debug('Start processing queue messages.');
$count = 0;
$handlerCallback = function (MessageInterface $message) use (&$max, &$count): bool {
if (($max > 0 && $max <= $count) || !$this->handle($message)) {
return false;
}
$count++;
return true;
};
$this->adapter->runExisting($handlerCallback);
$this->logger->info(
'Processed {count} queue messages.',
['count' => $count],
);
return $count;
}
public function listen(): void
{
$this->checkAdapter();
$this->logger->info('Start listening to the queue.');
$this->adapter->subscribe(fn(MessageInterface $message) => $this->handle($message));
$this->logger->info('Finish listening to the queue.');
}
public function status(string|int $id): MessageStatus
{
$this->checkAdapter();
return $this->adapter->status($id);
}
public function withAdapter(AdapterInterface $adapter, string|BackedEnum|null $queueName = null): static
{
$new = clone $this;
$new->adapter = $adapter;
if ($queueName !== null) {
$new->name = StringNormalizer::normalize($queueName);
}
return $new;
}
public function withMiddlewares(MiddlewarePushInterface|callable|array|string ...$middlewareDefinitions): self
{
$instance = clone $this;
$instance->middlewareDefinitions = $middlewareDefinitions;
return $instance;
}
public function withMiddlewaresAdded(MiddlewarePushInterface|callable|array|string ...$middlewareDefinitions): self
{
$instance = clone $this;
$instance->middlewareDefinitions = [...array_values($instance->middlewareDefinitions), ...array_values($middlewareDefinitions)];
return $instance;
}
private function handle(MessageInterface $message): bool
{
$this->worker->process($message, $this);
return $this->loop->canContinue();
}
/**
* @psalm-assert AdapterInterface $this->adapter
*/
private function checkAdapter(): void
{
if ($this->adapter === null) {
throw new AdapterNotConfiguredException();
}
}
private function createPushHandler(MiddlewarePushInterface|callable|array|string ...$middlewares): MessageHandlerPushInterface
{
return new class (
$this->adapterPushHandler,
$this->pushMiddlewareDispatcher,
array_merge($this->middlewareDefinitions, $middlewares),
) implements MessageHandlerPushInterface {
public function __construct(
private readonly AdapterPushHandler $adapterPushHandler,
private readonly PushMiddlewareDispatcher $dispatcher,
/**
* @var array|array[]|callable[]|MiddlewarePushInterface[]|string[]
*/
private readonly array $middlewares,
) {}
public function handlePush(PushRequest $request): PushRequest
{
return $this->dispatcher
->withMiddlewares($this->middlewares)
->dispatch($request, $this->adapterPushHandler);
}
};
}
}