You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

71 lines
1.8 KiB

<?php
declare(strict_types=1);
/**
* Trace.php
* Created by PhpStorm.
* Date: 2026/10/17
* Time: 09:40
* Author: qian.guo
* E-mail: yiyezhiqiutel@gmail.com
*/
namespace app\middleware;
use Closure;
use think\Request;
/**
* 请求链路追踪中间件
* 设计说明:
* - 每次请求分配一个 trace_id,只写响应头 X-Trace-Id,不进响应体
* 规范第七节的响应体固定为 code/msg/data(+total),不放额外字段
* - 客户端可自带 X-Trace-Id 便于跨端串联,但必须校验格式后再采用
* 直接回显任意字符串会被用来构造响应头注入或污染日志
* - 用静态属性暴露当前 trace_id:异常渲染发生在中间件之后
* $next 抛异常时本中间件后续代码不会执行,只有提前写入的静态值才拿得到
*/
class Trace
{
// 当前请求的链路ID
private static $trace_id = '';
public function handle(Request $request, Closure $next)
{
$incoming = (string) $request->header('x-trace-id', '');
$trace_id = '';
if (preg_match('/^[0-9a-f]{8,32}$/i', $incoming) === 1) {
$trace_id = strtolower($incoming);
}
if ($trace_id === '') {
$trace_id = self::generate();
}
self::$trace_id = $trace_id;
$response = $next($request);
return $response->header(['X-Trace-Id' => $trace_id]);
}
/**
* 读取当前链路ID
* getTraceId
* @return string
*/
public static function traceId()
{
return self::$trace_id;
}
/**
* 生成链路ID
* createTraceId
* @return string 8 位十六进制,足够单次请求周期内避免碰撞且不泄漏内部序号
*/
public static function generate()
{
return bin2hex(random_bytes(4));
}
}