-
Notifications
You must be signed in to change notification settings - Fork 23
/
EntryPoint.php
225 lines (194 loc) · 6.54 KB
/
EntryPoint.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
<?php
/**
* PHP Service Bus (publish-subscribe pattern implementation).
*
* @author Maksim Masiukevich <contacts@desperado.dev>
* @license MIT
* @license https://opensource.org/licenses/MIT
*/
declare(strict_types = 0);
namespace ServiceBus\EntryPoint;
use Amp\CancelledException;
use Amp\TimeoutException;
use function Amp\delay;
use Amp\Loop;
use Amp\Promise;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use ServiceBus\Transport\Common\Package\IncomingPackage;
use ServiceBus\Transport\Common\Queue;
use ServiceBus\Transport\Common\Transport;
use function ServiceBus\Common\throwableDetails;
use function ServiceBus\Common\throwableMessage;
/**
* Application entry point.
* It is the entry point for messages coming from a transport. Responsible for processing.
*/
final class EntryPoint
{
/**
* The default value for the maximum number of tasks processed simultaneously.
* The value should not be too large and should not exceed the maximum number of available connections to the
* database.
*/
private const DEFAULT_MAX_CONCURRENT_TASK_COUNT = 60;
/** Throttling value (in milliseconds) while achieving the maximum number of simultaneously executed tasks. */
private const DEFAULT_AWAIT_DELAY = 20;
/**
* Current transport from which messages will be received.
*
* @var Transport
*/
private $transport;
/**
* Handling incoming package processor.
* Responsible for deserialization, routing and task execution.
*
* @var EntryPointProcessor
*/
private $processor;
/**
* @var LoggerInterface
*/
private $logger;
/**
* The max number of concurrent tasks.
*
* @var int
*/
private $maxConcurrentTaskCount;
/**
* Collection of identifier of tasks that are being processed
*
* @psalm-var array<string, string>
*
* @var array
*/
private $currentTasksInProgress = [];
/**
* Throttling value (in milliseconds) while achieving the maximum number of simultaneously executed tasks.
*
* @var int
*/
private $awaitDelay;
public function __construct(
Transport $transport,
EntryPointProcessor $processor,
?LoggerInterface $logger = null,
?int $maxConcurrentTaskCount = null,
?int $awaitDelay = null
) {
$this->transport = $transport;
$this->processor = $processor;
$this->logger = $logger ?? new NullLogger();
$this->maxConcurrentTaskCount = $maxConcurrentTaskCount ?? self::DEFAULT_MAX_CONCURRENT_TASK_COUNT;
$this->awaitDelay = $awaitDelay ?? self::DEFAULT_AWAIT_DELAY;
}
/**
* Start queues listen.
*
* @throws \ServiceBus\Transport\Common\Exceptions\ConnectionFail Connection refused
*/
public function listen(Queue ...$queues): Promise
{
return $this->transport->consume(
function (IncomingPackage $package): \Generator
{
/** Handle incoming package */
$this->deferExecution($package);
/** Limit the maximum number of concurrently running tasks */
await:
$inProgressCount = \count($this->currentTasksInProgress);
if (($inProgressCount !== 0) && $inProgressCount >= $this->maxConcurrentTaskCount)
{
$this->logger->debug(
'The maximum number of tasks has been reached',
[
'currentCount' => $inProgressCount,
'currentCollection' => \array_values($this->currentTasksInProgress)
]
);
yield delay($this->awaitDelay);
goto await;
}
},
...$queues
);
}
/**
* Unsubscribe all queues.
* Terminates the subscription and stops the daemon.
*/
public function stop(): void
{
Loop::defer(
function (): \Generator
{
$this->logger->info('Subscriber stop command received');
yield $this->transport->stop();
await:
$inProgressCount = \count($this->currentTasksInProgress);
if ($inProgressCount !== 0)
{
$this->logger->info(
'Waiting for the completion of all tasks taken',
[
'currentCount' => $inProgressCount,
'currentCollection' => \array_keys($this->currentTasksInProgress)
]
);
yield delay(1000);
goto await;
}
$this->logger->info('The event loop has been stopped');
Loop::stop();
}
);
}
private function deferExecution(IncomingPackage $package): void
{
$this->currentTasksInProgress[$package->id()] = $package->id();
Loop::defer(
function () use ($package): void
{
$this->processor->handle($package)->onResolve(
function (?\Throwable $throwable) use ($package): \Generator
{
try
{
if ($throwable !== null)
{
throw $throwable;
}
}
catch (CancelledException | TimeoutException)
{
yield $package->reject(true);
}
catch (\Throwable $throwable)
{
$this->logThrowable($throwable, $package);
}
finally
{
unset($this->currentTasksInProgress[$package->id()]);
}
}
);
}
);
}
private function logThrowable(\Throwable $throwable, IncomingPackage $package): void
{
$this->logger->critical(
throwableMessage($throwable),
\array_merge(
throwableDetails($throwable),
[
'packageId' => $package->id(),
'headers' => $package->headers(),
]
)
);
}
}