Total Complexity | 54 |
Total Lines | 429 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Complex classes like BeanstalkClient often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use BeanstalkClient, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
36 | class BeanstalkClient extends Injectable |
||
37 | { |
||
38 | public const INBOX_PREFIX = 'INBOX_'; |
||
39 | |||
40 | public const QUEUE_ERROR = 'queue_error'; |
||
41 | |||
42 | /** @var Pheanstalk */ |
||
43 | private Pheanstalk $queue; |
||
44 | private bool $connected = false; |
||
45 | private array $subscriptions = []; |
||
46 | private string $tube; |
||
47 | private int $reconnectsCount = 0; |
||
48 | private $message; |
||
49 | private $timeout_handler; |
||
50 | private $error_handler; |
||
51 | |||
52 | private string $port; |
||
53 | |||
54 | /** |
||
55 | * BeanstalkClient constructor. |
||
56 | * |
||
57 | * @param string $tube The name of the tube. |
||
58 | * @param string $port The port number for the Beanstalkd server. |
||
59 | */ |
||
60 | public function __construct(string $tube = 'default', string $port = '') |
||
65 | } |
||
66 | |||
67 | /** |
||
68 | * Recreates connection to the Beanstalkd server. |
||
69 | */ |
||
70 | public function reconnect(): void |
||
71 | { |
||
72 | $config = $this->di->get('config')->beanstalk; |
||
73 | $tmpPort = $config->port; |
||
74 | if ( ! empty($this->port) && is_numeric($this->port)) { |
||
75 | $tmpPort = $this->port; |
||
76 | } |
||
77 | $this->queue = Pheanstalk::create($config->host, $tmpPort); |
||
78 | try { |
||
79 | $this->queue->useTube($this->tube); |
||
80 | }catch (Throwable $e){ |
||
81 | CriticalErrorsHandler::handleExceptionWithSyslog($e); |
||
82 | $this->connected = false; |
||
83 | return; |
||
84 | } |
||
85 | foreach ($this->subscriptions as $tube => $callback) { |
||
86 | $this->subscribe($tube, $callback); |
||
87 | } |
||
88 | $this->connected = true; |
||
89 | } |
||
90 | |||
91 | /** |
||
92 | * Subscribe on new message in tube |
||
93 | * |
||
94 | * @param string $tube - listening tube |
||
95 | * @param array | callable $callback - worker |
||
96 | */ |
||
97 | public function subscribe(string $tube, $callback): void |
||
103 | } |
||
104 | |||
105 | /** |
||
106 | * Returns connection status |
||
107 | * |
||
108 | * @return bool |
||
109 | */ |
||
110 | public function isConnected(): bool |
||
113 | } |
||
114 | |||
115 | /** |
||
116 | * Sends request and wait for answer from processor |
||
117 | * |
||
118 | * @deprecated Use sendRequest instead with array result: list($result, $message) = $client->sendRequest(...) |
||
119 | * |
||
120 | * @param $job_data |
||
121 | * @param int $timeout |
||
122 | * @param int $priority |
||
123 | * |
||
124 | * @return bool|string |
||
125 | */ |
||
126 | public function request($job_data, int $timeout = 10, int $priority = PheanstalkInterface::DEFAULT_PRIORITY) { |
||
127 | $this->message = false; |
||
128 | $inbox_tube = uniqid(self::INBOX_PREFIX, true); |
||
129 | $this->queue->watch($inbox_tube); |
||
130 | |||
131 | // Send message to backend worker |
||
132 | $requestMessage = [ |
||
133 | $job_data, |
||
134 | 'inbox_tube' => $inbox_tube, |
||
135 | ]; |
||
136 | $this->publish($requestMessage, null, $priority, 0, $timeout); |
||
137 | |||
138 | // We wait until a worker process request. |
||
139 | try { |
||
140 | $job = $this->queue->reserveWithTimeout($timeout); |
||
141 | if ($job !== null) { |
||
142 | $this->message = $job->getData(); |
||
143 | $this->queue->delete($job); |
||
144 | } |
||
145 | } catch (Throwable $exception) { |
||
146 | Util::sysLogMsg(__METHOD__, $exception->getMessage(), LOG_ERR); |
||
147 | if(isset($job)){ |
||
148 | $this->buryJob($job); |
||
149 | } |
||
150 | } |
||
151 | $this->queue->ignore($inbox_tube); |
||
152 | |||
153 | return $this->message; |
||
154 | } |
||
155 | |||
156 | |||
157 | /** |
||
158 | * Sends request and wait for answer from processor |
||
159 | * |
||
160 | * @param $job_data |
||
161 | * @param int $timeout |
||
162 | * @param int $priority |
||
163 | * |
||
164 | * @return array |
||
165 | */ |
||
166 | public function sendRequest($job_data, int $timeout = 10, int $priority = PheanstalkInterface::DEFAULT_PRIORITY):array |
||
167 | { |
||
168 | $result = true; |
||
169 | $inbox_tube = uniqid(self::INBOX_PREFIX, true); |
||
170 | $this->queue->watch($inbox_tube); |
||
171 | |||
172 | // Send message to backend worker |
||
173 | $requestMessage = [ |
||
174 | $job_data, |
||
175 | 'inbox_tube' => $inbox_tube, |
||
176 | ]; |
||
177 | $this->publish($requestMessage, null, $priority, 0, $timeout); |
||
178 | |||
179 | // We wait until a worker process request. |
||
180 | try { |
||
181 | $job = $this->queue->reserveWithTimeout($timeout); |
||
182 | if ($job !== null) { |
||
183 | $this->message = $job->getData(); |
||
184 | $this->queue->delete($job); |
||
185 | } else { |
||
186 | $this->message = '{"'.self::QUEUE_ERROR.'":"Worker did not answer within timeout '.$timeout.' sec"}'; |
||
187 | $result = false; |
||
188 | } |
||
189 | } catch (Throwable $e) { |
||
190 | if(isset($job)){ |
||
191 | $this->buryJob($job); |
||
192 | } |
||
193 | $prettyMessage = CriticalErrorsHandler::handleExceptionWithSyslog($e); |
||
194 | $this->message = '{"'.self::QUEUE_ERROR.'":"Exception on '.__METHOD__.' with message: '.$prettyMessage.'"}'; |
||
195 | $result = false; |
||
196 | } |
||
197 | $this->queue->ignore($inbox_tube); |
||
198 | |||
199 | return [$result, $this->message]; |
||
200 | } |
||
201 | |||
202 | /** |
||
203 | * Puts a job in a beanstalkd server queue |
||
204 | * |
||
205 | * @param mixed $job_data data to worker |
||
206 | * @param ?string $tube tube name |
||
207 | * @param int $priority Jobs with smaller priority values will be scheduled |
||
208 | * before jobs with larger priorities. The most urgent priority is 0; |
||
209 | * the least urgent priority is 4294967295. |
||
210 | * @param int $delay delay before insert job into work query |
||
211 | * @param int $ttr time to execute this job |
||
212 | * |
||
213 | * @return \Pheanstalk\Job |
||
214 | */ |
||
215 | public function publish( |
||
216 | $job_data, |
||
217 | $tube = null, |
||
218 | int $priority = PheanstalkInterface::DEFAULT_PRIORITY, |
||
219 | int $delay = PheanstalkInterface::DEFAULT_DELAY, |
||
220 | int $ttr = PheanstalkInterface::DEFAULT_TTR |
||
221 | ): Job { |
||
222 | $tube = str_replace("\\", '-', $tube); |
||
223 | // Change tube |
||
224 | if ( ! empty($tube) && $this->tube !== $tube) { |
||
225 | $this->queue->useTube($tube); |
||
226 | } |
||
227 | $job_data = serialize($job_data); |
||
228 | // Send JOB to queue |
||
229 | $result = $this->queue->put($job_data, $priority, $delay, $ttr); |
||
230 | |||
231 | // Return original tube |
||
232 | $this->queue->useTube($this->tube); |
||
233 | |||
234 | return $result; |
||
235 | } |
||
236 | |||
237 | /** |
||
238 | * Drops orphaned tasks |
||
239 | */ |
||
240 | public function cleanTubes() |
||
241 | { |
||
242 | $tubes = $this->queue->listTubes(); |
||
243 | $deletedJobInfo = []; |
||
244 | foreach ($tubes as $tube) { |
||
245 | try { |
||
246 | $this->queue->useTube($tube); |
||
247 | $queueStats = $this->queue->stats()->getArrayCopy(); |
||
248 | |||
249 | // Delete buried jobs |
||
250 | $countBuried = $queueStats['current-jobs-buried']; |
||
251 | while ($job = $this->queue->peekBuried()) { |
||
252 | $countBuried--; |
||
253 | if ($countBuried < 0) { |
||
254 | break; |
||
255 | } |
||
256 | $id = $job->getId(); |
||
257 | Util::sysLogMsg( |
||
258 | __METHOD__, |
||
259 | "Deleted buried job with ID {$id} from {$tube} with message {$job->getData()}", |
||
260 | LOG_DEBUG |
||
261 | ); |
||
262 | $this->queue->delete($job); |
||
263 | $deletedJobInfo[] = "{$id} from {$tube}"; |
||
264 | } |
||
265 | |||
266 | // Delete outdated jobs |
||
267 | $countReady = $queueStats['current-jobs-ready']; |
||
268 | while ($job = $this->queue->peekReady()) { |
||
269 | $countReady--; |
||
270 | if ($countReady < 0) { |
||
271 | break; |
||
272 | } |
||
273 | $id = $job->getId(); |
||
274 | $jobStats = $this->queue->statsJob($job)->getArrayCopy(); |
||
275 | $age = (int)$jobStats['age']; |
||
276 | $expectedTimeToExecute = (int)$jobStats['ttr'] * 2; |
||
277 | if ($age > $expectedTimeToExecute) { |
||
278 | Util::sysLogMsg( |
||
279 | __METHOD__, |
||
280 | "Deleted outdated job with ID {$id} from {$tube} with message {$job->getData()}", |
||
281 | LOG_DEBUG |
||
282 | ); |
||
283 | $this->queue->delete($job); |
||
284 | $deletedJobInfo[] = "{$id} from {$tube}"; |
||
285 | } |
||
286 | } |
||
287 | } catch (Throwable $e) { |
||
288 | CriticalErrorsHandler::handleExceptionWithSyslog($e); |
||
289 | } |
||
290 | } |
||
291 | if (count($deletedJobInfo) > 0) { |
||
292 | Util::sysLogMsg(__METHOD__, "Delete outdated jobs" . implode(PHP_EOL, $deletedJobInfo), LOG_WARNING); |
||
293 | } |
||
294 | } |
||
295 | |||
296 | /** |
||
297 | * Waits for a job from the Beanstalkd server. |
||
298 | * |
||
299 | * @param float $timeout The timeout value in seconds. |
||
300 | */ |
||
301 | public function wait(float $timeout = 5): void |
||
302 | { |
||
303 | $this->message = null; |
||
304 | $start = microtime(true); |
||
305 | try { |
||
306 | $job = $this->queue->reserveWithTimeout((int)$timeout); |
||
307 | } catch (Throwable $e) { |
||
308 | CriticalErrorsHandler::handleExceptionWithSyslog($e); |
||
309 | } |
||
310 | |||
311 | if ( ! isset($job)) { |
||
312 | $workTime = (microtime(true) - $start); |
||
313 | if ($workTime < $timeout) { |
||
314 | usleep(100000); |
||
315 | // If the work time $workTime is less than the timeout value $timeout |
||
316 | // and no job is received $job === null |
||
317 | // something is wrong, probably lost connection with the queue server |
||
318 | $this->reconnect(); |
||
319 | } |
||
320 | if (is_array($this->timeout_handler)) { |
||
321 | call_user_func($this->timeout_handler); |
||
322 | } |
||
323 | |||
324 | return; |
||
325 | } |
||
326 | |||
327 | // Processing job over callable function attached in $this->subscribe |
||
328 | if (json_decode($job->getData(), true) !== null) { |
||
329 | $mData = $job->getData(); |
||
330 | } else { |
||
331 | $mData = unserialize($job->getData(), [false]); |
||
332 | } |
||
333 | $this->message = $mData; |
||
334 | |||
335 | $stats = $this->queue->statsJob($job); |
||
336 | $requestFormTube = $stats['tube']; |
||
337 | $func = $this->subscriptions[$requestFormTube] ?? null; |
||
338 | |||
339 | if ($func === null) { |
||
340 | // Action not found |
||
341 | $this->buryJob($job); |
||
342 | } else { |
||
343 | try { |
||
344 | if (is_array($func)) { |
||
345 | call_user_func($func, $this); |
||
346 | } elseif (is_callable($func) === true) { |
||
347 | $func($this); |
||
348 | } |
||
349 | // Removes the job from the queue when it has been successfully completed |
||
350 | $this->queue->delete($job); |
||
351 | } catch (Throwable $e) { |
||
352 | // Marks the job as terminally failed and no workers will restart it. |
||
353 | $this->buryJob($job); |
||
354 | CriticalErrorsHandler::handleExceptionWithSyslog($e); |
||
355 | } |
||
356 | } |
||
357 | } |
||
358 | |||
359 | /** |
||
360 | * Buries a job in the Beanstalkd server. |
||
361 | * |
||
362 | * @param mixed $job The job to be buried. |
||
363 | */ |
||
364 | private function buryJob($job):void |
||
365 | { |
||
366 | if(!isset($job)){ |
||
367 | return; |
||
368 | } |
||
369 | try { |
||
370 | $this->queue->bury($job); |
||
371 | } catch (Throwable $e) { |
||
372 | CriticalErrorsHandler::handleExceptionWithSyslog($e); |
||
373 | } |
||
374 | } |
||
375 | |||
376 | /** |
||
377 | * Returns the body of the message. |
||
378 | * |
||
379 | * @return string The body of the message. |
||
380 | */ |
||
381 | public function getBody(): string |
||
382 | { |
||
383 | if (is_array($this->message) |
||
384 | && isset($this->message['inbox_tube']) |
||
385 | && count($this->message) === 2) { |
||
386 | // If it's a request that requires a response, the data was passed as the first element of the array. |
||
387 | $message_data = $this->message[0]; |
||
388 | } else { |
||
389 | $message_data = $this->message; |
||
390 | } |
||
391 | |||
392 | return $message_data; |
||
393 | } |
||
394 | |||
395 | /** |
||
396 | * Sends a reply message. |
||
397 | * |
||
398 | * @param mixed $response The response message. |
||
399 | * @return void |
||
400 | */ |
||
401 | public function reply($response): void |
||
402 | { |
||
403 | if (isset($this->message['inbox_tube'])) { |
||
404 | $this->queue->useTube($this->message['inbox_tube']); |
||
405 | $this->queue->put($response); |
||
406 | $this->queue->useTube($this->tube); |
||
407 | } |
||
408 | } |
||
409 | |||
410 | /** |
||
411 | * Sets the error handler for the Beanstalk client. |
||
412 | * |
||
413 | * @param mixed $handler The error handler. |
||
414 | * @return void |
||
415 | */ |
||
416 | public function setErrorHandler($handler): void |
||
417 | { |
||
418 | $this->error_handler = $handler; |
||
419 | } |
||
420 | |||
421 | /** |
||
422 | * Sets the timeout handler for the Beanstalk client. |
||
423 | * |
||
424 | * @param mixed $handler The timeout handler. |
||
425 | * @return void |
||
426 | */ |
||
427 | public function setTimeoutHandler($handler): void |
||
430 | } |
||
431 | |||
432 | /** |
||
433 | * Returns the number of times the Beanstalk client has reconnected. |
||
434 | * |
||
435 | * @return int The number of reconnects. |
||
436 | */ |
||
437 | public function reconnectsCount(): int |
||
438 | { |
||
439 | return $this->reconnectsCount; |
||
440 | } |
||
441 | |||
442 | /** |
||
443 | * Retrieves messages from a tube. |
||
444 | * |
||
445 | * @param string $tube The name of the tube. If empty, uses the default tube. |
||
446 | * @return array An array of messages retrieved from the tube. |
||
447 | */ |
||
448 | public function getMessagesFromTube(string $tube = ''): array |
||
465 | } |
||
466 | } |