Skip to content

RPC 中间件 ​

RPC 中间件使用与 Web 中间件类似的 process(request, handler) 模型, 但操作的是 RpcRequestInterface / RpcResponseInterface。

1. 接口 ​

php
use kuiper\rpc\message\RpcRequestInterface;
use kuiper\rpc\message\RpcResponseInterface;
use kuiper\rpc\RpcRequestHandlerInterface;

// 框架接口定义(namespace kuiper\rpc\middleware)
interface MiddlewareInterface
{
    public function process(
        RpcRequestInterface $request,
        RpcRequestHandlerInterface $handler
    ): RpcResponseInterface;
}

客户端和服务端共用该接口。

2. MiddlewareStack ​

MiddlewareStack 按数组顺序执行:

php
$stack = new MiddlewareStack([
    new AccessLog(),
    new Retry(),
], $finalHandler);

$stack->handle($request);

执行顺序:

text
AccessLog (before)
  → Retry (before)
    → finalHandler
  → Retry (after)
→ AccessLog (after)

即数组下标 0 的中间件在最外层,最先执行。

3. 客户端中间件 ​

RpcExecutorFactory 的第二个参数是中间件数组:

php
$executorFactory = new RpcExecutorFactory(
    $handler,
    [
        new AddRequestReferer(),
        new Retry(maxAttempts: 3),
        new CircuitBreaker('demo.DemoService'),
        new AccessLog('rpc.access'),
    ]
);

数组第一个是最外层(先拿到请求、最后拿到响应)。用配置挂载时写法相同:

yaml
application:
  rpc:
    default:
      middlewares:
        - kuiper\rpc\client\middleware\AccessLog
        - kuiper\resilience\middleware\CircuitBreaker
        - kuiper\resilience\middleware\Retry

推荐的链路顺序(ServiceDiscovery 开启时会自动置顶)、熔断与重试的取舍、 以及"重试次数 × 超时 = 最坏耗时"的估算见 客户端最佳实践。

AccessLog ​

php
new AccessLog('rpc.access');

记录:

  • endpoint
  • service / method
  • total_duration_ms
  • success
  • error message

duration 的语义取决于中间件位置:

  • 放在最靠近 transport 的位置:反映传输 + 编解码耗时
  • 放在外层:包含其它中间件耗时

需要 LoggerAwareInterface 注入 logger。

Retry ​

php
new Retry(
    maxAttempts: 3,
    waitMs: 100,
    idempotentPatterns: ['get*', 'find*']
);
  • 仅对 ConnectionException / RequestException 重试

  • 线性退避:第 n 次重试等待 waitMs * n 毫秒(无抖动;Swoole 协程下 usleep 会阻塞 整个 worker 的其它协程,建议仅在 CLI 场景使用)

  • 默认 idempotentPatterns: [],即默认不重试任何方法(安全默认)—— 需要重试时显式放宽,例如只匹配查询方法:

    php
    new Retry(maxAttempts: 3, waitMs: 100, idempotentPatterns: ['get*', 'find*', 'query*', 'list*']);
  • 传 ['*'] 表示重试所有方法——对非幂等的写方法(如 create、update) 网络超时后会重复执行,仅在确认全部方法幂等时使用

  • 支持通配符 *

CircuitBreaker ​

php
new CircuitBreaker(
    serviceName: 'demo.DemoService',
    failureThreshold: 5,
    recoveryTimeout: 30,
    metrics: $metrics
);

状态:

  • CLOSED:正常
  • OPEN:失败次数达到阈值,直接拒绝
  • HALF_OPEN:恢复超时后允许有限探测

失败计数语义与已知限制:

  • 失败计数是累计的:成功调用不会重置计数(仅 half-open 恢复为 closed 时清零), 长期偶发失败会累积到阈值导致误熔断
  • 只有抛异常(连接失败等传输层错误)才计为失败;响应里带 error 的业务失败 不计数,不会触发熔断
  • 熔断拒绝抛通用的 \RuntimeException,调用方只能靠消息文本区分
  • Swoole 协程环境下使用 Swoole\Coroutine\Channel 作为互斥锁,锁覆盖整个下游调用; 若中间件实例在协程内创建,所有并发请求会被串行化(实例在主协程创建则无锁)。 多 worker / 多实例之间熔断状态不共享。

支持 CircuitBreakerMetricsInterface 导出:

  • onSuccess
  • onFailure
  • onCallNotPermitted
  • onStateTransition

NormalizeArguments ​

php
new NormalizeArguments($normalizer);

使用 NormalizerInterface 再次规范化请求参数;normalizer 为 null 时直接透传。

AddRequestReferer ​

为请求属性生成并写入:

  • RpcContext::TRACE_ID
  • RpcContext::SPAN_ID

如果请求已有值则保留。

NamespaceAsHost ​

零配置寻址的运行时兜底:请求的 endpoint 的 host 为空时,用 ServiceLocator::getNamespace() 补齐主机名(v0.8 的同名中间件语义)。

框架自建客户端的 host 已在装配层解析好(未配置 host 时直接取 ns),因此该中间件 在客户端链上是 no-op;它默认挂在服务发现之后、用户配置的中间件之前,保证手工装配 RpcExecutorFactory、或自定义中间件替换了 endpoint 的场景仍然零配置可用。

构造参数:port(覆盖端口)、subDomain(追加在命名空间之后的域名后缀)。

ServiceDiscovery ​

服务发现中间件,详见 服务发现。

4. 服务端中间件 ​

通过配置注册:

php
'application' => [
    'rpc' => [
        'server' => [
            'middlewares' => [
                \App\rpc\middleware\LoggingMiddleware::class,
            ],
        ],
    ],
],

配置键用复数 middlewares

服务端中间件列表的配置键是 application.rpc.server.middlewares(与客户端一致)。 旧的单数键 application.rpc.server.middleware 仍可工作(仅在复数键未配置时回退读取), 但已不推荐使用,新配置请统一写 middlewares。

RpcServerConfiguration 会把类名从容器中取出并添加到 RpcServerRpcRequestHandler。

也可以手动添加:

php
$handler = new RpcServerRpcRequestHandler($registry, $responseFactory);
$handler->addMiddleware(new LoggingMiddleware());

执行语义 ​

  • 业务异常不会穿过中间件:业务方法抛出的异常在最终处理环节被转成错误响应 (serve() 内 catch (\Throwable),默认 -32603)后沿链返回
  • 中间件看到的是带 error 的响应对象(可据此上报),拿不到异常本身; 原异常经 previous 保留
  • 服务不存在、方法不存在、参数错误等协议级错误同样走这条路径(-32600/-32602)
  • 中间件自身抛出的异常(如限流、鉴权中间件)会穿出中间件链,由 handle() 兜底转成错误响应;挂在最外层的 AccessLog 会先记一条 error 级日志(error_type 标明异常类)再继续上抛

内置服务端中间件 ​

框架在 kuiper\rpc\server\middleware 下提供了一组开箱可用的服务端中间件:

中间件作用构造参数
AccessLog记录服务名、方法、耗时与业务成败(PSR-3 logger);默认已挂载,见下requestFilter、sampleRate
Error把异常转换为 JSON-RPC 错误响应无(自动注入 RpcServerResponseFactoryInterface)
AuthenticationMiddleware校验 JWT(HS256/HS384/HS512),通过后把 payload 写入 auth.payload attributesecret、algorithm、leeway、tokenAttributes
RateLimitMiddleware令牌桶限流,超限抛 RateLimitExceededException(带 retryAfter)rate、burst、clientIdentifier、cleanupInterval、clientIpAttributes
SensitiveDataMaskingMiddleware日志中的敏感字段脱敏(password、token、secret 等)sensitiveFields、maskValue

AccessLog(默认启用) ​

AccessLog 由 RpcServerConfiguration 默认挂到服务端中间件链最外层, 每次 RPC 调用写一行日志到专用通道 rpc-access.log,记录业务成败 (成功 / 业务失败 / 异常)。字段、配置项与两层日志分工见 RPC 服务端文档的访问日志章节。

  • 开关:application.rpc.access_log_enabled(环境变量 RPC_ACCESS_LOG_ENABLED, 默认 true);关闭后不挂载中间件、不写该文件;
  • 采样:application.rpc.log_sample_rate(默认 1.0),只采样成功请求, 失败请求始终记录;
  • 需要自定义过滤回调或采样率时,在 application.rpc.server.middlewares 里 显式挂载自己的实例(此时不会再自动挂载一次):
php
use kuiper\rpc\server\middleware\AccessLog;

return [
    'application' => [
        'rpc' => [
            'server' => [
                'middlewares' => [
                    // 只记录特定服务,且成功请求 10% 采样
                    new AccessLog(
                        requestFilter: static fn ($request, $response): bool => 'OrderService' === $request->getRpcMethod()->getServiceLocator()->getName(),
                        sampleRate: 0.1,
                    ),
                ],
            ],
        ],
    ],
];

其它内置中间件需要显式挂载,挂载方式与自定义中间件一致,写类名即可:

php
'application' => [
    'rpc' => [
        'server' => [
            'middlewares' => [
                \kuiper\rpc\server\middleware\AccessLog::class,
                \kuiper\rpc\server\middleware\Error::class,
            ],
        ],
    ],
],

需要参数的中间件(认证、限流)不能只写类名——配置里的类名会从容器取实例, 构造参数的默认值不会从配置读取。两种配置方式:

方式一:在 config.php 里直接放实例(最简单):

php
use kuiper\rpc\server\middleware\AuthenticationMiddleware;

return [
    'application' => [
        'rpc' => [
            'server' => [
                'middlewares' => [
                    \kuiper\rpc\server\middleware\AccessLog::class,
                    new AuthenticationMiddleware(secret: (string) env('JWT_SECRET')),
                ],
            ],
        ],
    ],
];

方式二:在 container.php 里注册 Bean(实例需要容器里的其它依赖时用):

php
use kuiper\rpc\server\middleware\AuthenticationMiddleware;

$builder->addDefinitions([
    AuthenticationMiddleware::class => \DI\factory(
        static fn (): AuthenticationMiddleware => new AuthenticationMiddleware(
            secret: (string) env('JWT_SECRET'),
        )
    ),
]);

之后配置里写 \kuiper\rpc\server\middleware\AuthenticationMiddleware::class 即可。

认证中间件的 token 来源:v0.9 的 RPC 请求不携带 HTTP 头, token 从 request attribute 读取,依次查找 auth.token、auth.authorization、authorization (允许带 Bearer 前缀)。HTTP 场景下请在 web 层写一个中间件, 把 Authorization 头放进同名 attribute。

限流中间件的客户端标识:默认从 client_ip、remote_addr、remote_address 三个 attribute 依次查找;同样需要由上层把来源写入 attribute。

5. 自定义中间件 ​

客户端 ​

php
use kuiper\rpc\message\RpcRequestInterface;
use kuiper\rpc\message\RpcResponseInterface;
use kuiper\rpc\middleware\MiddlewareInterface;
use kuiper\rpc\RpcRequestHandlerInterface;

class RequestIdMiddleware implements MiddlewareInterface
{
    public function process(
        RpcRequestInterface $request,
        RpcRequestHandlerInterface $handler
    ): RpcResponseInterface {
        $request = $request->withAttribute('request.id', bin2hex(random_bytes(8)));

        return $handler->handle($request);
    }
}

服务端 ​

php
class TimingMiddleware implements MiddlewareInterface
{
    public function process(
        RpcRequestInterface $request,
        RpcRequestHandlerInterface $handler
    ): RpcResponseInterface {
        $start = microtime(true);
        try {
            return $handler->handle($request);
        } finally {
            error_log(sprintf(
                '%s.%s took %.2fms',
                $request->getRpcMethod()->getServiceLocator()->getName(),
                $request->getRpcMethod()->getMethodName(),
                (microtime(true) - $start) * 1000
            ));
        }
    }
}

6. 中间件工厂 ​

kuiper\rpc\middleware\MiddlewareFactoryInterface 和 AbstractMiddlewareFactory 提供了按优先级创建中间件的扩展点:

php
class MyMiddlewareFactory extends AbstractMiddlewareFactory
{
    public function create(ContainerInterface $container): MiddlewareInterface
    {
        return new MyMiddleware();
    }
}

优先级通过构造参数 priority 指定;数字越小越靠前。

7. 当前限制 ​

  • 客户端中间件通过 middlewares 配置挂载(数组第一个最外层);启用 service_discovery.enabled 时服务发现中间件自动置于最前。
  • 服务端中间件通过 application.rpc.server.middlewares 配置,按数组顺序执行 (旧的单数键 middleware 仅作兼容回退,已不推荐使用)。
  • 服务端中间件的构造参数不从 application.rpc.server.* 配置读取: 类名走容器(默认参数生效),带参数的中间件需自行注册 Bean(见第 4 节)。
  • AuthenticationMiddleware 自实现的 JWT 校验只支持 HMAC 系列(HS256/HS384/HS512), 不支持 RS/ES 非对称算法与 kid 头。
  • RateLimitMiddleware 的令牌桶状态保存在进程内存里:Swoole 多 worker 下各 worker 独立计数, 需要全局限流时应自行接入 Redis 等共享存储。

基于 MIT 许可发布