Files
kiri-http-server/Tasker/OnServerTask.php
T

95 lines
1.7 KiB
PHP
Raw Normal View History

2022-01-09 03:49:02 +08:00
<?php
2022-01-10 11:39:55 +08:00
namespace Kiri\Server\Tasker;
2022-01-09 03:49:02 +08:00
use Kiri\Annotation\Inject;
use Kiri\Abstracts\Logger;
use Kiri\Exception\ConfigException;
2022-01-10 11:39:55 +08:00
use Kiri\Server\Contract\OnTaskInterface;
2022-01-09 03:49:02 +08:00
use Swoole\Server;
/**
* Class OnServerTask
* @package Server\Task
*/
class OnServerTask
{
#[Inject(Logger::class)]
public Logger $logger;
/**
* @param Server $server
* @param int $task_id
* @param int $src_worker_id
* @param mixed $data
* @throws ConfigException
*/
public function onTask(Server $server, int $task_id, int $src_worker_id, mixed $data)
{
try {
$data = $this->resolve($data);
} catch (\Throwable $exception) {
$data = jTraceEx($exception);
2022-01-11 16:16:04 +08:00
$this->logger->error('task', [error_trigger_format($exception)]);
2022-01-09 03:49:02 +08:00
} finally {
$server->finish($data);
}
}
/**
* @param Server $server
* @param Server\Task $task
* @throws ConfigException
*/
public function onCoroutineTask(Server $server, Server\Task $task)
{
try {
$data = $this->resolve($task->data);
} catch (\Throwable $exception) {
$data = jTraceEx($exception);
2022-01-11 16:16:04 +08:00
$this->logger->error('task', [error_trigger_format($exception)]);
2022-01-09 03:49:02 +08:00
} finally {
2022-01-11 10:26:34 +08:00
$task->finish($data);
2022-01-09 03:49:02 +08:00
}
}
/**
* @param $data
* @return null
*/
private function resolve($data)
{
$execute = unserialize($data);
if ($execute instanceof OnTaskInterface) {
return $execute->execute();
}
return null;
}
/**
* @param Server $server
* @param int $task_id
* @param mixed $data
*/
public function onFinish(Server $server, int $task_id, mixed $data)
{
if (!($data instanceof OnTaskInterface)) {
return;
}
$data->finish($server, $task_id);
}
}