This commit is contained in:
2021-03-08 16:01:07 +08:00
parent e67c0d8816
commit 7b13890bb7
5 changed files with 514 additions and 476 deletions
+14 -13
View File
@@ -4,13 +4,13 @@ declare(strict_types=1);
namespace HttpServer\Events; namespace HttpServer\Events;
use Closure;
use HttpServer\Abstracts\Callback; use HttpServer\Abstracts\Callback;
use HttpServer\Http\Request;
use Snowflake\Core\Json;
use Snowflake\Event; use Snowflake\Event;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Swoole\Server; use Swoole\Server;
use Exception; use Exception;
use HttpServer\Events\Utility\DataResolve;
/** /**
* Class OnPacket * Class OnPacket
@@ -20,12 +20,10 @@ class OnPacket extends Callback
{ {
/** @var ?Closure */ public int $port = 0;
public ?Closure $unpack = null;
/** @var ?Closure */ public string $host = '';
public ?Closure $pack = null;
/** /**
@@ -38,15 +36,18 @@ class OnPacket extends Callback
public function onHandler(Server $server, string $data, array $clientInfo): mixed public function onHandler(Server $server, string $data, array $clientInfo): mixed
{ {
try { try {
$data = DataResolve::unpack($this->unpack, $clientInfo['address'], $clientInfo['port'], $data); $request = Request::createListenRequest($clientInfo, $server, $data);
if (empty($data)) {
throw new Exception('Format error.'); [$host, $port] = [$clientInfo['address'], $clientInfo['port']];
$router = Snowflake::app()->getRouter();
if (($node = $router->find_path($request)) === null) {
return $server->sendto($host, $port, Json::encode(['state' => 404]));
} }
return $server->sendto($clientInfo['address'], $clientInfo['port'], DataResolve::pack($this->pack, $data)); return $server->sendto($host, $port, $node->dispatch());
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
$response['message'] = $exception->getMessage(); $response = Json::encode(['state' => 500, 'message' => $exception->getMessage()]);
$response['state'] = 500;
$response = DataResolve::pack($this->pack, $response);
return $server->sendto($clientInfo['address'], $clientInfo['port'], $response); return $server->sendto($clientInfo['address'], $clientInfo['port'], $response);
} finally { } finally {
fire(Event::SYSTEM_RESOURCE_RELEASES); fire(Event::SYSTEM_RESOURCE_RELEASES);
+11 -16
View File
@@ -5,12 +5,12 @@ namespace HttpServer\Events;
use HttpServer\Abstracts\Callback; use HttpServer\Abstracts\Callback;
use HttpServer\Http\Request;
use Snowflake\Core\Json;
use Snowflake\Event; use Snowflake\Event;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Swoole\Server; use Swoole\Server;
use Exception; use Exception;
use Closure;
use HttpServer\Events\Utility\DataResolve;
/** /**
* Class OnReceive * Class OnReceive
@@ -19,13 +19,10 @@ use HttpServer\Events\Utility\DataResolve;
class OnReceive extends Callback class OnReceive extends Callback
{ {
public int $port = 0;
/** @var ?Closure */
public ?Closure $unpack = null;
/** @var ?Closure */ public string $host = '';
public ?Closure $pack = null;
/** /**
@@ -39,18 +36,15 @@ class OnReceive extends Callback
public function onHandler(Server $server, int $fd, int $reID, string $data): mixed public function onHandler(Server $server, int $fd, int $reID, string $data): mixed
{ {
try { try {
$client = $server->getClientInfo($fd, $reID); $request = Request::createListenRequest($fd, $server, $data, $reID);
$data = DataResolve::unpack($this->unpack, $client['remote_ip'], $client['remote_port'], $data); $router = Snowflake::app()->getRouter();
if (empty($data)) { if (($node = $router->find_path($request)) === null) {
throw new Exception('Format error.'); return $server->send($fd, Json::encode(['state' => 404]));
} }
return $server->send($fd, DataResolve::pack($this->pack, $data)); return $server->send($fd, $node->dispatch());
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
$response['message'] = $exception->getMessage(); return $server->send($fd, Json::encode(['state' => 500, 'message' => $exception->getMessage()]));
$response['state'] = 500;
$response = DataResolve::pack($this->pack, $response);
return $server->send($fd, $response);
} finally { } finally {
$event = Snowflake::app()->getEvent(); $event = Snowflake::app()->getEvent();
$event->trigger(Event::SYSTEM_RESOURCE_RELEASES); $event->trigger(Event::SYSTEM_RESOURCE_RELEASES);
@@ -58,4 +52,5 @@ class OnReceive extends Callback
} }
} }
} }
+10
View File
@@ -72,6 +72,16 @@ class HttpParams
} }
} }
/**
* @return mixed
*/
public function getBody(): mixed
{
return $this->body;
}
/** /**
* @param string $key * @param string $key
* @param string $value * @param string $value
+477 -445
View File
@@ -15,6 +15,7 @@ use Snowflake\Core\Json;
use Snowflake\Exception\ComponentException; use Snowflake\Exception\ComponentException;
use Snowflake\Exception\NotFindClassException; use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake; use Snowflake\Snowflake;
use Swoole\Server;
use function router; use function router;
defined('REQUEST_OK') or define('REQUEST_OK', 0); defined('REQUEST_OK') or define('REQUEST_OK', 0);
@@ -38,451 +39,482 @@ defined('REQUEST_FAIL') or define('REQUEST_FAIL', 500);
class Request extends HttpService class Request extends HttpService
{ {
public int $fd = 0; public int $fd = 0;
public ?HttpParams $params; public ?HttpParams $params;
public ?HttpHeaders $headers; public ?HttpHeaders $headers;
public bool $isCli = FALSE; public bool $isCli = FALSE;
public float $startTime; public float $startTime;
public ?array $clientInfo;
public string $uri = '';
public string $uri = '';
public int $statusCode = 200;
public int $statusCode = 200;
/** @var string[] */
private array $explode = []; /** @var string[] */
private array $explode = [];
const PLATFORM_MAC_OX = 'mac';
const PLATFORM_IPHONE = 'iphone'; const PLATFORM_MAC_OX = 'mac';
const PLATFORM_ANDROID = 'android'; const PLATFORM_IPHONE = 'iphone';
const PLATFORM_WINDOWS = 'windows'; const PLATFORM_ANDROID = 'android';
const PLATFORM_WINDOWS = 'windows';
/**
* @var AuthIdentity|null /**
*/ * @var AuthIdentity|null
private ?AuthIdentity $_grant = null; */
private ?AuthIdentity $_grant = null;
/**
* @param $fd /**
*/ * @param $fd
public function setFd($fd) */
{ public function setFd($fd)
$this->fd = $fd; {
} $this->fd = $fd;
}
/**
* @return array|null /**
* @throws ComponentException * @return array|null
* @throws NotFindClassException * @throws ComponentException
* @throws ReflectionException * @throws NotFindClassException
*/ * @throws ReflectionException
public function getConnectInfo(): array|null */
{ public function getConnectInfo(): array|null
if (empty($this->fd)) { {
return null; if (empty($this->fd)) {
} return null;
$server = Snowflake::app()->getSwoole(); }
$server = Snowflake::app()->getSwoole();
return $server->getClientInfo($this->fd);
} return $server->getClientInfo($this->fd);
}
/**
* @return bool /**
*/ * @return bool
public function isFavicon(): bool */
{ public function isFavicon(): bool
return $this->getUri() === 'favicon.ico'; {
} return $this->getUri() === 'favicon.ico';
}
/**
* @return mixed /**
*/ * @return mixed
public function getIdentity(): mixed */
{ public function getIdentity(): mixed
return $this->_grant; {
} return $this->_grant;
}
/**
* @return bool /**
*/ * @return bool
public function isHead(): bool */
{ public function isHead(): bool
$result = $this->headers->getHeader('request_method') == 'head'; {
if ($result) { $result = $this->headers->getHeader('request_method') == 'head';
$this->setStatus(101); if ($result) {
} else { $this->setStatus(101);
$this->setStatus(200); } else {
} $this->setStatus(200);
return $result; }
} return $result;
}
/**
* @param $status /**
* @return mixed * @param $status
*/ * @return mixed
public function setStatus($status): mixed */
{ public function setStatus($status): mixed
return $this->statusCode = $status; {
} return $this->statusCode = $status;
}
/**
* @return int /**
*/ * @return int
public function getStatus(): int */
{ public function getStatus(): int
return $this->statusCode; {
} return $this->statusCode;
}
/**
* @return bool /**
*/ * @return bool
public function getIsPackage(): bool */
{ public function getIsPackage(): bool
return $this->headers->getHeader('request_method') == 'package'; {
} return $this->headers->getHeader('request_method') == 'package';
}
/**
* @return bool /**
*/ * @return bool
public function getIsReceive(): bool */
{ public function getIsReceive(): bool
return $this->headers->getHeader('request_method') == 'receive'; {
} return $this->headers->getHeader('request_method') == 'receive';
}
/**
* @param $value /**
*/ * @param $value
public function setGrantAuthorization($value) */
{ public function setGrantAuthorization($value)
$this->_grant = $value; {
} $this->_grant = $value;
}
/**
* @return bool /**
*/ * @return bool
public function hasGrant(): bool */
{ public function hasGrant(): bool
return $this->_grant !== null; {
} return $this->_grant !== null;
}
/**
* @return string /**
*/ * @return string
public function parseUri(): string */
{ public function parseUri(): string
$array = []; {
$explode = explode('/', $this->headers->getHeader('request_uri')); $array = [];
foreach ($explode as $item) { $explode = explode('/', $this->headers->getHeader('request_uri'));
if (empty($item)) { foreach ($explode as $item) {
continue; if (empty($item)) {
} continue;
$array[] = $item; }
} $array[] = $item;
return $this->uri = implode('/', ($this->explode = $array)); }
} return $this->uri = implode('/', ($this->explode = $array));
}
/**
* @return string[] /**
*/ * @return string[]
public function getExplode(): array */
{ public function getExplode(): array
return $this->explode; {
} return $this->explode;
}
/**
* @return string /**
*/ * @return string
#[Pure] public function getCurrent(): string */
{ #[Pure] public function getCurrent(): string
return current($this->explode); {
} return current($this->explode);
}
/**
* @return string /**
*/ * @return string
public function getUri(): string */
{ public function getUri(): string
if (!$this->headers) { {
return 'command exec.'; if (!$this->headers) {
} return 'command exec.';
if (!empty($this->uri)) { }
return $this->uri; if (!empty($this->uri)) {
} return $this->uri;
$uri = $this->headers->getHeader('request_uri'); }
$uri = ltrim($uri, '/'); $uri = $this->headers->getHeader('request_uri');
if (empty($uri)) return '/'; $uri = ltrim($uri, '/');
return $uri; if (empty($uri)) return '/';
} return $uri;
}
/**
* @return mixed /**
* @throws ComponentException * @return mixed
*/ * @throws ComponentException
public function adapter(): mixed */
{ public function adapter(): mixed
if (!$this->isHead()) { {
return router()->dispatch(); if (!$this->isHead()) {
} return router()->dispatch();
return ''; }
} return '';
}
/**
* @return string|null /**
*/ * @return string|null
public function getPlatform(): ?string */
{ public function getPlatform(): ?string
$user = $this->headers->getHeader('user-agent'); {
$match = preg_match('/\(.*\)?/', $user, $output); $user = $this->headers->getHeader('user-agent');
if (!$match || count($output) < 1) { $match = preg_match('/\(.*\)?/', $user, $output);
return null; if (!$match || count($output) < 1) {
} return null;
$output = strtolower(array_shift($output)); }
if (strpos('mac', $output)) { $output = strtolower(array_shift($output));
return 'mac'; if (strpos('mac', $output)) {
} else if (strpos('iphone', $output)) { return 'mac';
return 'iphone'; } else if (strpos('iphone', $output)) {
} else if (strpos('android', $output)) { return 'iphone';
return 'android'; } else if (strpos('android', $output)) {
} else if (strpos('windows', $output)) { return 'android';
return 'windows'; } else if (strpos('windows', $output)) {
} return 'windows';
return null; }
} return null;
}
/**
* @return bool /**
*/ * @return bool
public function isIos(): bool */
{ public function isIos(): bool
return $this->getPlatform() == static::PLATFORM_IPHONE; {
} return $this->getPlatform() == static::PLATFORM_IPHONE;
}
/**
* @return bool /**
*/ * @return bool
public function isAndroid(): bool */
{ public function isAndroid(): bool
return $this->getPlatform() == static::PLATFORM_ANDROID; {
} return $this->getPlatform() == static::PLATFORM_ANDROID;
}
/**
* @return bool /**
*/ * @return bool
public function isMacOs(): bool */
{ public function isMacOs(): bool
return $this->getPlatform() == static::PLATFORM_MAC_OX; {
} return $this->getPlatform() == static::PLATFORM_MAC_OX;
}
/**
* @return bool /**
*/ * @return bool
public function isWindows(): bool */
{ public function isWindows(): bool
return $this->getPlatform() == static::PLATFORM_WINDOWS; {
} return $this->getPlatform() == static::PLATFORM_WINDOWS;
}
/**
* @return bool /**
*/ * @return bool
public function getIsPost(): bool */
{ public function getIsPost(): bool
return $this->getMethod() == 'post'; {
} return $this->getMethod() == 'post';
}
/**
* @return bool /**
* @throws Exception * @return bool
*/ * @throws Exception
public function getIsHttp(): bool */
{ public function getIsHttp(): bool
return true; {
} return true;
}
/**
* @return bool /**
*/ * @return bool
public function getIsOption(): bool */
{ public function getIsOption(): bool
return $this->getMethod() == 'options'; {
} return $this->getMethod() == 'options';
}
/**
* @return bool /**
*/ * @return bool
public function getIsGet(): bool */
{ public function getIsGet(): bool
return $this->getMethod() == 'get'; {
} return $this->getMethod() == 'get';
}
/**
* @return bool /**
*/ * @return bool
public function getIsDelete(): bool */
{ public function getIsDelete(): bool
return $this->getMethod() == 'delete'; {
} return $this->getMethod() == 'delete';
}
/**
* @return string /**
* * @return string
* 获取请求类型 *
*/ * 获取请求类型
public function getMethod(): string */
{ public function getMethod(): string
$method = $this->headers->get('request_method'); {
if (empty($method)) { $method = $this->headers->get('request_method');
return 'get'; if (empty($method)) {
} return 'get';
return strtolower($method); }
} return strtolower($method);
}
/**
* @return bool /**
*/ * @return bool
public function getIsCli(): bool */
{ public function getIsCli(): bool
return $this->isCli === TRUE; {
} return $this->isCli === TRUE;
}
/**
* @param $name /**
* @param $value * @param $name
* * @param $value
* @throws Exception *
*/ * @throws Exception
public function __set($name, $value) */
{ public function __set($name, $value)
$method = 'set' . ucfirst($name); {
if (method_exists($this, $method)) { $method = 'set' . ucfirst($name);
$this->$method($value); if (method_exists($this, $method)) {
} else { $this->$method($value);
parent::__set($name, $value); // TODO: Change the autogenerated stub } else {
} parent::__set($name, $value); // TODO: Change the autogenerated stub
} }
}
/**
* @return mixed|null /**
*/ * @return mixed|null
public function getIp(): string|null */
{ public function getIp(): string|null
$headers = $this->headers->getHeaders(); {
if (!empty($headers['x-forwarded-for'])) return $headers['x-forwarded-for']; $headers = $this->headers->getHeaders();
if (!empty($headers['request-ip'])) return $headers['request-ip']; if (!empty($headers['x-forwarded-for'])) return $headers['x-forwarded-for'];
if (!empty($headers['remote_addr'])) return $headers['remote_addr']; if (!empty($headers['request-ip'])) return $headers['request-ip'];
return NULL; if (!empty($headers['remote_addr'])) return $headers['remote_addr'];
} return NULL;
}
/**
* @return string /**
*/ * @return string
public function getRuntime(): string */
{ public function getRuntime(): string
return sprintf('%.5f', microtime(TRUE) - $this->startTime); {
} return sprintf('%.5f', microtime(TRUE) - $this->startTime);
}
/**
* @return string /**
*/ * @return string
public function getDebug(): string */
{ public function getDebug(): string
$mainstay = sprintf("%.6f", microtime(true)); // 带毫秒的时间戳 {
$mainstay = sprintf("%.6f", microtime(true)); // 带毫秒的时间戳
$timestamp = floor($mainstay); // 时间戳
$milliseconds = round(($mainstay - $timestamp) * 1000); // 毫秒 $timestamp = floor($mainstay); // 时间戳
$milliseconds = round(($mainstay - $timestamp) * 1000); // 毫秒
$datetime = date("Y-m-d H:i:s", $timestamp) . '.' . $milliseconds;
$datetime = date("Y-m-d H:i:s", $timestamp) . '.' . $milliseconds;
$tmp = [
'[Debug ' . $datetime . '] ', $tmp = [
$this->getIp(), '[Debug ' . $datetime . '] ',
$this->getUri(), $this->getIp(),
'`' . $this->headers->getHeader('user-agent') . '`', $this->getUri(),
$this->getRuntime() '`' . $this->headers->getHeader('user-agent') . '`',
]; $this->getRuntime()
];
return implode(' ', $tmp);
} return implode(' ', $tmp);
}
/**
* @param $router /**
* @return bool * @param $router
*/ * @return bool
public function is($router): bool */
{ public function is($router): bool
return $this->getUri() == trim($router, '/'); {
} return $this->getUri() == trim($router, '/');
}
/**
* @return bool /**
*/ * @return bool
public function isNotFound(): bool */
{ public function isNotFound(): bool
return Json::to(404, 'Page ' . $this->getUri() . ' not found.'); {
} return Json::to(404, 'Page ' . $this->getUri() . ' not found.');
}
/**
* @param $request /**
* @return mixed * @param $request
* @throws ReflectionException * @return mixed
* @throws NotFindClassException * @throws ReflectionException
*/ * @throws NotFindClassException
public static function create($request): Request */
{ public static function create($request): Request
/** @var Request $sRequest */ {
$sRequest = Context::setContext('request', Snowflake::createObject(Request::class)); /** @var Request $sRequest */
$sRequest->fd = $request->fd; $sRequest = Context::setContext('request', Snowflake::createObject(Request::class));
$sRequest->startTime = microtime(true); $sRequest->fd = $request->fd;
$sRequest->startTime = microtime(true);
$sRequest->params = new HttpParams($request->rawContent(), $request->get, $request->files);
if (!empty($request->post)) { $sRequest->params = new HttpParams($request->rawContent(), $request->get, $request->files);
$sRequest->params->setPosts($request->post ?? []); if (!empty($request->post)) {
} $sRequest->params->setPosts($request->post ?? []);
$sRequest->headers = new HttpHeaders(ArrayAccess::merge($request->server, $request->header)); }
$sRequest->uri = $sRequest->headers->get('request_uri'); $sRequest->headers = new HttpHeaders(ArrayAccess::merge($request->server, $request->header));
$sRequest->uri = $sRequest->headers->get('request_uri');
$sRequest->parseUri();
return $sRequest; $sRequest->parseUri();
} return $sRequest;
}
/**
* @param $frame /**
* @param $route * @param $frame
* @param string $event * @param $route
* @return Request * @param string $event
* @throws NotFindClassException * @return Request
* @throws ReflectionException * @throws NotFindClassException
*/ * @throws ReflectionException
public static function socketQuery($frame, $event = Socket::MESSAGE, $route = 'event'): Request */
{ public static function socketQuery($frame, $event = Socket::MESSAGE, $route = 'event'): Request
/** @var Request $sRequest */ {
$sRequest = Snowflake::createObject(Request::class); /** @var Request $sRequest */
$sRequest->fd = $frame->fd; $sRequest = Snowflake::createObject(Request::class);
$sRequest->startTime = microtime(true); $sRequest->fd = $frame->fd;
$sRequest->startTime = microtime(true);
$sRequest->params = new HttpParams([], [], []);
$sRequest->headers = new HttpHeaders([]); $sRequest->params = new HttpParams([], [], []);
$sRequest->headers->replace('request_method', 'sw::socket'); $sRequest->headers = new HttpHeaders([]);
$sRequest->headers->replace('request_uri', $event . '::' . $route); $sRequest->headers->replace('request_method', 'sw::socket');
$sRequest->parseUri(); $sRequest->headers->replace('request_uri', $event . '::' . $route);
$sRequest->parseUri();
return $sRequest;
} return Context::setContext('request', $sRequest);
}
/**
* @param $fd
* @param Server $server
* @param $data
* @param int $reID
* @return Request
* @throws NotFindClassException
* @throws ReflectionException
*/
public static function createListenRequest($fd, Server $server, $data, $reID = 0): Request
{
/** @var Request $sRequest */
$sRequest = Snowflake::createObject(Request::class);
if (is_array($fd)) {
$sRequest->fd = 0;
$sRequest->clientInfo = $fd;
} else {
$sRequest->fd = $fd;
$sRequest->clientInfo = $server->getClientInfo($fd, $reID);
}
$sRequest->startTime = microtime(true);
$sRequest->params = new HttpParams(['body' => $data], [], []);
$sRequest->headers = new HttpHeaders([]);
$sRequest->headers->replace('request_method', 'listen');
$sRequest->headers->replace('request_uri', 'add-port-listen/' . $server->port);
$sRequest->parseUri();
return Context::setContext('request', $sRequest);
}
} }
+2 -2
View File
@@ -431,8 +431,8 @@ class Server extends HttpService
} else { } else {
$this->onBind($newListener, 'packet', [$class = new OnPacket(), 'onHandler']); $this->onBind($newListener, 'packet', [$class = new OnPacket(), 'onHandler']);
} }
$class->pack = $config['resolve']['pack'] ?? null; $class->host = $config['host'];
$class->unpack = $config['resolve']['unpack'] ?? null; $class->port = $config['port'];
} }