Skip to content

Commit

Permalink
Optimized UdpSocketAspect (#535)
Browse files Browse the repository at this point in the history
Co-authored-by: Deeka Wong <8337659+huangdijia@users.noreply.github.com>
  • Loading branch information
huangdijia and huangdijia authored Feb 1, 2024
1 parent 441a795 commit 834dc69
Showing 1 changed file with 26 additions and 14 deletions.
40 changes: 26 additions & 14 deletions src/Aspect/UdpSocketAspect.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,40 +11,52 @@

namespace FriendsOfHyperf\MonologHook\Aspect;

use Hyperf\Context\Context;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Monolog\Handler\SyslogUdp\UdpSocket;
use Swoole\Coroutine\Client;

use function Hyperf\Coroutine\defer;

/**
* @property string $ip
* @property int $port
*/
class UdpSocketAspect extends AbstractAspect
{
public array $classes = [
UdpSocket::class . '::send',
UdpSocket::class . '::close',
UdpSocket::class . '::getSocket',
];

public function process(ProceedingJoinPoint $proceedingJoinPoint)
{
if (Coroutine::inCoroutine()) {
if ($proceedingJoinPoint->methodName == 'close') {
return;
}

/** @var string $chunk */
$chunk = $proceedingJoinPoint->arguments['keys']['chunk'] ?? '';
[$ip, $port] = (fn () => [$this->ip, $this->port])->call($proceedingJoinPoint->getInstance());

$socket = new Client(SWOOLE_SOCK_UDP);
$socket->connect($ip, $port, 0.5);
$key = sprintf(
'%s::%s@%s:%s',
$proceedingJoinPoint->className,
$proceedingJoinPoint->methodName,
$ip,
$port
);

return Context::getOrSet($key, function () use ($port) {
$domain = AF_INET;
$protocol = SOL_UDP;

if ($port === 0) { // Check if we are using unix sockets.
$domain = AF_UNIX;
$protocol = IPPROTO_IP;
}

defer(fn () => $socket->close());
$socket = socket_create($domain, SOCK_DGRAM, $protocol);

$socket->send($chunk);
defer(fn () => socket_close($socket));

return;
return $socket;
});
}

return $proceedingJoinPoint->process();
Expand Down

0 comments on commit 834dc69

Please sign in to comment.