Files
kiri-pool/PoolItem.php
T

148 lines
2.7 KiB
PHP
Raw Permalink Normal View History

2023-08-16 00:28:54 +08:00
<?php
declare(strict_types=1);
namespace Kiri\Pool;
use Closure;
use Swoole\Coroutine\Channel;
use Swoole\Coroutine;
class PoolItem
{
/**
* @var Channel|SplQueue
*/
private Channel|SplQueue $_items;
/**
* @var int
*/
private int $created = 0;
/**
* @param int $maxCreated
* @param Closure|array $callback
*/
public function __construct(readonly public int $maxCreated, readonly public Closure|array $callback)
{
2023-08-25 09:37:59 +08:00
$this->reconnect();
2023-08-16 00:28:54 +08:00
}
2023-08-16 00:39:55 +08:00
/**
* @return bool
*/
public function isClose(): bool
{
if ($this->_items instanceof Channel) {
return $this->_items->errCode == SWOOLE_CHANNEL_CLOSED;
}
return false;
}
/**
* @return void
*/
public function reconnect(): void
{
2023-08-25 09:37:59 +08:00
if (Coroutine::getCid() > -1) {
2023-08-16 00:39:55 +08:00
$this->_items = new Channel($this->maxCreated);
2023-08-25 09:37:59 +08:00
} else {
$this->_items = new SplQueue($this->maxCreated);
2023-08-16 00:39:55 +08:00
}
}
2023-08-16 00:28:54 +08:00
/**
* @param Channel|SplQueue $items
*/
public function setItems(Channel|SplQueue $items): void
{
$this->_items = $items;
}
/**
* @param mixed $item
* @return void
*/
public function push(mixed $item): void
{
if (is_null($item)) {
2023-08-16 16:33:57 +08:00
return;
2023-08-16 00:28:54 +08:00
}
$this->_items->push($item);
}
/**
* @return bool
*/
public function isEmpty(): bool
{
return $this->_items->isEmpty();
}
/**
* @return int
*/
public function size(): int
{
return $this->_items->length();
}
/**
* @return bool
*/
public function close(): bool
{
return $this->_items->close();
}
/**
* @param int $min
* @return void
*/
public function tailor(int $min = 0): void
{
while ($this->_items->length() > $min) {
$connection = $this->_items->pop(0.000001);
if ($connection instanceof StopHeartbeatCheck) {
$connection->stopHeartbeatCheck();
}
$connection = null;
}
}
2023-08-16 16:33:57 +08:00
/**
* @return void
*/
public function abandon(): void
{
$this->created -= 1;
}
2023-08-16 00:28:54 +08:00
/**
* @param int $waite
* @return mixed
*/
public function pop(int $waite = 10): mixed
{
2023-08-29 22:27:47 +08:00
if ($this->_items->isEmpty()) {
2023-08-16 00:28:54 +08:00
return call_user_func($this->callback);
} else {
return $this->_items->pop($waite);
}
}
}