Files
kiri-router/src/Router.php
T

417 lines
11 KiB
PHP
Raw Normal View History

2023-04-15 23:29:27 +08:00
<?php
2023-04-16 01:24:30 +08:00
declare(strict_types=1);
2023-04-15 23:29:27 +08:00
namespace Kiri\Router;
2023-04-15 23:31:16 +08:00
use Closure;
2026-04-17 16:30:52 +08:00
use Kiri\Di\HotReloadState;
2024-11-18 16:11:16 +08:00
use Kiri\Server\Events\OnWorkerStart;
2023-04-15 23:31:16 +08:00
use Kiri;
2024-11-15 14:16:37 +08:00
use Kiri\Abstracts\CoordinatorManager;
use Kiri\Coordinator;
2026-04-17 16:30:52 +08:00
use Kiri\Router\RouteArtifactState;
2024-08-29 17:14:37 +08:00
use Kiri\Router\Validator\ValidatorMiddleware;
2023-06-27 16:29:09 +08:00
use Kiri\Router\Base\Middleware as MiddlewareManager;
2023-04-16 01:24:30 +08:00
use Kiri\Router\Constrict\RequestMethod;
2023-11-22 09:26:18 +08:00
use Psr\Container\ContainerInterface;
2024-12-16 16:36:35 +08:00
use Psr\Http\Message\ResponseInterface;
2023-04-15 23:31:16 +08:00
/**
*
*
* $component->set([
* 'request' => [
* 'middlewares' => []
* ]
* ])
*/
2023-04-15 23:29:27 +08:00
class Router
{
2023-10-17 20:27:26 +08:00
2024-12-16 16:36:35 +08:00
const array METHODS = [RequestMethod::REQUEST_POST, RequestMethod::REQUEST_GET, RequestMethod::REQUEST_OPTIONS, RequestMethod::REQUEST_DELETE, RequestMethod::REQUEST_PUT, RequestMethod::REQUEST_HEAD];
/**
* @var string
*/
private static string $type = ROUTER_TYPE_HTTP;
2026-04-17 16:30:52 +08:00
private static ?string $currentSourceFile = null;
2026-06-24 20:17:55 +08:00
/**
* 标记首次完整扫描是否已完成
* Master 进程中完成扫描后设为 trueWorker 通过 fork 继承此标记
* Worker 启动时检查此标记,避免重复执行全量 app 目录扫描导致 OOM
* @var bool
*/
private static bool $initialScanDone = false;
2024-12-16 16:36:35 +08:00
/**
2025-12-30 20:21:44 +08:00
* @param string $name
2024-12-16 16:36:35 +08:00
* @param Closure $closure
*/
public static function addServer(string $name, Closure $closure): void
{
static::$type = $name;
$closure();
static::$type = ROUTER_TYPE_HTTP;
}
/**
* @param Closure $handler
*/
public static function jsonp(Closure $handler): void
{
static::$type = 'json-rpc';
$handler();
static::$type = ROUTER_TYPE_HTTP;
}
/**
* @param string $route
* @param string $handler
*
* @throws
*/
public static function post(string $route, string $handler): void
{
$router = Kiri::getDi()->get(DataGrip::class)->get(static::$type);
$router->addRoute([RequestMethod::REQUEST_POST], $route, $handler);
}
/**
* @param string $route
* @param string $handler
*
* @throws
*/
public static function get(string $route, string $handler): void
{
$router = Kiri::getDi()->get(DataGrip::class)->get(static::$type);
$router->addRoute([RequestMethod::REQUEST_GET], $route, $handler);
}
/**
* @param string $route
* @param string $handler
*
* @throws
*/
public static function options(string $route, string $handler): void
{
$router = Kiri::getDi()->get(DataGrip::class)->get(static::$type);
$router->addRoute([RequestMethod::REQUEST_OPTIONS], $route, $handler);
}
/**
* @param string $route
* @param string $handler
*
* @throws
*/
public static function any(string $route, string $handler): void
{
$router = Kiri::getDi()->get(DataGrip::class)->get(static::$type);
$router->addRoute(self::METHODS, $route, $handler);
}
/**
* @param string $route
* @param string $handler
*
* @throws
*/
public static function delete(string $route, string $handler): void
{
$router = Kiri::getDi()->get(DataGrip::class)->get(static::$type);
$router->addRoute([RequestMethod::REQUEST_DELETE], $route, $handler);
}
/**
* @param string $route
* @param string $handler
*
* @throws
*/
public static function head(string $route, string $handler): void
{
$router = Kiri::getDi()->get(DataGrip::class)->get(static::$type);
$router->addRoute([RequestMethod::REQUEST_HEAD], $route, $handler);
}
/**
* @param string $route
* @param string $handler
*
* @throws
*/
public static function put(string $route, string $handler): void
{
$router = Kiri::getDi()->get(DataGrip::class)->get(static::$type);
$router->addRoute([RequestMethod::REQUEST_PUT], $route, $handler);
}
/**
* @param array|RequestMethod $methods
2025-12-30 20:21:44 +08:00
* @param string $route
* @param string|array $handler
2024-12-16 16:36:35 +08:00
*/
public static function addRoute(array|RequestMethod $methods, string $route, string|array $handler): void
{
$router = Kiri::getDi()->get(DataGrip::class)->get(static::$type);
if ($methods instanceof RequestMethod) {
$methods = [$methods];
}
$router->addRoute($methods, $route, $handler);
}
/**
2025-12-30 20:21:44 +08:00
* @param array $config
2024-12-16 16:36:35 +08:00
* @param Closure $closure
*
* @throws
*/
public static function group(array $config, Closure $closure): void
{
$router = Kiri::getDi()->get(DataGrip::class)->get(static::$type);
$router->groupTack[] = $config;
call_user_func($closure);
array_pop($router->groupTack);
}
/**
2026-06-24 20:17:55 +08:00
* 扫描并构建路由表
*
* Master 进程:执行完整扫描(路由文件加载 + app 目录扫描 + DeferRegistry 注入)
* Worker 进程(首次启动):仅加载路由文件注册路由表,跳过全量 app 扫描
* Worker 进程(热重载):检测到文件变更时执行完整扫描流程
*
* 设计原因:
* - Master 已完成类加载和字节码编译,Worker 通过 fork 继承全部内存
* - Worker 重复执行 opcache_compile_file + invalidateClasses 不产生新信息
* - 在应用文件较多时(500+),每个 Worker 的全量扫描会消耗数百 MB 内存导致 OOM
*
2024-12-16 16:36:35 +08:00
* @throws
*/
public function scan_build_route(): void
{
$coordinator = CoordinatorManager::utility(Coordinator::WORKER_START);
$container = Kiri::getDi();
2026-06-24 20:17:55 +08:00
$changedFiles = $container->get(HotReloadState::class)->consume();
2026-06-24 20:37:13 +08:00
// Worker 首次启动(无变更文件 + Master 已完成扫描):
2026-06-24 20:45:37 +08:00
// 重新 include 路由文件(Router::get/post 显式注册) + 基于 Master 扫描清单重建注解路由
// 避免 opcache_compile_file,仅用 Reflection 重建路由,内存开销极小
2026-06-24 20:17:55 +08:00
if (empty($changedFiles) && self::$initialScanDone) {
2026-06-24 20:45:37 +08:00
$container->get(DataGrip::class)->reset(static::$type);
2026-06-24 20:17:55 +08:00
$this->read_dir_file(APP_PATH . 'routes');
2026-06-24 20:45:37 +08:00
$this->rebuildAnnotationRoutes($container);
2026-06-24 20:17:55 +08:00
$this->reset($container);
$coordinator->done();
return;
}
// 标记首次扫描完成(Master 首次启动或 Worker 热重载时执行到此)
self::$initialScanDone = true;
2026-06-24 20:37:13 +08:00
$container->get(DataGrip::class)->reset(static::$type);
2026-06-24 20:17:55 +08:00
$scanner = $container->get(Kiri\Di\Scanner::class);
2026-04-17 16:30:52 +08:00
$artifactState = $container->get(RouteArtifactState::class);
$scanConfig = array_merge(
config('servers.reload.scan', []),
config('site.scanner', [])
);
$scanner->setConfig($scanConfig);
$normalizedAppPath = str_replace('\\', '/', APP_PATH . 'app');
$normalizedRoutePath = str_replace('\\', '/', APP_PATH . 'routes');
$routeChanged = false;
$appChangedFiles = [];
foreach ($changedFiles as $changedFile) {
if (str_starts_with($changedFile, $normalizedRoutePath . '/')) {
$routeChanged = true;
continue;
}
if (str_starts_with($changedFile, $normalizedAppPath . '/')) {
$appChangedFiles[] = $changedFile;
}
}
$usedArtifact = false;
if (($scanConfig['cache_enabled'] ?? false) && !$routeChanged && $artifactState->has(static::$type)) {
$artifact = $artifactState->load(static::$type);
$router = $container->get(DataGrip::class)->get(static::$type);
$usedArtifact = $router->importArtifact($artifact, $appChangedFiles);
}
if (!$usedArtifact) {
$this->read_dir_file(APP_PATH . 'routes');
}
if (!$routeChanged && !empty($appChangedFiles) && ($scanConfig['cache_enabled'] ?? false)) {
$scanner->scanFiles($appChangedFiles, APP_PATH . 'app/', null, !$usedArtifact);
} elseif (!$usedArtifact) {
$scanner->scan(APP_PATH . 'app/');
} else {
$scanner->scanFiles([], APP_PATH . 'app/', null, false);
}
2024-12-16 16:36:35 +08:00
$this->reset($container);
2026-04-17 16:30:52 +08:00
$artifactState->store(static::$type, $container->get(DataGrip::class)->get(static::$type)->exportArtifact());
2024-12-16 16:36:35 +08:00
$coordinator->done();
}
/**
* @param ContainerInterface $container
*
* @return void
* @throws
*/
public function reset(ContainerInterface $container): void
{
$router = $container->get(DataGrip::class)->get(static::$type);
2026-04-17 16:30:52 +08:00
if ((bool)config('servers.reload.scan.prebuild_http_handlers', false)) {
$router->warmHttpHandlers();
2024-12-16 16:36:35 +08:00
}
}
2026-06-24 20:45:37 +08:00
/**
* 基于 Master 扫描清单重建注解路由(轻量级,无文件 I/O)
* 遍历 Scanner manifest 中的所有类,用 Reflection 重新发现 #[Route]/#[Get] 等注解
* 避免 Worker 重复执行 opcache_compile_file,但确保注解路由不丢失
*
* @param ContainerInterface $container
* @return void
*/
private function rebuildAnnotationRoutes(ContainerInterface $container): void
{
$scanner = $container->get(Kiri\Di\Scanner::class);
$scanConfig = array_merge(
config('servers.reload.scan', []),
config('site.scanner', [])
);
$scanner->setConfig($scanConfig);
$manifestEntries = $scanner->getManifestClasses();
2026-06-24 20:49:06 +08:00
if (empty($manifestEntries)) {
\Kiri::getLogger()->warning('Annotation route rebuild: manifest is empty, annotation routes will NOT be registered');
return;
}
$routeCount = 0;
$classCount = 0;
$errorCount = 0;
$dispatchCount = 0;
2026-06-24 20:45:37 +08:00
foreach ($manifestEntries as $path => $entry) {
$classes = is_array($entry) && isset($entry['classes']) ? $entry['classes'] : [];
foreach ($classes as $class) {
if (!class_exists($class)) {
continue;
}
2026-06-24 20:49:06 +08:00
$classCount++;
2026-06-24 20:45:37 +08:00
try {
$reflect = $container->getReflectionClass($class);
if (!$reflect->isInstantiable() || $reflect->isTrait() || $reflect->isEnum() || $reflect->isInterface()) {
continue;
}
foreach ($reflect->getMethods() as $method) {
if ($method->isStatic() || $method->getDeclaringClass()->getName() !== $class) {
continue;
}
foreach ($method->getAttributes() as $attribute) {
$attrName = $attribute->getName();
if (!class_exists($attrName)) {
continue;
}
try {
$instance = $attribute->newInstance();
if ($instance instanceof Kiri\Di\Interface\InjectMethodInterface) {
$instance->dispatch($class, $method->getName());
2026-06-24 20:49:06 +08:00
$dispatchCount++;
2026-06-24 20:45:37 +08:00
}
} catch (\Throwable $e) {
2026-06-24 20:49:06 +08:00
$errorCount++;
\Kiri::getLogger()->error("Annotation rebuild error [{$class}::{$method->getName()} @ {$attrName}]: {$e->getMessage()}");
2026-06-24 20:45:37 +08:00
}
}
}
} catch (\Throwable $e) {
2026-06-24 20:49:06 +08:00
$errorCount++;
\Kiri::getLogger()->error("Annotation rebuild class [{$class}]: {$e->getMessage()}");
2026-06-24 20:45:37 +08:00
}
}
}
2026-06-24 20:49:06 +08:00
$router = $container->get(DataGrip::class)->get(static::$type);
$routeCount = count($router->dump());
\Kiri::getLogger()->info("Annotation route rebuild: {$classCount} classes processed, {$dispatchCount} annotation routes dispatched, {$routeCount} total routes, {$errorCount} errors");
2026-06-24 20:45:37 +08:00
}
2024-12-16 16:36:35 +08:00
/**
* @param $path
*
* @return void
* @throws
*/
private function read_dir_file($path): void
{
$files = glob($path . '/*');
for ($i = 0; $i < count($files); $i++) {
$file = $files[$i];
if (is_dir($file)) {
$this->read_dir_file($file);
} else {
$this->resolve_file($file);
}
}
}
/**
* @param $files
*
* @throws
*/
private function resolve_file($files): void
{
try {
2026-04-17 16:30:52 +08:00
static::$currentSourceFile = str_replace('\\', '/', realpath($files) ?: $files);
2024-12-16 16:36:35 +08:00
include "$files";
} catch (\Throwable $throwable) {
2025-12-31 00:19:29 +08:00
\Kiri::getLogger()->json_log($throwable);
2026-04-17 16:30:52 +08:00
} finally {
static::$currentSourceFile = null;
2024-12-16 16:36:35 +08:00
}
}
2023-04-15 23:29:27 +08:00
2026-04-17 16:30:52 +08:00
public static function getCurrentSourceFile(): ?string
{
return static::$currentSourceFile;
}
2023-04-15 23:29:27 +08:00
}