Files
kiri-http-server/Task/Task.php
T

96 lines
2.3 KiB
PHP
Raw Normal View History

2023-04-22 02:04:31 +08:00
<?php
namespace Kiri\Server\Task;
2023-07-31 23:08:58 +08:00
use Kiri;
2024-04-24 14:17:09 +08:00
use Kiri\Router\Base\ExceptionHandlerDispatcher;
use Kiri\Router\DataGrip;
use Kiri\Router\Interface\ExceptionHandlerInterface;
2023-04-22 02:04:31 +08:00
use Kiri\Server\Constant;
2024-04-24 14:17:09 +08:00
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
2023-04-22 02:04:31 +08:00
use Swoole\Server;
2023-07-31 23:13:57 +08:00
/**
*
*/
2023-08-17 17:04:55 +08:00
class Task
2023-04-22 02:04:31 +08:00
{
2024-04-24 14:17:09 +08:00
public ExceptionHandlerInterface $exception;
/**
* @param ContainerInterface $container
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function __construct(public ContainerInterface $container)
{
$exception = \config('exception.task');
if (!in_array(ExceptionHandlerInterface::class, class_implements($exception))) {
$exception = ExceptionHandlerDispatcher::class;
}
$this->exception = $this->container->get($exception);
}
2023-08-17 16:56:51 +08:00
/**
* @param Server $server
* @return void
*/
public function initTaskWorker(Server $server): void
{
if (!isset($server->setting[Constant::OPTION_TASK_WORKER_NUM])) {
return;
}
if ($server->setting[Constant::OPTION_TASK_WORKER_NUM] < 1) {
return;
}
$server->on('finish', [$this, 'onFinish']);
$server->on('task', [$this, 'onTask']);
}
/**
* @param Server $server
* @param int $task_id
* @param mixed $data
* @return void
2023-12-12 15:35:34 +08:00
* @throws
2023-08-17 16:56:51 +08:00
*/
public function onFinish(Server $server, int $task_id, mixed $data): void
{
event(new OnTaskFinish($task_id, $data));
}
/**
* @param Server $server
* @param int $task_id
* @param int $src_worker_id
* @param mixed $data
* @return mixed
2023-12-12 15:35:34 +08:00
* @throws
2023-08-17 16:56:51 +08:00
*/
public function onTask(Server $server, int $task_id, int $src_worker_id, mixed $data): mixed
{
2024-04-24 14:17:09 +08:00
try {
$data = json_decode($data, true);
if (is_null($data)) {
return null;
}
$data[0] = Kiri::getDi()->get($data[0]);
return call_user_func($data, $task_id, $src_worker_id);
} catch (\Throwable $throwable) {
return $this->exception->emit($throwable, response());
2023-08-17 16:56:51 +08:00
}
}
2023-04-22 02:04:31 +08:00
}