Skip to content

编解码 ​

RPC 模块通过 Codec 层把 RpcRequest / RpcResponse 转换为传输层消息, 与具体 HTTP/TCP 传输解耦。

1. 接口 ​

php
interface RequestCodecInterface
{
    public function supports(string $protocol, string $serialization): bool;
    public function encodeRequest(RpcRequestInterface $request): TransportRequestInterface;
    public function decodeRequest(TransportRequestInterface $message): RpcRequestInterface;
}

interface ResponseCodecInterface
{
    public function supports(string $protocol, string $serialization): bool;
    public function encodeResponse(RpcResponseInterface $response): TransportResponseInterface;
    public function decodeResponse(TransportResponseInterface $message, ?RpcRequestInterface $request = null): RpcResponseInterface;
}

一个 Codec 通常同时实现两者。CodecInterface 是旧的合并接口,已标记为废弃。

2. 内置 Codec ​

Codec协议说明
HttpJsonRpcCodechttpJSON-RPC 2.0 over HTTP
TcpJsonRpcCodectcpJSON-RPC over TCP(不含分帧)
TarsHttpJsonRpcCodechttpTARS RPC 报文:多返回值、out 参数、业务错误码

HttpJsonRpcCodec ​

请求:

json
{"jsonrpc":"2.0","method":"demo.DemoService.hello","params":{"name":"Kuiper"},"id":1}
  • method 格式:{service}.{method}
  • service 本身可以包含点,如 demo.DemoService.hello,按最后一个点拆分
  • params 支持对象(命名参数)或数组(位置参数)
  • id 会被保存到 request attribute jsonrpc.id,响应原样回显

响应:

json
{"jsonrpc":"2.0","result":["Hello, Kuiper!"],"id":1}

v0.9 服务端默认把方法返回值包成单元素数组,客户端 RpcExecutor 通过 result[0] 取值。

严格 JSON-RPC 2.0 客户端注意 result 的形态差异

HttpJsonRpcCodec 的响应 result 恒为数组(单返回值包装成单元素数组)—— kuiper 客户端约定 result[0] 取值。严格按 JSON-RPC 2.0 语义解析的第三方客户端 (期望 result 为标量 / 对象本身)会拿到数组而不匹配。

期望「result 就是返回值本身」的外部客户端,让它们走 TarsHttpJsonRpcCodec(不带 @extended 的请求,服务端返回单值, 见下一节)——这是 kuiper 的设计权衡:单 codec 内两种形态无法同时满足。

错误:

json
{"jsonrpc":"2.0","error":{"code":-32602,"message":"..."},"id":1}

错误码来自 JsonRpcServerException;普通异常映射为 -32603。

TcpJsonRpcCodec ​

  • 只负责 JSON 内容,不负责 TCP 分帧
  • 需要配合使用长度前缀或 EOF 的 TCP 传输器
  • SocketTcpTransporter 使用 4 字节大端长度前缀

TarsHttpJsonRpcCodec ​

TARS RPC 在 HTTP 上的报文格式,与 kuiper v0.8 的 JSON-RPC 服务协议一致 (v0.8 的服务端就是这个格式,因此老客户端不用任何修改就能调用 v0.9 服务端,反之亦然)。

请求:客户端总是携带 @extended: "1.0",id 是整数,params 是位置数组:

json
{"id":1,"jsonrpc":"2.0","method":"demo.DemoService.hello","params":["Kuiper"],"@extended":"1.0"}
  • @extended 存在时,服务端返回完整的 [返回值, ...out 参数] 并原样回显 @extended
  • 不带 @extended 的请求(严格 JSON-RPC 2.0 客户端),服务端返回单值:result 是返回值本身

响应:

json
// 带 @extended:完整结果数组
{"@extended":"1.0","jsonrpc":"2.0","id":1,"result":[{"id":1}]}

// 不带 @extended:单值
{"jsonrpc":"2.0","id":1,"result":{"id":1}}

响应体以 \r\n 结尾(v0.8 的协议 EOF)。

多输出参数(out 参数):TARS 用引用参数表达多输出。服务端 tars 文件里的 out string errorMsg 会生成 PHP 引用参数:

php
// 生成的 servant 接口
public function findAllUser(?int &$total): array;

调用方传入变量,方法返回后变量被回填:

php
$total = null;
$users = $client->findAllUser($total);   // $total 被写成 3
  • 服务端:RpcServerRpcRequestHandler 为引用参数准备占位变量, 方法返回后把返回值与各 out 参数一起放进 result
  • 客户端:代理用 RpcExecutor::executeAll() 取回全部结果,再解构回填到引用参数
  • out 参数不出现在请求参数里,客户端无需为其传值

二进制字段(vector<byte>):tars 中的 vector&lt;byte&gt; 生成为 \kuiper\serializer\BinaryString,JSON 中以 base64 字符串传输:

json
{"attachments":[{"content":"JVBERi0xLjcK...","ossUrl":""}]}

业务错误码:error.code 使用业务异常 getCode()(如 1011400), 没有业务码时回退 -32603。

error.data:与 v0.8 一致,错误响应带 data 字段(base64 的异常信息), v0.8 客户端会把它反序列化成原始异常后抛出。

json
{"jsonrpc":"2.0","id":1,"error":{"code":1011400,"message":"...","data":"eyJjbGFzcyI6..."}}

HTTP 状态码:v0.8 服务端用 400(请求非法)/ 500(业务异常),v0.9 统一用 200, 错误信息都在响应体的 error 里;v0.8 与 v0.9 的客户端都不依赖状态码。

启用:

php
'application' => [
    'rpc' => [
        'server' => [
            'codec' => 'tars',
        ],
    ],
],

3. CodecRegistry ​

php
$registry = new CodecRegistry([
    new HttpJsonRpcCodec(),
    new TcpJsonRpcCodec(),
]);

$codec = $registry->getCodec('http', 'jsonrpc');
  • getCodec() 返回同时实现请求/响应接口的 codec
  • 找不到时抛 CodecNotFoundException
  • 也保留 getRequestCodec() / getResponseCodec() 两个查询方法

4. 自定义 Codec ​

php
class MyJsonRpcCodec extends HttpJsonRpcCodec
{
    public function decodeRequest(TransportRequestInterface $message): RpcRequestInterface
    {
        // 自定义请求解析
        return parent::decodeRequest($message);
    }

    public function encodeResponse(RpcResponseInterface $message): TransportResponseInterface
    {
        // 自定义响应格式
        return parent::encodeResponse($message);
    }
}

$registry = new CodecRegistry([new MyJsonRpcCodec()]);

如需替换服务端默认 Codec,可以覆盖 CodecRegistry Bean,或在 RpcServerConfiguration 的 createCodecRegistry() 中扩展。

5. 序列化方式 ​

支持的组合:

text
protocol:     http / https / tcp
serialization: tars(默认) / jsonrpc

各编解码器的 supports():

编解码器protocolserialization
HttpJsonRpcCodechttp、httpsjsonrpc
TarsHttpJsonRpcCodec(默认)http、httpstars、jsonrpc
TcpJsonRpcCodectcpjsonrpc

6. 错误映射 ​

AbstractJsonRpcCodec 统一处理错误响应:

php
$error = $message->getError();
$data['error'] = [
    'code' => $error instanceof JsonRpcServerException
        ? $error->getErrorCode()->value
        : JsonRpcErrorCode::INTERNAL_ERROR->value,
    'message' => $error->getMessage(),
];

TarsHttpJsonRpcCodec 则优先使用业务异常自身的 getCode()。

基于 MIT 许可发布