Final fix on the msg worker

This commit is contained in:
Pinga 2025-02-06 17:38:43 +02:00
parent 6651e3d613
commit e143b1ad39

View file

@ -3,14 +3,11 @@
* msg_worker.php
*
* A worker script that continuously pulls messages from a Redis queue and processes them.
* Uses Swoole's coroutine runtime and Coroutine Redis client.
*/
// Enable strict types if desired
declare(strict_types=1);
use Swoole\Coroutine;
use Swoole\Coroutine\Redis;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as PHPMailerException;
use Utopia\Messaging\Messages\Email;
@ -39,7 +36,7 @@ $maxRetries = 3;
$retryQueueKey = 'message_queue_retry';
/**
* Creates and returns a new Coroutine Redis connection.
* Creates and returns a new Redis connection.
*
* @return Redis
* @throws Exception if connection fails.
@ -53,8 +50,7 @@ function connectRedis(): Redis {
return $redis;
}
// Run the worker inside Swoole's coroutine runtime.
Swoole\Coroutine\run(function() use ($c, $logger, $maxRetries, $retryQueueKey) {
// Run the worker
$redis = connectRedis();
$logger->info("Worker started, waiting for messages...");
@ -66,7 +62,7 @@ Swoole\Coroutine\run(function() use ($c, $logger, $maxRetries, $retryQueueKey) {
} catch (Exception $e) {
$logger->error("Redis error", ['error' => $e->getMessage()]);
// Wait before trying to reconnect
Coroutine::sleep(5);
sleep(5);
try {
$redis = connectRedis();
} catch (Exception $ex) {
@ -94,7 +90,7 @@ Swoole\Coroutine\run(function() use ($c, $logger, $maxRetries, $retryQueueKey) {
if ($c['mailer'] === 'phpmailer') {
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = 0;
$mail->SMTPDebug = 1;
$mail->isSMTP();
$mail->Host = $c['mailer_smtp_host'];
$mail->SMTPAuth = true;
@ -111,14 +107,7 @@ Swoole\Coroutine\run(function() use ($c, $logger, $maxRetries, $retryQueueKey) {
$mail->isHTML(true);
$mail->AltBody = strip_tags($data['body']);
}
Swoole\Coroutine::create(function() use ($mail) {
try {
$mail->send();
} catch (Exception $e) {
echo "Mail Error: " . $e->getMessage();
}
});
} catch (PHPMailerException $e) {
$logger->error("PHPMailer error: ", ['error' => $e->getMessage()]);
}
@ -214,4 +203,3 @@ Swoole\Coroutine\run(function() use ($c, $logger, $maxRetries, $retryQueueKey) {
}
}
}
});