This commit is contained in:
2021-08-24 18:24:46 +08:00
parent 575f4b8520
commit 24c93edf2b
110 changed files with 5 additions and 6 deletions
+125
View File
@@ -0,0 +1,125 @@
<?php
namespace Server\Abstracts;
use JetBrains\PhpStorm\Pure;
use Kiri\Kiri;
use Swoole\Coroutine;
use Swoole\Process;
/**
*
*/
abstract class CustomProcess implements \Server\SInterface\CustomProcess
{
/** @var bool */
protected bool $enableSwooleCoroutine = true;
protected bool $isStop = false;
/**
*
*/
public function onProcessStop(): void
{
$this->isStop = true;
}
/**
* @return bool
*/
public function checkProcessIsStop(): bool
{
return $this->isStop === true;
}
/**
* @param Process $process
*/
public function signListen(Process $process): void
{
// if (Coroutine::getCid() === -1) {
// Process::signal(SIGTERM | SIGKILL, function ($signo) use ($process) {
// if ($signo) {
// $lists = Kiri::app()->getProcess();
// foreach ($lists as $process) {
// $process->exit(0);
// }
// }
// });
// } else {
// Coroutine::create(function () use ($process) {
// /** @var Coroutine\Socket $message */
// $message = $process->exportSocket();
// if ($message->recv() == 0x03455343213212) {
// $this->waiteExit($process);
// }
// });
// Coroutine::create(function () use ($process) {
// $data = Coroutine::waitSignal(SIGTERM | SIGKILL, -1);
// if ($data) {
// $lists = Kiri::app()->getProcess();
// foreach ($lists as $name => $process) {
// foreach ($process as $item) {
// /** @var Coroutine\Socket $export */
// $export = $item->exportSocket();
// $export->send(0x03455343213212);
// }
// }
// }
// });
// }
}
/**
*
*/
protected function exit(): void
{
putenv('process.status=idle');
}
/**
* @return bool
*/
#[Pure] public function isWorking(): bool
{
return env('process.status', 'working') == 'working';
}
/**
*
*/
private function waiteExit(Process $process): void
{
$this->onProcessStop();
while ($this->isWorking()) {
$this->sleep();
}
$process->exit(0);
}
/**
*
*/
private function sleep(): void
{
if ($this->enableSwooleCoroutine) {
Coroutine::sleep(0.1);
} else {
usleep(100);
}
}
}
@@ -0,0 +1,16 @@
<?php
namespace Server\Abstracts;
use Annotation\Inject;
use Kiri\Events\EventDispatch;
trait EventDispatchHelper
{
/** @var EventDispatch */
#[Inject(EventDispatch::class)]
public EventDispatch $eventDispatch;
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace Server\Abstracts;
use Annotation\Inject;
use Http\Route\Router;
use Kiri\Abstracts\Config;
use Kiri\Exception\ConfigException;
use Kiri\Exception\NotFindClassException;
use Kiri\Kiri;
use ReflectionException;
use Server\Constrict\ResponseEmitter;
use Server\Constrict\TcpEmitter;
use Server\ExceptionHandlerDispatcher;
use Server\ExceptionHandlerInterface;
use Server\SInterface\OnRequest;
/**
*
*/
abstract class Http extends Server implements OnRequest
{
use EventDispatchHelper;
use ResponseHelper;
/** @var Router|mixed */
#[Inject('router')]
public Router $router;
/**
* @var ExceptionHandlerInterface
*/
public ExceptionHandlerInterface $exceptionHandler;
/**
* @throws ReflectionException
* @throws ConfigException
* @throws NotFindClassException
*/
public function init()
{
$exceptionHandler = Config::get('exception.http', ExceptionHandlerDispatcher::class);
if (!in_array(ExceptionHandlerInterface::class, class_implements($exceptionHandler))) {
$exceptionHandler = ExceptionHandlerDispatcher::class;
}
$this->exceptionHandler = Kiri::getDi()->get($exceptionHandler);
$this->responseEmitter = Kiri::getDi()->get(ResponseEmitter::class);
}
}
@@ -0,0 +1,21 @@
<?php
namespace Server\Abstracts;
/**
*
*/
class PageNotFoundException extends \Exception
{
/**
*
*/
public function __construct(int $code)
{
parent::__construct('<h2>HTTP 404 Not Found</h2><hr><i>Powered by Swoole</i>', $code);
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace Server\Abstracts;
use Annotation\Inject;
use Server\Constrict\Emitter;
use Server\Constrict\Response as CResponse;
use Server\Constrict\ResponseEmitter;
/**
*
*/
trait ResponseHelper
{
/** @var CResponse|mixed */
#[Inject(CResponse::class)]
public CResponse $response;
public Emitter $responseEmitter;
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace Server\Abstracts;
use Exception;
use Kiri\Abstracts\Config;
use Kiri\Exception\ConfigException;
use Kiri\Kiri;
/**
* Class Server
* @package Server\Abstracts
*/
abstract class Server
{
/**
* @param $prefix
* @throws ConfigException
*/
protected function setProcessName($prefix)
{
if (Kiri::getPlatform()->isMac()) {
return;
}
$name = Config::get('id', 'system-service');
if (!empty($prefix)) {
$name .= '.' . $prefix;
}
swoole_set_process_name($name);
}
/**
* Server constructor.
* @throws Exception
*/
public function __construct()
{
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace Server\Abstracts;
use Kiri\Abstracts\Config;
use Kiri\Exception\ConfigException;
use Kiri\Exception\NotFindClassException;
use Kiri\Kiri;
use ReflectionException;
use Server\Constrict\TcpEmitter;
use Server\Constrict\UdpEmitter;
use Server\ExceptionHandlerDispatcher;
use Server\ExceptionHandlerInterface;
use Server\SInterface\OnReceive;
abstract class Tcp extends Server implements OnReceive
{
use EventDispatchHelper;
use ResponseHelper;
/**
* @var ExceptionHandlerInterface
*/
public ExceptionHandlerInterface $exceptionHandler;
/**
* @throws ReflectionException
* @throws ConfigException
* @throws NotFindClassException
*/
public function init()
{
$exceptionHandler = Config::get('exception.tcp', ExceptionHandlerDispatcher::class);
if (!in_array(ExceptionHandlerInterface::class, class_implements($exceptionHandler))) {
$exceptionHandler = ExceptionHandlerDispatcher::class;
}
$this->exceptionHandler = Kiri::getDi()->get($exceptionHandler);
$this->responseEmitter = Kiri::getDi()->get(TcpEmitter::class);
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace Server\Abstracts;
use Kiri\Abstracts\Config;
use Kiri\Exception\ConfigException;
use Kiri\Exception\NotFindClassException;
use Kiri\Kiri;
use ReflectionException;
use Server\Constrict\UdpEmitter;
use Server\ExceptionHandlerDispatcher;
use Server\ExceptionHandlerInterface;
use Server\SInterface\OnPacket;
use Server\SInterface\OnReceive;
/**
*
*/
abstract class Udp extends Server implements OnPacket
{
use EventDispatchHelper;
use ResponseHelper;
/**
* @var ExceptionHandlerInterface
*/
public ExceptionHandlerInterface $exceptionHandler;
/**
* @throws ReflectionException
* @throws ConfigException
* @throws NotFindClassException
*/
public function init()
{
$exceptionHandler = Config::get('exception.udp', ExceptionHandlerDispatcher::class);
if (!in_array(ExceptionHandlerInterface::class, class_implements($exceptionHandler))) {
$exceptionHandler = ExceptionHandlerDispatcher::class;
}
$this->exceptionHandler = Kiri::getDi()->get($exceptionHandler);
$this->responseEmitter = Kiri::getDi()->get(UdpEmitter::class);
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
namespace Server\Abstracts;
use Exception;
use Kiri\Abstracts\Config;
use Kiri\Exception\ConfigException;
use Kiri\Exception\NotFindClassException;
use Kiri\Kiri;
use ReflectionException;
use Server\Constrict\ResponseEmitter;
use Server\Constrict\WebSocketEmitter;
use Server\ExceptionHandlerDispatcher;
use Server\ExceptionHandlerInterface;
use Server\SInterface\OnClose;
use Server\SInterface\OnHandshake;
use Server\SInterface\OnMessage;
use Swoole\Http\Request;
use Swoole\Http\Response;
/**
*
*/
abstract class Websocket extends Server implements OnHandshake, OnMessage, OnClose
{
use EventDispatchHelper;
use ResponseHelper;
/**
* @var ExceptionHandlerInterface
*/
public ExceptionHandlerInterface $exceptionHandler;
/**
* @throws ReflectionException
* @throws ConfigException
* @throws NotFindClassException
*/
public function init()
{
$exceptionHandler = Config::get('exception.websocket', ExceptionHandlerDispatcher::class);
if (!in_array(ExceptionHandlerInterface::class, class_implements($exceptionHandler))) {
$exceptionHandler = ExceptionHandlerDispatcher::class;
}
$this->exceptionHandler = Kiri::getDi()->get($exceptionHandler);
$this->responseEmitter = Kiri::getDi()->get(WebSocketEmitter::class);
}
/**
* @param Request $request
* @param Response $response
* @throws Exception
*/
public function onHandshake(Request $request, Response $response): void
{
// TODO: Implement OnHandshake() method.
$secWebSocketKey = $request->header['sec-websocket-key'];
$patten = '#^[+/0-9A-Za-z]{21}[AQgw]==$#';
if (0 === preg_match($patten, $secWebSocketKey) || 16 !== strlen(base64_decode($secWebSocketKey))) {
throw new Exception('protocol error.', 500);
}
$key = base64_encode(sha1($request->header['sec-websocket-key'] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', TRUE));
$headers = [
'Upgrade' => 'websocket',
'Connection' => 'Upgrade',
'Sec-websocket-Accept' => $key,
'Sec-websocket-Version' => '13',
];
if (isset($request->header['sec-websocket-protocol'])) {
$explode = explode(',',$request->header['sec-websocket-protocol']);
$headers['Sec-websocket-Protocol'] = $explode[0];
}
foreach ($headers as $key => $val) {
$response->setHeader($key, $val);
}
}
}
+95
View File
@@ -0,0 +1,95 @@
<?php
namespace Server;
use JetBrains\PhpStorm\Pure;
use Swoole\Coroutine\Channel;
class ApplicationStore
{
private static ?ApplicationStore $applicationStore = null;
private Channel $lock;
/**
* ApplicationStore constructor.
*/
private function __construct()
{
$this->lock = new Channel(1);
}
/**
* @return ApplicationStore|null
*/
public static function getStore(): ?ApplicationStore
{
if (!(static::$applicationStore instanceof ApplicationStore)) {
static::$applicationStore = new ApplicationStore();
}
return static::$applicationStore;
}
/**
* @return $this
*/
public function instance(): static
{
return $this;
}
/**
*
*/
public function waite(): void
{
if ($this->lock->errCode == SWOOLE_CHANNEL_CLOSED) {
return;
}
$this->lock->pop(-1);
}
public function close()
{
$this->lock->push(1);
$this->lock->close();
}
/**
*
*/
public function done(): void
{
$this->lock->pop();
}
/**
* @return bool
*/
public function isBusy(): bool
{
return !$this->lock->isEmpty();
}
/**
* @return string
*/
#[Pure] public function getStatus(): string
{
return env('state');
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace Server;
/**
* Class Constant
* @package Server
*/
class Constant
{
const START = 'Start';
const SHUTDOWN = 'Shutdown';
const WORKER_START = 'WorkerStart';
const WORKER_STOP = 'WorkerStop';
const WORKER_EXIT = 'WorkerExit';
const CONNECT = 'Connect';
const HANDSHAKE = 'handshake';
const DISCONNECT = 'disconnect';
const MESSAGE = 'message';
const RECEIVE = 'Receive';
const PACKET = 'Packet';
const REQUEST = 'request';
const CLOSE = 'Close';
const TASK = 'Task';
const FINISH = 'Finish';
const PIPE_MESSAGE = 'PipeMessage';
const WORKER_ERROR = 'WorkerError';
const MANAGER_START = 'ManagerStart';
const MANAGER_STOP = 'ManagerStop';
const BEFORE_RELOAD = 'BeforeReload';
const AFTER_RELOAD = 'AfterReload';
const SERVER_TYPE_HTTP = 'http';
const SERVER_TYPE_WEBSOCKET = 'ws';
const SERVER_TYPE_TCP = 'tcp';
const SERVER_TYPE_UDP = 'udp';
const SERVER_TYPE_BASE = 'base';
}
+81
View File
@@ -0,0 +1,81 @@
<?php
namespace Server\Constrict;
use Kiri\Exception\NotFindClassException;
use ReflectionException;
use Server\ResponseInterface;
/**
*
*/
class DownloadEmitter implements Emitter
{
const IMAGES = [
'png' => 'image/png',
'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'svg' => 'image/svg+xml',
];
/**
* @param mixed $response
* @param ResponseInterface $emitter
* @throws NotFindClassException
* @throws ReflectionException
*/
public function sender(mixed $response, ResponseInterface $emitter): void
{
$content = $emitter->getContent()->getData();
$explode = explode('/', $content['path']);
$response->header('Pragma', 'public');
$response->header('Expires', '0');
$response->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
$response->header('Content-Disposition', 'attachment;filename=' . end($explode));
$response->header('Content-Type', $type = get_file_extension($content['path']));
if (!in_array($type, self::IMAGES)) {
$response->header('Content-Transfer-Encoding', 'binary');
} else {
$response->end(file_get_contents($content['path']));
return;
}
if ($content['isChunk'] === false) {
$response->sendfile($content['path']);
} else {
$this->chunk($content, $response);
}
}
/**
* @param $content
* @param $response
*/
private function chunk($content, $response): void
{
$resource = fopen($content['path'], 'r');
$state = fstat($resource);
$offset = $content['offset'];
$response->header('Content-length', $state['size']);
while ($file = fread($resource, $content['limit'])) {
$response->write($file);
fseek($resource, $offset);
if ($offset >= $state['size']) {
break;
}
$offset += $content['limit'];
}
$response->end();
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Server\Constrict;
use Server\ResponseInterface;
interface Emitter
{
/**
* @param mixed $response
* @param ResponseInterface $emitter
* @return mixed
*/
public function sender(mixed $response, ResponseInterface $emitter): void;
}
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace Server\Constrict;
use Http\Context\Context;
use Http\Context\Request as HttpResponse;
use Http\Context\Response;
use ReflectionException;
use Server\RequestInterface;
use Kiri\Exception\NotFindClassException;
use Kiri\Kiri;
/**
* @mixin HttpResponse
*/
class Request implements RequestInterface
{
/**
* @param $name
* @param $args
* @return mixed
*/
public function __call($name, $args)
{
if (!Context::hasContext(HttpResponse::class)) {
$request = Context::setContext(HttpResponse::class, new HttpResponse());
} else {
$request = Context::getContext(HttpResponse::class);
}
if (property_exists($request, $name)) {
return $request->{$name};
}
return $request->{$name}(...$args);
}
/**
* @param $name
* @return mixed
*/
public function __get($name): mixed
{
// TODO: Change the autogenerated stub
return Context::getContext(HttpResponse::class)->{$name};
}
/**
* @param \Swoole\Http\Request $request
* @return Request
* @throws ReflectionException
* @throws NotFindClassException
*/
public static function create(\Swoole\Http\Request $request): RequestInterface
{
Context::setContext(Response::class, new Response());
$sRequest = new HttpResponse();
$sRequest->setHeaders(array_merge($request->header, $request->server));
$sRequest->setUri($sRequest->getRequestUri());
$sRequest->setClientId($request->fd);
$sRequest->setRawContent($request->rawContent(), $sRequest->getContentType());
$sRequest->setFiles($request->files ?? []);
$sRequest->setPosts($request->post ?? []);
$sRequest->setGets($request->get ?? []);
Context::setContext(HttpResponse::class, $sRequest);
return Kiri::getDi()->get(Request::class);
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace Server\Constrict;
use Http\Context\Context;
use Http\Context\Response as HttpResponse;
use Server\ResponseInterface;
/**
* Class Response
* @package Server
* @mixin HttpResponse
*/
class Response implements ResponseInterface
{
const JSON = 'json';
const XML = 'xml';
const HTML = 'html';
const FILE = 'file';
/**
* @param $name
* @param $args
* @return mixed
*/
public function __call($name, $args)
{
if (!Context::hasContext(HttpResponse::class)) {
$context = Context::setContext(HttpResponse::class, new HttpResponse());
} else {
$context = Context::getContext(HttpResponse::class);
}
return $context->{$name}(...$args);
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace Server\Constrict;
use Exception;
use Http\Context\Formatter\FileFormatter;
use Kiri\Exception\NotFindClassException;
use ReflectionException;
use Server\ResponseInterface;
use Swoole\Server;
/**
*
*/
class ResponseEmitter implements Emitter
{
/**
* @param \Swoole\Http\Response|\Swoole\Http2\Response $response
* @param ResponseInterface $emitter
* @throws NotFindClassException
* @throws ReflectionException
* @throws Exception
*/
public function sender(mixed $response, ResponseInterface $emitter): void
{
$content = $emitter->configure($response)->getContent();
if ($content instanceof FileFormatter) {
di(DownloadEmitter::class)->sender($response, $emitter);
return;
}
$response->header('Content-Type', $emitter->getResponseFormat());
$response->end($content->getData());
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace Server\Constrict;
use Http\Context\Formatter\FileFormatter;
use Kiri\Exception\NotFindClassException;
use Server\ResponseInterface;
use Swoole\Server;
/**
*
*/
class TcpEmitter implements Emitter
{
/**
* @param Server $response
* @param ResponseInterface $emitter
* @throws NotFindClassException
* @throws \ReflectionException
* @throws \Exception
*/
public function sender(mixed $response, ResponseInterface $emitter): void
{
$formatter = $emitter->getContent();
if ($formatter instanceof FileFormatter) {
$response->sendfile($emitter->getClientId(), $formatter->getData());
} else {
$response->send($emitter->getClientId(), $formatter->getData());
}
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace Server\Constrict;
use Kiri\Exception\NotFindClassException;
use Server\ResponseInterface;
use Swoole\Server;
/**
*
*/
class UdpEmitter implements Emitter
{
/**
* @param Server $response
* @param ResponseInterface $emitter
* @throws NotFindClassException
* @throws \ReflectionException
* @throws \Exception
*/
public function sender(mixed $response, ResponseInterface $emitter): void
{
$clientInfo = $emitter->getClientInfo();
$response->sendto($clientInfo['host'], $clientInfo['port'],
$emitter->getContent()->getData()
);
}
}
@@ -0,0 +1,27 @@
<?php
namespace Server\Constrict;
use Kiri\Exception\NotFindClassException;
use Server\ResponseInterface;
/**
*
*/
class WebSocketEmitter implements Emitter
{
/**
* @param mixed $response
* @param ResponseInterface $emitter
* @throws NotFindClassException
* @throws \ReflectionException
* @throws \Exception
*/
public function sender(mixed $response, ResponseInterface $emitter): void
{
$response->push($emitter->getClientId(), $emitter->getContent()->getData());
}
}
@@ -0,0 +1,16 @@
<?php
namespace Server\Events;
class OnAfterCommandExecute
{
/**
* @param mixed $data
*/
public function __construct(public mixed $data)
{
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Server\Events;
use Swoole\Server;
class OnAfterReload
{
/**
* @param Server $server
*/
public function __construct(Server $server)
{
}
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace Server\Events;
class OnAfterRequest
{
}
@@ -0,0 +1,8 @@
<?php
namespace Server\Events;
class OnAfterWorkerStart
{
}
@@ -0,0 +1,8 @@
<?php
namespace Server\Events;
class OnBeforeCommandExecute
{
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Server\Events;
use Swoole\Server;
class OnBeforeReload
{
/**
* @param Server $server
*/
public function __construct(Server $server)
{
}
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace Server\Events;
class OnBeforeRequest
{
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace Server\Events;
use Swoole\Server;
class OnManagerStart
{
/**
* @param Server $server
*/
public function __construct(Server $server)
{
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Server\Events;
use Swoole\Server;
class OnManagerStop
{
/**
* @param Server $server
*/
public function __construct(Server $server)
{
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Server\Events;
use Swoole\Server;
class OnShutdown
{
/**
* @param Server|null $server
*/
public function __construct(?Server $server = null)
{
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Server\Events;
use Swoole\Server;
class OnStart
{
/**
* @param Server $server
*/
public function __construct(Server $server)
{
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace Server\Events;
use Swoole\Server;
/**
*
*/
class OnWorkerError
{
/**
* @param Server $server
* @param int $worker_id
* @param int $worker_pid
* @param int $exit_code
* @param int $signal
*/
public function __construct(Server $server, int $worker_id, int $worker_pid, int $exit_code, int $signal)
{
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace Server\Events;
use Swoole\Server;
/**
*
*/
class OnWorkerExit
{
/**
* @param Server $server
* @param int $workerId
*/
public function __construct(Server $server, int $workerId)
{
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace Server\Events;
use Swoole\Server;
/**
*
*/
class OnWorkerStart
{
/**
* @param Server $server
* @param int $workerId
*/
public function __construct(Server $server, int $workerId)
{
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace Server\Events;
use Swoole\Server;
/**
*
*/
class OnWorkerStop
{
/**
* @param Server $server
* @param int $workerId
*/
public function __construct(Server $server, int $workerId)
{
}
}
@@ -0,0 +1,35 @@
<?php
namespace Server;
use Server\Constrict\Response;
use Server\Constrict\Response as CResponse;
use Throwable;
/**
*
*/
class ExceptionHandlerDispatcher implements ExceptionHandlerInterface
{
/**
* @param Throwable $exception
* @param CResponse $response
* @return ResponseInterface
*/
public function emit(Throwable $exception, Response $response): ResponseInterface
{
if ($exception->getCode() == 404) {
return $response->setContent($exception->getMessage())
->setFormat(CResponse::HTML)
->setStatusCode(404);
}
$code = $exception->getCode() == 0 ? 500 : $exception->getCode();
return $response->setContent(jTraceEx($exception, null, true))
->setFormat(CResponse::HTML)
->setStatusCode($code);
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace Server;
use Server\Constrict\Response;
use Throwable;
/**
*
*/
interface ExceptionHandlerInterface
{
/**
* @param Throwable $exception
* @param Response $response
* @return ResponseInterface
*/
public function emit(Throwable $exception, Response $response): ResponseInterface;
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace Server\Manager;
use Annotation\Inject;
use Server\Abstracts\Server;
use Exception;
use Server\Events\OnAfterRequest;
use Server\SInterface\PipeMessage;
use Kiri\Events\EventDispatch;
/**
*
*/
class OnPipeMessage extends Server
{
/** @var EventDispatch */
#[Inject(EventDispatch::class)]
public EventDispatch $eventDispatch;
/**
* @param \Swoole\Server $server
* @param int $src_worker_id
* @param mixed $message
* @throws Exception
*/
public function onPipeMessage(\Swoole\Server $server, int $src_worker_id, mixed $message)
{
if (!is_object($message) || !($message instanceof PipeMessage)) {
return;
}
call_user_func([$message, 'process'], $server, $src_worker_id);
$this->eventDispatch->dispatch(new OnAfterRequest());
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace Server\Manager;
use Annotation\Inject;
use Server\Abstracts\Server;
use Server\Events\OnShutdown;
use Server\Events\OnStart;
use Kiri\Events\EventDispatch;
use Kiri\Exception\ConfigException;
/**
* Class OnServerDefault
* @package Server\Manager
*/
class OnServer extends Server
{
/**
* @var EventDispatch
*/
#[Inject(EventDispatch::class)]
public EventDispatch $eventDispatch;
/**
* @param \Swoole\Server $server
* @throws ConfigException
*/
public function onStart(\Swoole\Server $server)
{
$this->setProcessName(sprintf('start[%d].server', $server->master_pid));
$this->eventDispatch->dispatch(new OnStart($server));
}
/**
* @param \Swoole\Server $server
*/
public function onShutdown(\Swoole\Server $server)
{
$this->eventDispatch->dispatch(new OnShutdown($server));
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace Server\Manager;
use Annotation\Inject;
use Kiri\Events\EventDispatch;
use Server\Abstracts\Server;
use Kiri\Exception\ConfigException;
use Server\Events\OnManagerStart;
use Server\Events\OnManagerStop;
/**
* Class OnServerManager
* @package Server\Manager
*/
class OnServerManager extends Server
{
/**
* @var EventDispatch
*/
#[Inject(EventDispatch::class)]
public EventDispatch $eventDispatch;
/**
* @param \Swoole\Server $server
* @throws ConfigException
*/
public function onManagerStart(\Swoole\Server $server)
{
$this->setProcessName(sprintf('manger[%d].0', $server->manager_pid));
$this->eventDispatch->dispatch(new OnManagerStart($server));
}
/**
* @param \Swoole\Server $server
*/
public function onManagerStop(\Swoole\Server $server)
{
$this->eventDispatch->dispatch(new OnManagerStop($server));
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace Server\Manager;
use Annotation\Inject;
use Kiri\Events\EventDispatch;
use Server\Events\OnAfterReload;
use Server\Events\OnBeforeReload;
use Swoole\Server;
/**
*
*/
class OnServerReload
{
/**
* @var EventDispatch
*/
#[Inject(EventDispatch::class)]
public EventDispatch $eventDispatch;
/**
* @param Server $server
*/
public function onBeforeReload(Server $server)
{
$this->eventDispatch->dispatch(new OnBeforeReload($server));
}
/**
* @param Server $server
*/
public function onAfterReload(Server $server)
{
$this->eventDispatch->dispatch(new OnAfterReload($server));
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace Server\Protocol;
abstract class Protocol
{
/**
* @param $data
* @return array
*/
public function resolveProtocol($data): array
{
$explode = explode("\r\n\r\n", $data);
$http_protocol = [];
foreach (explode("\r\n", $explode[0]) as $key => $datum) {
if (empty($datum) || $key == 0) {
continue;
}
[$key, $value] = explode(': ', $datum);
$http_protocol[trim($key)] = trim($value);
}
return [$http_protocol, $explode[1]];
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
namespace Server\Protocol;
class WebSocket extends Protocol
{
//
public function decode($received): ?string
{
$decoded = null;
$buffer = $received;
$len = ord($buffer[1]) & 127;
if ($len === 126) {
$masks = substr($buffer, 4, 4);
$data = substr($buffer, 8);
} else {
if ($len === 127) {
$masks = substr($buffer, 10, 4);
$data = substr($buffer, 14);
} else {
$masks = substr($buffer, 2, 4);
$data = substr($buffer, 6);
}
}
for ($index = 0; $index < strlen($data); $index++) {
$decoded .= $data[$index] ^ $masks[$index % 4];
}
return $decoded;
}
const BINARY_TYPE_BLOB = "\x81";
public function encode($buffer): string
{
$len = strlen($buffer);
$first_byte = self::BINARY_TYPE_BLOB;
if ($len <= 125) {
$encode_buffer = $first_byte . chr($len) . $buffer;
} else {
if ($len <= 65535) {
$encode_buffer = $first_byte . chr(126) . pack("n", $len) . $buffer;
} else {
//pack("xxxN", $len)pack函数只处理2的32次方大小的文件,实际上2的32次方已经4G了。
$encode_buffer = $first_byte . chr(127) . pack("xxxxN", $len) . $buffer;
}
}
return $encode_buffer;
}
/**
* @param $data
* @return string
*/
private function getWebSocketProtocol($data): string
{
[$http_protocol, $body] = $this->resolveProtocol($data);
$key = base64_encode(sha1($http_protocol['Sec-WebSocket-Key'] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', TRUE));
$headers = [
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
'Sec-WebSocket-Accept: ' . $key,
'Sec-WebSocket-Version: 13',
];
if (isset($http_protocol['Sec-WebSocket-Protocol'])) {
$headers[] = 'Sec-WebSocket-Protocol: ' . $http_protocol['Sec-WebSocket-Protocol'];
}
return implode("\r\n", $headers) . "\r\n\r\n";
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
namespace Server;
use Http\Context\Request;
/**
*
* @mixin Request
*/
interface RequestInterface
{
}
+14
View File
@@ -0,0 +1,14 @@
<?php
namespace Server;
use Http\Context\Response;
/**
* @mixin Response
*/
interface ResponseInterface
{
}
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace Server\SInterface;
use Swoole\Process;
/**
* Interface CustomProcess
* @package SInterface
*/
interface CustomProcess
{
/**
* @param Process $process
* @return string
*/
public function getProcessName(Process $process): string;
/**
* @param Process $process
*/
public function signListen(Process $process): void;
/**
* @param Process $process
*/
public function onHandler(Process $process): void;
/**
*
*/
public function onProcessStop(): void;
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace Server\SInterface;
use Swoole\Server;
/**
*
*/
interface OnClose
{
/**
* @param Server $server
* @param int $fd
*/
public function onClose(Server $server, int $fd): void;
/**
* @param Server $server
* @param int $fd
*/
public function onDisconnect(Server $server, int $fd): void;
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Server\SInterface;
use Swoole\Server;
interface OnConnect
{
/**
* @param Server $server
* @param int $fd
* @return void
*/
public function onConnect(Server $server, int $fd): void;
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace Server\SInterface;
use Swoole\Http\Request;
use Swoole\Http\Response;
/**
*
*/
interface OnHandshake
{
/**
* @param Request $request
* @param Response $response
*/
public function onHandshake(Request $request, Response $response): void;
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace Server\SInterface;
use Swoole\Server;
use Swoole\WebSocket\Frame;
interface OnMessage
{
/**
* @param Server $server
* @param Frame $frame
* @return void
*/
public function onMessage(Server $server, Frame $frame): void;
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace Server\SInterface;
use Server\Abstracts\Server;
interface OnPacket
{
/**
* @param Server $server
* @param string $data
* @param array $clientInfo
* @return mixed
*/
public function onPacket(Server $server, string $data, array $clientInfo): void;
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace Server\SInterface;
use Swoole\Server;
/**
*
*/
interface OnReceive
{
/**
* @param Server $server
* @param int $fd
* @param int $reactor_id
* @param string $data
* @return void
*/
public function onReceive(Server $server, int $fd, int $reactor_id, string $data): void;
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Server\SInterface;
use Swoole\Http\Request;
use Swoole\Http\Response;
interface OnRequest
{
/**
* @param Request $request
* @param Response $response
*/
public function onRequest(Request $request, Response $response): void;
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace Server\SInterface;
/**
* Interface PipeMessage
* @package Server\SInterface
*/
interface PipeMessage
{
/**
*
*/
public function process(): void;
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace Server\SInterface;
use Swoole\Server;
interface TaskExecute
{
public function execute();
public function finish(Server $server, int $task_id);
}
+472
View File
@@ -0,0 +1,472 @@
<?php
namespace Server;
use Closure;
use Exception;
use Kiri\Abstracts\Config;
use Kiri\Exception\ConfigException;
use Kiri\Exception\NotFindClassException;
use Kiri\Kiri;
use ReflectionException;
use Server\Manager\OnPipeMessage;
use Server\SInterface\CustomProcess;
use Server\SInterface\TaskExecute;
use Server\Task\OnServerTask;
use Swoole\Http\Server as HServer;
use Swoole\Process;
use Swoole\Server;
use Swoole\Server\Port;
use Swoole\WebSocket\Server as WServer;
/**
* Class OnServerManager
* @package Http\Service
*/
class ServerManager
{
/** @var string */
public string $host = '';
public int $port = 0;
/** @var array<string,Port> */
public array $ports = [];
public int $mode = SWOOLE_TCP;
private mixed $server = null;
/**
* @return Server|WServer|HServer|null
*/
public function getServer(): Server|WServer|HServer|null
{
return $this->server;
}
/**
* @param string $type
* @param string $host
* @param int $port
* @param int $mode
* @param array $settings
* @throws ReflectionException
* @throws ConfigException
* @throws Exception
*/
public function addListener(string $type, string $host, int $port, int $mode, array $settings = [])
{
if ($this->checkPortIsAlready($port)) $this->stopServer($port);
if (!$this->server) {
$this->createBaseServer($type, $host, $port, $mode, $settings);
} else {
if (!isset($settings['settings'])) {
$settings['settings'] = [];
}
$this->addNewListener($type, $host, $port, $mode, $settings);
}
}
/**
* @throws NotFindClassException
* @throws ReflectionException
* @throws ConfigException
*/
public function initBaseServer($configs, int $daemon = 0): void
{
$context = di(ServerManager::class);
foreach ($this->sortService($configs['ports']) as $config) {
$this->startListenerHandler($context, $config, $daemon);
}
$this->bindCallback($this->server, [Constant::PIPE_MESSAGE => [OnPipeMessage::class, 'onPipeMessage']]);
$this->bindCallback($this->server, $this->getSystemEvents($configs));
}
/**
* @return bool
* @throws ConfigException
* @throws Exception
*/
public function isRunner(): bool
{
$configs = Config::get('server', [], true);
foreach ($this->sortService($configs['ports']) as $config) {
if ($this->checkPortIsAlready($config['port'])) {
return true;
}
}
return false;
}
/**
* @param string|CustomProcess $customProcess
* @param null $redirect_stdin_and_stdout
* @param int|null $pipe_type
* @param bool $enable_coroutine
* @throws Exception
*/
public function addProcess(string|CustomProcess $customProcess, $redirect_stdin_and_stdout = null, ?int $pipe_type = SOCK_DGRAM, bool $enable_coroutine = true)
{
$process = $this->initProcess($customProcess, $redirect_stdin_and_stdout, $pipe_type, $enable_coroutine);
$this->server->addProcess($process);
if ($customProcess instanceof CustomProcess) {
Kiri::app()->addProcess($customProcess::class, $process);
} else {
Kiri::app()->addProcess($customProcess, $process);
}
}
/**
* @param $customProcess
* @param $redirect_stdin_and_stdout
* @param $pipe_type
* @param $enable_coroutine
* @return Process
*/
private function initProcess($customProcess, $redirect_stdin_and_stdout, $pipe_type, $enable_coroutine): Process
{
$server = $this->server;
return new Process(function (Process $soloProcess) use ($customProcess, $server) {
if (is_string($customProcess)) {
$customProcess = Kiri::createObject($customProcess, [$server]);
}
$name = $customProcess->getProcessName($soloProcess);
info(sprintf("Process %s start.", $name));
scan_directory(directory('app'), 'App');
$system = sprintf('%s.process[%d]', Config::get('id', 'system-service'), $soloProcess->pid);
if (Kiri::getPlatform()->isLinux()) {
$soloProcess->name($system . '.' . $name . ' start.');
}
$customProcess->signListen($soloProcess);
$customProcess->onHandler($soloProcess);
},
$redirect_stdin_and_stdout,
$pipe_type,
$enable_coroutine
);
}
/**
* @param array $ports
* @return array
*/
public function sortService(array $ports): array
{
$array = [];
foreach ($ports as $port) {
if ($port['type'] == Constant::SERVER_TYPE_WEBSOCKET) {
array_unshift($array, $port);
} else if ($port['type'] == Constant::SERVER_TYPE_HTTP) {
if (!empty($array) && $array[0]['type'] == Constant::SERVER_TYPE_WEBSOCKET) {
$array[] = $port;
} else {
array_unshift($array, $port);
}
} else {
$array[] = $port;
}
}
return $array;
}
/**
* @param array $configs
* @return array
*/
private function getSystemEvents(array $configs): array
{
return array_intersect_key($configs['events'] ?? [], [
Constant::SHUTDOWN => '',
Constant::WORKER_START => '',
Constant::WORKER_ERROR => '',
Constant::WORKER_EXIT => '',
Constant::WORKER_STOP => '',
Constant::MANAGER_START => '',
Constant::MANAGER_STOP => '',
Constant::BEFORE_RELOAD => '',
Constant::AFTER_RELOAD => '',
Constant::START => '',
]);
}
/**
* @param ServerManager $context
* @param array $config
* @param int $daemon
* @throws ConfigException
* @throws ReflectionException
* @throws Exception
*/
private function startListenerHandler(ServerManager $context, array $config, int $daemon = 0)
{
if (!$this->server) {
$config = $this->mergeConfig($config, $daemon);
}
$context->addListener(
$config['type'], $config['host'], $config['port'], $config['mode'],
$config);
}
/**
* @param $config
* @param $daemon
* @return array
* @throws Exception
*/
private function mergeConfig($config, $daemon): array
{
$config['settings'] = $config['settings'] ?? [];
if (!isset($config['settings']['daemonize']) || !$config['settings']['daemonize'] != $daemon) {
$config['settings']['daemonize'] = $daemon;
}
if (!isset($config['settings']['log_file'])) {
$config['settings']['log_file'] = storage('system.log');
}
$config['settings']['pid_file'] = storage('.swoole.pid');
$config['events'] = $config['events'] ?? [];
return $config;
}
/**
* @param string $type
* @param string $host
* @param int $port
* @param int $mode
* @param array $settings
* @throws ReflectionException
* @throws Exception
*/
private function addNewListener(string $type, string $host, int $port, int $mode, array $settings = [])
{
echo sprintf("\033[36m[" . date('Y-m-d H:i:s') . "]\033[0m $type service %s::%d start.", $host, $port) . PHP_EOL;
/** @var Server\Port $service */
$this->ports[$port] = $this->server->addlistener($host, $port, $mode);
if ($this->ports[$port] === false) {
throw new Exception("The port is already in use[$host::$port]");
}
$this->ports[$port]->set($settings['settings'] ?? []);
$this->addServiceEvents($settings['events'] ?? [], $this->ports[$port]);
}
/**
* @param int $port
* @param string $event
* @return Closure|array|null
*/
public function getPortCallback(int $port, string $event): Closure|array|null
{
/** @var Server\Port $_port */
$_port = $this->ports[$port] ?? null;
if (is_null($_port)) {
return null;
}
return $_port->getCallback($event);
}
/**
* @param string $type
* @param string $host
* @param int $port
* @param int $mode
* @param array $settings
* @throws ReflectionException
* @throws ConfigException
*/
private function createBaseServer(string $type, string $host, int $port, int $mode, array $settings = [])
{
$match = match ($type) {
Constant::SERVER_TYPE_BASE, Constant::SERVER_TYPE_TCP,
Constant::SERVER_TYPE_UDP => Server::class,
Constant::SERVER_TYPE_HTTP => HServer::class,
Constant::SERVER_TYPE_WEBSOCKET => WServer::class
};
$this->server = new $match($host, $port, SWOOLE_PROCESS, $mode);
$this->server->set(array_merge(Config::get('server.settings', []), $settings['settings']));
echo sprintf("\033[36m[" . date('Y-m-d H:i:s') . "]\033[0m $type service %s::%d start.", $host, $port) . PHP_EOL;
$this->addDefaultListener($type, $settings);
}
/**
* @param int $port
* @throws Exception
*/
public function stopServer(int $port)
{
if (!($pid = $this->checkPortIsAlready($port))) {
return;
}
while ($this->checkPortIsAlready($port)) {
Process::kill($pid, SIGTERM);
usleep(300);
}
}
/**
* @param $port
* @return bool|string
* @throws Exception
*/
private function checkPortIsAlready($port): bool|string
{
if (!Kiri::getPlatform()->isLinux()) {
exec("lsof -i :" . $port . " | grep -i 'LISTEN' | awk '{print $2}'", $output);
if (empty($output)) return false;
$output = explode(PHP_EOL, $output[0]);
return $output[0];
}
$serverPid = file_get_contents(storage('.swoole.pid'));
if (!empty($serverPid) && shell_exec('ps -ef | grep ' . $serverPid . ' | grep -v grep')) {
Process::kill($serverPid, SIGTERM);
}
exec('netstat -lnp | grep ' . $port . ' | grep "LISTEN" | awk \'{print $7}\'', $output);
if (empty($output)) {
return false;
}
return explode('/', $output[0])[0];
}
/**
* @param string $type
* @param array $settings
* @throws ReflectionException
* @throws Exception
*/
private function addDefaultListener(string $type, array $settings): void
{
if (($this->server->setting['task_worker_num'] ?? 0) > 0) {
$this->addTaskListener($settings['events']);
}
$this->addServiceEvents($settings['events'] ?? [], $this->server);
Kiri::getDi()->setBindings(SwooleServerInterface::class,
$this->server);
}
/**
* @param array $events
* @param Server|Port $server
* @throws ReflectionException
*/
private function addServiceEvents(array $events, Server|Port $server)
{
foreach ($events as $name => $event) {
if (is_array($event) && is_string($event[0])) {
$event[0] = Kiri::getDi()->get($event[0], [$server]);
}
$server->on($name, $event);
}
}
/**
*
*/
public function start()
{
$this->server->start();
}
/**
* @param string $class
* @return object
* @throws NotFindClassException
* @throws ReflectionException
*/
private function getNewInstance(string $class): object
{
return Kiri::getDi()->newObject($class);
}
/**
* @param TaskExecute|string $handler
* @param array $params
* @param int|null $workerId
* @throws ReflectionException
* @throws Exception
*/
public function task(TaskExecute|string $handler, array $params = [], int $workerId = null)
{
if ($workerId === null || $workerId <= $this->server->setting['worker_num']) {
$workerId = random_int($this->server->setting['worker_num'] + 1,
$this->server->setting['worker_num'] + 1 + $this->server->setting['task_worker_num']);
}
if (is_string($handler)) {
$implements = Kiri::getDi()->getReflect($handler);
if (!in_array(TaskExecute::class, $implements->getInterfaceNames())) {
throw new Exception('Task must instance ' . TaskExecute::class);
}
$handler = $implements->newInstanceArgs($params);
}
$this->server->task(serialize($handler), $workerId);
}
/**
* @param array $events
* @throws ReflectionException
*/
private function addTaskListener(array $events = []): void
{
$task_use_object = $this->server->setting['task_object'] ?? $this->server->setting['task_use_object'] ?? false;
$reflect = Kiri::getDi()->getReflect(OnServerTask::class)?->newInstance();
if ($task_use_object || $this->server->setting['task_enable_coroutine']) {
$this->server->on('task', $events[Constant::TASK] ?? [$reflect, 'onCoroutineTask']);
} else {
$this->server->on('task', $events[Constant::TASK] ?? [$reflect, 'onTask']);
}
$this->server->on('finish', $events[Constant::FINISH] ?? [$reflect, 'onFinish']);
}
/**
* @param Port|Server $server
* @param array|null $settings
* @throws ReflectionException
*/
public function bindCallback(Port|Server $server, ?array $settings = [])
{
// TODO: Implement bindCallback() method.
if (count($settings) < 1) {
return;
}
foreach ($settings as $event_type => $callback) {
if ($this->server->getCallback($event_type) !== null) {
continue;
}
if (is_array($callback) && !is_object($callback[0])) {
$callback[0] = Kiri::getDi()->get($callback[0]);
}
$this->server->on($event_type, $callback);
}
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace Server\Service;
use Exception;
use Http\Exception\RequestException;
use Http\Route\Node;
use Server\Events\OnAfterRequest;
use Server\ResponseInterface;
use Server\SInterface\OnClose;
use Server\SInterface\OnConnect;
use Swoole\Error;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Server;
/**
*
*/
class Http extends \Server\Abstracts\Http implements OnClose, OnConnect
{
/**
* @param Server $server
* @param int $fd
*/
public function onConnect(Server $server, int $fd): void
{
// TODO: Implement onConnect() method.
}
/**
* @param Request $request
* @param Response $response
*/
public function onRequest(Request $request, Response $response): void
{
// TODO: Implement onRequest() method.
try {
$node = $this->router->Branch_search(\Server\Constrict\Request::create($request));
if (!($node instanceof Node)) {
throw new RequestException('<h2>HTTP 404 Not Found</h2><hr><i>Powered by Swoole</i>', 404);
}
if (!(($responseData = $node->dispatch()) instanceof ResponseInterface)) {
$responseData = $this->response->setContent($responseData)->setStatusCode(200);
}
} catch (Error | \Throwable $exception) {
$responseData = $this->exceptionHandler->emit($exception, $this->response);
} finally {
$this->responseEmitter->sender($response, $responseData);
$this->eventDispatch->dispatch(new OnAfterRequest());
}
}
/**
* @param Server $server
* @param int $fd
* @throws Exception
*/
public function onDisconnect(Server $server, int $fd): void
{
}
/**
* @param Server $server
* @param int $fd
* @throws Exception
*/
public function onClose(Server $server, int $fd): void
{
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace Server\Service;
use Server\SInterface\OnClose;
use Server\SInterface\OnConnect;
use Swoole\Server;
/**
*
*/
class Tcp extends \Server\Abstracts\Tcp implements OnConnect, OnClose
{
/**
* @param Server $server
* @param int $fd
*/
public function onConnect(Server $server, int $fd): void
{
// TODO: Implement onConnect() method.
}
/**
* @param Server $server
* @param int $fd
* @param int $reactor_id
* @param string $data
*/
public function onReceive(Server $server, int $fd, int $reactor_id, string $data): void
{
// TODO: Implement onReceive() method.
}
/**
* @param Server $server
* @param int $fd
*/
public function onClose(Server $server, int $fd): void
{
// TODO: Implement onClose() method.
}
/**
* @param Server $server
* @param int $fd
*/
public function onDisconnect(Server $server, int $fd): void
{
// TODO: Implement onDisconnect() method.
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace Server\Service;
use Server\Abstracts\Server;
/**
*
*/
class Udp extends \Server\Abstracts\Udp
{
/**
* @param Server $server
* @param string $data
* @param array $clientInfo
*/
public function onPacket(Server $server, string $data, array $clientInfo): void
{
// TODO: Implement onPacket() method.
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace Server\Service;
use Exception;
use Server\SInterface\OnRequest;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Server;
use Swoole\WebSocket\Frame;
/**
*
*/
class WebSocket extends \Server\Abstracts\Websocket
{
/**
* @param Request $request
* @param Response $response
* @throws Exception
*/
public function onHandshake(Request $request, Response $response): void
{
parent::onHandshake($request, $response); // TODO: Change the autogenerated stub
$response->status(101);
$response->end();
}
/**
* @param Server $server
* @param Frame $frame
*/
public function onMessage(Server $server, Frame $frame): void
{
// TODO: Implement OnMessage() method.
}
/**
* @param Server $server
* @param int $fd
*/
public function onClose(Server $server, int $fd): void
{
// TODO: Implement OnClose() method.
}
/**
* @param Server $server
* @param int $fd
*/
public function onDisconnect(Server $server, int $fd): void
{
// TODO: Implement OnDisconnect() method.
}
}
+14
View File
@@ -0,0 +1,14 @@
<?php
namespace Server;
use Swoole\Server;
/**
* @mixin Server
*/
interface SwooleServerInterface
{
}
+89
View File
@@ -0,0 +1,89 @@
<?php
namespace Server\Task;
use ReflectionException;
use Server\SInterface\TaskExecute;
use Kiri\Exception\NotFindClassException;
use Kiri\Kiri;
use Swoole\Server;
/**
* Class OnServerTask
* @package Server\Task
*/
class OnServerTask
{
/**
* @param Server $server
* @param int $task_id
* @param int $src_worker_id
* @param mixed $data
*/
public function onTask(Server $server, int $task_id, int $src_worker_id, mixed $data)
{
try {
$data = $this->resolve($data);
} catch (\Throwable $exception) {
$data = [$exception->getMessage()];
} finally {
$server->finish($data);
}
}
/**
* @param Server $server
* @param Server\Task $task
*/
public function onCoroutineTask(Server $server, Server\Task $task)
{
try {
$data = $this->resolve($task->data);
} catch (\Throwable $exception) {
$data = [$exception->getMessage()];
} finally {
$server->finish($data);
}
}
/**
* @param $data
* @return null
* @throws ReflectionException
*/
private function resolve($data)
{
[$class, $params] = json_encode($data, true);
$reflect = Kiri::getDi()->getReflect($class);
if (!$reflect->isInstantiable()) {
return null;
}
$class = $reflect->newInstanceArgs($params);
return $class->execute();
}
/**
* @param Server $server
* @param int $task_id
* @param mixed $data
*/
public function onFinish(Server $server, int $task_id, mixed $data)
{
if (!($data instanceof TaskExecute)) {
return;
}
$data->finish($server, $task_id);
}
}
+198
View File
@@ -0,0 +1,198 @@
<?php
namespace Server\Worker;
use Annotation\Annotation;
use Annotation\Inject;
use Exception;
use Kiri\Abstracts\Config;
use Kiri\Core\Help;
use Kiri\Events\EventDispatch;
use Kiri\Exception\ConfigException;
use Kiri\Kiri;
use Kiri\Runtime;
use ReflectionException;
use Server\Events\OnAfterWorkerStart;
use Server\Events\OnWorkerError;
use Server\Events\OnWorkerExit;
use Server\Events\OnWorkerStart;
use Server\Events\OnWorkerStop;
use Swoole\Server;
use Swoole\Timer;
/**
* Class OnServerWorker
* @package Server\Worker
*/
class OnServerWorker extends \Server\Abstracts\Server
{
/**
* @var EventDispatch
*/
#[Inject(EventDispatch::class)]
public EventDispatch $eventDispatch;
/**
* @param Server $server
* @param int $workerId
* @throws Exception
*/
public function onWorkerStart(Server $server, int $workerId)
{
$this->eventDispatch->dispatch(new OnWorkerStart($server, $workerId));
$this->onWorkerStartInit($server, $workerId);
$this->eventDispatch->dispatch(new OnAfterWorkerStart());
}
/**
* @param Server $server
* @param int $workerId
* @throws ConfigException
* @throws ReflectionException
* @throws Exception
*/
private function onWorkerStartInit(Server $server, int $workerId)
{
putenv('state=start');
putenv('worker=' . $workerId);
$serialize = file_get_contents(storage(Runtime::CONFIG_NAME));
if (!empty($serialize)) {
Config::sets(unserialize($serialize));
}
$annotation = Kiri::app()->getAnnotation();
$annotation->read(APP_PATH . 'app', 'App',
$workerId < $server->setting['worker_num'] ? [] : [CONTROLLER_PATH]
);
$this->workerInitExecutor($server, $annotation, $workerId);
$this->interpretDirectory($annotation);
}
/**
* @param Annotation $annotation
* @throws ReflectionException
* @throws Exception
*/
private function interpretDirectory(Annotation $annotation)
{
$fileLists = $annotation->runtime(APP_PATH . 'app');
$di = Kiri::getDi();
foreach ($fileLists as $class) {
foreach ($di->getTargetNote($class) as $value) {
$value->execute($class);
}
$methods = $di->getMethodAttribute($class);
foreach ($methods as $method => $attribute) {
if (empty($attribute)) {
continue;
}
foreach ($attribute as $item) {
$item->execute($class, $method);
}
}
}
}
/**
* @param Server $server
* @param Annotation $annotation
* @param int $workerId
* @throws ConfigException
* @throws Exception
*/
private function workerInitExecutor(Server $server, Annotation $annotation, int $workerId)
{
if ($workerId < $server->setting['worker_num']) {
$loader = Kiri::app()->getRouter();
$loader->_loader();
putenv('environmental=' . Kiri::WORKER);
echo sprintf("\033[36m[" . date('Y-m-d H:i:s') . "]\033[0m Worker[%d].%d start.", $server->worker_pid, $workerId) . PHP_EOL;
$this->setProcessName(sprintf('Worker[%d].%d', $server->worker_pid, $workerId));
} else {
putenv('environmental=' . Kiri::TASK);
echo sprintf("\033[36m[" . date('Y-m-d H:i:s') . "]\033[0m Tasker[%d].%d start.", $server->worker_pid, $workerId) . PHP_EOL;
$this->setProcessName(sprintf('Tasker[%d].%d', $server->worker_pid, $workerId));
}
}
/**
* @param Server $server
* @param int $workerId
* @throws Exception
*/
public function onWorkerStop(Server $server, int $workerId)
{
$this->eventDispatch->dispatch(new OnWorkerStop($server, $workerId));
Timer::clearAll();
}
/**
* @param Server $server
* @param int $workerId
* @throws Exception
*/
public function onWorkerExit(Server $server, int $workerId)
{
putenv('state=exit');
$this->eventDispatch->dispatch(new OnWorkerExit($server, $workerId));
Kiri::getApp('logger')->insert();
}
/**
* @param Server $server
* @param int $worker_id
* @param int $worker_pid
* @param int $exit_code
* @param int $signal
* @throws Exception
*/
public function onWorkerError(Server $server, int $worker_id, int $worker_pid, int $exit_code, int $signal)
{
$this->eventDispatch->dispatch(new OnWorkerError($server, $worker_id, $worker_pid, $exit_code, $signal));
$message = sprintf('Worker#%d::%d error stop. signal %d, exit_code %d, msg %s',
$worker_id, $worker_pid, $signal, $exit_code, swoole_strerror(swoole_last_error(), 9)
);
write($message, 'worker-exit');
$this->system_mail($message);
}
/**
* @param $messageContent
* @throws Exception
*/
protected function system_mail($messageContent)
{
try {
$email = Config::get('email');
if (!empty($email) && ($email['enable'] ?? false) == true) {
Help::sendEmail($email, 'Service Error', $messageContent);
}
} catch (\Throwable $e) {
error($e, 'email');
}
}
}