96 lines
2.3 KiB
PHP
96 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace Kiri\Server\Task;
|
|
|
|
|
|
use Kiri;
|
|
use Kiri\Router\Base\ExceptionHandlerDispatcher;
|
|
use Kiri\Router\DataGrip;
|
|
use Kiri\Router\Interface\ExceptionHandlerInterface;
|
|
use Kiri\Server\Constant;
|
|
use Psr\Container\ContainerExceptionInterface;
|
|
use Psr\Container\ContainerInterface;
|
|
use Psr\Container\NotFoundExceptionInterface;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Swoole\Server;
|
|
|
|
/**
|
|
*
|
|
*/
|
|
class Task
|
|
{
|
|
|
|
|
|
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);
|
|
}
|
|
|
|
|
|
/**
|
|
* @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
|
|
* @throws
|
|
*/
|
|
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
|
|
* @throws
|
|
*/
|
|
public function onTask(Server $server, int $task_id, int $src_worker_id, mixed $data): mixed
|
|
{
|
|
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());
|
|
}
|
|
}
|
|
|
|
|
|
}
|