@@ -53,6 +53,11 @@ class Server
5353 */
5454 protected Hook $ workerStartHook ;
5555
56+ /**
57+ * Hook that is called when worker stops
58+ */
59+ protected Hook $ workerStopHook ;
60+
5661 /**
5762 * @var array
5863 */
@@ -96,7 +101,7 @@ public function getResource(string $name, bool $fresh = false): mixed
96101 {
97102 if (!\array_key_exists ($ name , $ this ->resources ) || $ fresh || self ::$ resourcesCallbacks [$ name ]['reset ' ]) {
98103 if (!\array_key_exists ($ name , self ::$ resourcesCallbacks )) {
99- throw new Exception (' Failed to find resource: " ' . $ name . ' " ' );
104+ throw new Exception (" Failed to find resource: $ name" );
100105 }
101106
102107 $ this ->resources [$ name ] = \call_user_func_array (
@@ -213,49 +218,23 @@ public function start(): self
213218 $ this ->adapter ->workerStart (function (string $ workerId ) {
214219 Console::success ("[Worker] Worker {$ workerId } is ready! " );
215220 self ::setResource ('workerId ' , fn () => $ workerId );
216- if (! is_null ( $ this ->workerStartHook ) ) {
221+ if ($ this ->workerStartHook !== null ) {
217222 call_user_func_array ($ this ->workerStartHook ->getAction (), $ this ->getArguments ($ this ->workerStartHook ));
218223 }
219224
220- while (true ) {
221- $ this ->adapter ->consumer ->consume (
222- $ this ->adapter ->queue ,
223- function (Message $ message ) {
224- $ receivedAtTimestamp = microtime (true );
225- Console::info ("[Job] Received Job ( {$ message ->getPid ()}). " );
226- try {
227- $ waitDuration = microtime (true ) - $ message ->getTimestamp ();
228- $ this ->jobWaitTime ->record ($ waitDuration );
229-
230- $ this ->resources = [];
231- self ::setResource ('message ' , fn () => $ message );
232- if ($ this ->job ->getHook ()) {
233- foreach ($ this ->initHooks as $ hook ) { // Global init hooks
234- if (in_array ('* ' , $ hook ->getGroups ())) {
235- $ arguments = $ this ->getArguments ($ hook , $ message ->getPayload ());
236- \call_user_func_array ($ hook ->getAction (), $ arguments );
237- }
238- }
239- }
240-
241- foreach ($ this ->job ->getGroups () as $ group ) {
242- foreach ($ this ->initHooks as $ hook ) { // Group init hooks
243- if (in_array ($ group , $ hook ->getGroups ())) {
244- $ arguments = $ this ->getArguments ($ hook , $ message ->getPayload ());
245- \call_user_func_array ($ hook ->getAction (), $ arguments );
246- }
247- }
248- }
249-
250- return \call_user_func_array ($ this ->job ->getAction (), $ this ->getArguments ($ this ->job , $ message ->getPayload ()));
251- } finally {
252- $ processDuration = microtime (true ) - $ receivedAtTimestamp ;
253- $ this ->processDuration ->record ($ processDuration );
254- }
255- },
256- function (Message $ message ) {
225+ $ this ->adapter ->consumer ->consume (
226+ $ this ->adapter ->queue ,
227+ function (Message $ message ) {
228+ $ receivedAtTimestamp = microtime (true );
229+ Console::info ("[Job] Received Job ( {$ message ->getPid ()}). " );
230+ try {
231+ $ waitDuration = microtime (true ) - $ message ->getTimestamp ();
232+ $ this ->jobWaitTime ->record ($ waitDuration );
233+
234+ $ this ->resources = [];
235+ self ::setResource ('message ' , fn () => $ message );
257236 if ($ this ->job ->getHook ()) {
258- foreach ($ this ->shutdownHooks as $ hook ) { // Global init hooks
237+ foreach ($ this ->initHooks as $ hook ) { // Global init hooks
259238 if (in_array ('* ' , $ hook ->getGroups ())) {
260239 $ arguments = $ this ->getArguments ($ hook , $ message ->getPayload ());
261240 \call_user_func_array ($ hook ->getAction (), $ arguments );
@@ -264,27 +243,65 @@ function (Message $message) {
264243 }
265244
266245 foreach ($ this ->job ->getGroups () as $ group ) {
267- foreach ($ this ->shutdownHooks as $ hook ) { // Group init hooks
246+ foreach ($ this ->initHooks as $ hook ) { // Group init hooks
268247 if (in_array ($ group , $ hook ->getGroups ())) {
269248 $ arguments = $ this ->getArguments ($ hook , $ message ->getPayload ());
270249 \call_user_func_array ($ hook ->getAction (), $ arguments );
271250 }
272251 }
273252 }
274- Console::success ("[Job] ( {$ message ->getPid ()}) successfully run. " );
275- },
276- function (?Message $ message , Throwable $ th ) {
277- Console::error ("[Job] ( {$ message ?->getPid()}) failed to run. " );
278- Console::error ("[Job] ( {$ message ?->getPid()}) {$ th ->getMessage ()}" );
279253
280- self ::setResource ('error ' , fn () => $ th );
254+ return \call_user_func_array ($ this ->job ->getAction (), $ this ->getArguments ($ this ->job , $ message ->getPayload ()));
255+ } finally {
256+ $ processDuration = microtime (true ) - $ receivedAtTimestamp ;
257+ $ this ->processDuration ->record ($ processDuration );
258+ }
259+ },
260+ function (Message $ message ) {
261+ if ($ this ->job ->getHook ()) {
262+ foreach ($ this ->shutdownHooks as $ hook ) { // Global init hooks
263+ if (in_array ('* ' , $ hook ->getGroups ())) {
264+ $ arguments = $ this ->getArguments ($ hook , $ message ->getPayload ());
265+ \call_user_func_array ($ hook ->getAction (), $ arguments );
266+ }
267+ }
268+ }
281269
282- foreach ($ this ->errorHooks as $ hook ) {
283- ($ hook ->getAction ())(...$ this ->getArguments ($ hook ));
270+ foreach ($ this ->job ->getGroups () as $ group ) {
271+ foreach ($ this ->shutdownHooks as $ hook ) { // Group init hooks
272+ if (in_array ($ group , $ hook ->getGroups ())) {
273+ $ arguments = $ this ->getArguments ($ hook , $ message ->getPayload ());
274+ \call_user_func_array ($ hook ->getAction (), $ arguments );
275+ }
284276 }
285- },
286- );
277+ }
278+ Console::success ("[Job] ( {$ message ->getPid ()}) successfully run. " );
279+ },
280+ function (?Message $ message , Throwable $ th ) {
281+ Console::error ("[Job] ( {$ message ?->getPid()}) failed to run. " );
282+ Console::error ("[Job] ( {$ message ?->getPid()}) {$ th ->getMessage ()}" );
283+
284+ self ::setResource ('error ' , fn () => $ th );
285+
286+ foreach ($ this ->errorHooks as $ hook ) {
287+ $ hook ->getAction ()(...$ this ->getArguments ($ hook ));
288+ }
289+ },
290+ );
291+ });
292+
293+ $ this ->adapter ->workerStop (function ($ workerId ) {
294+ Console::info ("[Worker] Worker {$ workerId } stopping... " );
295+ self ::setResource ('workerId ' , fn () => $ workerId );
296+
297+ // Call user-defined workerStop hook if set
298+ if ($ this ->workerStopHook !== null ) {
299+ call_user_func_array ($ this ->workerStopHook ->getAction (), $ this ->getArguments ($ this ->workerStopHook ));
287300 }
301+
302+ // Close consumer connection
303+ $ this ->adapter ->consumer ->close ();
304+ Console::success ("[Worker] Worker {$ workerId } stopped gracefully. " );
288305 });
289306
290307 $ this ->adapter ->start ();
@@ -320,27 +337,23 @@ public function getWorkerStart(): Hook
320337
321338 /**
322339 * Is called when a Worker stops.
323- * @param callable|null $callback
324- * @return self
325- * @throws Exception
340+ * @return Hook
326341 */
327- public function workerStop (? callable $ callback = null ): self
342+ public function workerStop (): Hook
328343 {
329- try {
330- $ this ->adapter ->workerStop (function (string $ workerId ) use ($ callback ) {
331- Console::success ("[Worker] Worker {$ workerId } is ready! " );
332- if (!is_null ($ callback )) {
333- call_user_func ($ callback );
334- }
335- });
336- } catch (Throwable $ error ) {
337- self ::setResource ('error ' , fn () => $ error );
338- foreach ($ this ->errorHooks as $ hook ) {
339- call_user_func_array ($ hook ->getAction (), $ this ->getArguments ($ hook ));
340- }
341- }
344+ $ hook = new Hook ();
345+ $ hook ->groups (['* ' ]);
346+ $ this ->workerStopHook = $ hook ;
347+ return $ hook ;
348+ }
342349
343- return $ this ;
350+ /**
351+ * Returns Worker stops hook.
352+ * @return ?Hook
353+ */
354+ public function getWorkerStop (): ?Hook
355+ {
356+ return $ this ->workerStopHook ;
344357 }
345358
346359 /**
@@ -355,7 +368,7 @@ protected function getArguments(Hook $hook, array $payload = []): array
355368 $ arguments = [];
356369 foreach ($ hook ->getParams () as $ key => $ param ) { // Get value from route or request object
357370 $ value = $ payload [$ key ] ?? $ param ['default ' ];
358- $ value = ($ value === '' || is_null ( $ value) ) ? $ param ['default ' ] : $ value ;
371+ $ value = ($ value === '' || $ value === null ) ? $ param ['default ' ] : $ value ;
359372
360373 $ this ->validate ($ key , $ param , $ value );
361374 $ hook ->setParamValue ($ key , $ value );
@@ -384,7 +397,7 @@ protected function getArguments(Hook $hook, array $payload = []): array
384397 */
385398 protected function validate (string $ key , array $ param , mixed $ value ): void
386399 {
387- if ('' !== $ value && ! is_null ( $ value) ) {
400+ if ('' !== $ value && $ value !== null ) {
388401 $ validator = $ param ['validator ' ]; // checking whether the class exists
389402
390403 if (\is_callable ($ validator )) {
@@ -399,7 +412,7 @@ protected function validate(string $key, array $param, mixed $value): void
399412 throw new Exception ('Invalid ' .$ key . ': ' . $ validator ->getDescription (), 400 );
400413 }
401414 } elseif (!$ param ['optional ' ]) {
402- throw new Exception (' Param " ' . $ key . ' " is not optional.' , 400 );
415+ throw new Exception (" Param $ key is not optional. " , 400 );
403416 }
404417 }
405418
0 commit comments