Skip to content

Commit

Permalink
Add WeakMap for storing coSockets (#539)
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 committed Feb 3, 2024
1 parent d48ad85 commit 18dedec
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions src/Aspect/UdpSocketAspect.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Monolog\Handler\SyslogUdp\UdpSocket;
use Socket;
use WeakMap;

/**
* @property Socket|null $socket
Expand All @@ -26,10 +27,12 @@ class UdpSocketAspect extends AbstractAspect
UdpSocket::class . '::getSocket',
];

/**
* @var Socket[]
*/
public static array $coSockets = [];
public static WeakMap $coSockets;

public function __construct()
{
self::$coSockets = new WeakMap();
}

public function process(ProceedingJoinPoint $proceedingJoinPoint)
{
Expand All @@ -38,13 +41,12 @@ public function process(ProceedingJoinPoint $proceedingJoinPoint)
}

$instance = $proceedingJoinPoint->getInstance();
$hash = spl_object_hash($instance);

if (isset(self::$coSockets[$hash]) && self::$coSockets[$hash] instanceof Socket) {
return self::$coSockets[$hash];
if (isset(self::$coSockets[$instance]) && self::$coSockets[$instance] instanceof Socket) {
return self::$coSockets[$instance];
}

return self::$coSockets[$hash] = (function () use ($proceedingJoinPoint) {
return self::$coSockets[$instance] = (function () use ($proceedingJoinPoint) {
$nonCoSocket = $this->socket; // Save the socket of non-coroutine.
$this->socket = null; // Unset the socket of non-coroutine.
$coSocket = $proceedingJoinPoint->process(); // ReCreate the socket in coroutine.
Expand Down

0 comments on commit 18dedec

Please sign in to comment.