Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
.DS_Store
.idea
.vscode
.venv
.ccls
.ccls-cache

Expand Down
16 changes: 4 additions & 12 deletions docs/developer_guide/develop_plugins/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,7 @@ Business configuration uses `ConfigLoader`: first call `provider.load(path)` to

## Decoder

A decoder turns bytes into a dict. The registration type is `PluginType.CONFIG_DECODER`. The built-in registered names are `yaml`, `json`, and `noop`. What `with_codec` takes is that registered name:

```python
from trpc_sdk.config import with_codec

with_codec("yaml")
```
A decoder turns bytes into a dict. The registration type is `PluginType.CONFIG_DECODER`. The built-in registered names are `yaml`, `json`, and `noop`.:

`noop` returns the bytes unchanged. That result has no interface for reading by key, so `loader.get` cannot be used with it.

Expand Down Expand Up @@ -59,7 +53,7 @@ class MyDecoder(BaseConfigDecoder):
self._options = options
```

Use it as `with_codec("my_decoder")`.
Use it as `ConfigLoaderFactory.sync_load(..., decoder="my_decoder",)`.

## Data Source

Expand Down Expand Up @@ -114,13 +108,11 @@ To read a local file, replace `"memory"` with `"file"`. `FileConfigProvider` is

```python
from trpc_sdk.config import ConfigLoaderFactory
from trpc_sdk.config import with_codec
from trpc_sdk.config import with_provider

loader = ConfigLoaderFactory.sync_load(
"application.yaml",
with_provider("file"),
with_codec("yaml"),
decoder="yaml",
provider="file"
)
server = loader.get("server", {})
```
Expand Down
16 changes: 4 additions & 12 deletions docs/developer_guide/develop_plugins/config.zh_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,7 @@

## 解码器

解码器把 bytes 变成 dict,注册类型是 `PluginType.CONFIG_DECODER`。内置注册名是 `yaml`、`json`、`noop`。`with_codec` 传入的是这个注册名:

```python
from trpc_sdk.config import with_codec

with_codec("yaml")
```
解码器把 bytes 变成 dict,注册类型是 `PluginType.CONFIG_DECODER`。内置注册名是 `yaml`、`json`、`noop`。

`noop` 原样返回 bytes。这种结果没有按 key 取值的接口,`loader.get` 不能和它一起用。

Expand Down Expand Up @@ -57,7 +51,7 @@ class MyDecoder(BaseConfigDecoder):
self._options = options
```

使用时写成 `with_codec("my_decoder")`。
使用时写成 `ConfigLoaderFactory.sync_load(decoder="my_decoder")`。

## 数据源

Expand Down Expand Up @@ -112,13 +106,11 @@ class MemoryConfigProvider(BaseConfigProvider):

```python
from trpc_sdk.config import ConfigLoaderFactory
from trpc_sdk.config import with_codec
from trpc_sdk.config import with_provider

loader = ConfigLoaderFactory.sync_load(
"application.yaml",
with_provider("file"),
with_codec("yaml"),
decoder="yaml",
provider="file"
)
server = loader.get("server", {})
```
Expand Down
16 changes: 8 additions & 8 deletions docs/developer_guide/develop_plugins/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ English | [中文](database.zh_CN.md)

# How to Write a Database Plugin

When a call to Redis, MySQL, or another store should reuse the RPC client's naming route (`Selector`), timeout control, and client filters (metrics, tracing, and so on), wrap the third-party database SDK into the `Client.invoke` path under a custom `protocol`. tRPC-Python ships Redis, MySQL, and Kafka plugins in the ecosystem repository [python-database](https://github.com/trpc-ecosystem/python-database).
When a call to Redis, MySQL, or another store should reuse the RPC client's naming route (`Selector`), timeout control, and client filters (metrics, tracing, and so on), wrap the third-party database SDK into the `TrpcClient.invoke` path under a custom `protocol`. tRPC-Python ships Redis, MySQL, and Kafka plugins in the ecosystem repository [python-database](https://github.com/trpc-ecosystem/python-database).

The overall workflow is:

1. **Pass the command via `req_head`**: Database SDKs usually take structured commands or arguments rather than serialized wire bytes. The caller passes empty bytes `b""` as the request body (with `SerializationType.Noop`) and attaches the command object via `Options().set_req_head(command)`, which places it on `msg.client_req_head`.
1. **Pass the command via `req_head`**: Database SDKs usually take structured commands or arguments rather than serialized wire bytes. The caller passes empty bytes `b""` as the request body (with `SerializationType.NOOP`) and attaches the command object via `Options().set_req_head(command)`, which places it on `msg.client_req_head`.
2. **Register a pass-through `CLIENT_CODEC`**: Register a codec that returns the byte buffer unchanged so the protocol slot is valid.
3. **Execute the SDK call in `CLIENT_TRANSPORT`**: At the end of the client filter chain, `round_trip` reads the resolved `(host, port)` from `options.address` and the command object from `msg.client_req_head`, invokes the third-party database SDK, and writes the result back onto the command object.

Expand All @@ -20,7 +20,7 @@ The walkthrough below registers a generic protocol named `store` without tying i

When `protocol: store` is set in `trpc_python.yaml` or via call options, `Options.set_protocol("store")` looks up plugins in this exact order:

1. **Look up `CLIENT_CODEC`**: Calls `get_client_codec(protocol)`. **If no client codec is registered under that name, `set_protocol` returns immediately** without updating the parser or transport. The options instance keeps the default `trpc` transport with `opts.codec = None`, and `Client.invoke` subsequently raises `ClientEncodeError("client codec empty")` before reaching the transport layer.
1. **Look up `CLIENT_CODEC`**: Calls `get_client_codec(protocol)`. **If no client codec is registered under that name, `set_protocol` returns immediately** without updating the parser or transport. The options instance keeps the default `trpc` transport with `opts.codec = None`, and `TrpcClient.invoke` subsequently raises `ClientEncodeError("client codec empty")` before reaching the transport layer.
2. **Look up `CLIENT_CHECKER`**: Once a codec exists, calls `get_client_parser(protocol)`. Because the third-party database SDK manages its own framing and connections, you do not need to register a client checker (`set_parser(None)` has no effect on a custom `round_trip`).
3. **Look up `CLIENT_TRANSPORT`**: Calls `get_client_transport(protocol)`. If a transport instance is found, it replaces the default `trpc` transport initialized in `_create_client_options`.

Expand Down Expand Up @@ -100,15 +100,15 @@ client:

## 4. Calling from Business Code

When calling `Client().invoke()` from business code, pay attention to three details:
When calling `TrpcClient().invoke()` from business code, pay attention to three details:

1. **Set the callee service name on the message before calling `invoke`**: `get_options` loads YAML configuration (`load_client_config`) using `msg.callee_service_name` *before* applying the per-call `Options` list. Always call `msg.set_callee_service_name("trpc.app.server.store")` prior to `invoke`. If you only pass `Options().set_service_name(...)`, the YAML lookup has already happened with an empty name, and the `protocol` and `target` from YAML will be missed.
2. **Use `SerializationType.Noop` with an empty request body**: `NoopSerializer.serialize` only accepts `bytes` or `Body` instances, so a custom `StoreCommand` object cannot be passed as the request body `req`. Pass `b""` as the request body, `Body` as the response class, and attach `command` via `Options().set_req_head(command)` (which `update_message` copies to `msg.client_req_head`).
2. **Use `SerializationType.NOOP` with an empty request body**: `NoopSerializer.serialize` only accepts `bytes` or `Body` instances, so a custom `StoreCommand` object cannot be passed as the request body `req`. Pass `b""` as the request body, `Body` as the response class, and attach `command` via `Options().set_req_head(command)` (which `update_message` copies to `msg.client_req_head`).
3. **Import the plugin module at startup**: Make sure the module defining `StoreCodec` and `StoreTransport` is imported before making calls so `@register_plugin` executes.

```python
from trpc_sdk.abc import clone_client_message
from trpc_sdk.client import Client
from trpc_sdk.client import TrpcClient
from trpc_sdk.client import Options
from trpc_sdk.serialization import Body
from trpc_sdk.serialization import SerializationType
Expand All @@ -124,14 +124,14 @@ async def execute(ctx, statement: str):
ctx, _ = clone_client_message(ctx)
ctx.get_message().set_callee_service_name("trpc.app.server.store")
command = StoreCommand(statement)
await Client().invoke(
await TrpcClient().invoke(
ctx,
b"",
Body,
[
Options()
.set_req_head(command)
.set_serialization_type(SerializationType.Noop),
.set_serialization_type(SerializationType.NOOP),
],
)
return command.result
Expand Down
16 changes: 8 additions & 8 deletions docs/developer_guide/develop_plugins/database.zh_CN.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# 怎么开发数据库插件

在 tRPC-Python 中,如果希望访问 Redis、MySQL 等存储时,能够复用 RPC 客户端的名字服务路由(`Selector`)、超时控制以及客户端拦截器(如监控上报、调用链追踪),可以通过自定义 `protocol` 将第三方数据库 SDK 接入 `Client.invoke` 调用链路。tRPC-Python 提供了 Redis、MySQL、Kafka 插件,可以参考生态仓库 [python-database](https://github.com/trpc-ecosystem/python-database)。
在 tRPC-Python 中,如果希望访问 Redis、MySQL 等存储时,能够复用 RPC 客户端的名字服务路由(`Selector`)、超时控制以及客户端拦截器(如监控上报、调用链追踪),可以通过自定义 `protocol` 将第三方数据库 SDK 接入 `TrpcClient.invoke` 调用链路。tRPC-Python 提供了 Redis、MySQL、Kafka 插件,可以参考生态仓库 [python-database](https://github.com/trpc-ecosystem/python-database)。

整体思路如下:

1. **命令传递**:数据库 SDK 通常接收结构化的命令或参数,而非序列化后的字节流。调用方将请求体设为空字节 `b""`(配合 `SerializationType.Noop`),把真正的命令对象放进 `Options().set_req_head(command)`,通过消息头 `msg.client_req_head` 传给传输层。
1. **命令传递**:数据库 SDK 通常接收结构化的命令或参数,而非序列化后的字节流。调用方将请求体设为空字节 `b""`(配合 `SerializationType.NOOP`),把真正的命令对象放进 `Options().set_req_head(command)`,通过消息头 `msg.client_req_head` 传给传输层。
2. **协议占槽(`CLIENT_CODEC`)**:注册一个直通(pass-through)的客户端编解码器,对字节流原样透传。
3. **执行调用(`CLIENT_TRANSPORT`)**:在客户端过滤器链末端的 `round_trip` 中,从 `options.address` 拿到路由解析出的 `(host, port)`,从 `msg.client_req_head` 拿到命令对象,调用第三方数据库 SDK 完成读写,并将结果写回命令对象。

Expand All @@ -18,7 +18,7 @@

在 `trpc_python.yaml` 或调用参数中指定 `protocol: store` 时,`Options.set_protocol("store")` 会按以下顺序查找并挂载插件:

1. **查找 `CLIENT_CODEC`**:调用 `get_client_codec(protocol)`。**如果未找到同名 codec,`set_protocol` 会直接返回**,不会继续替换后续的 checker 和 transport。此时 options 仍保留默认的 `trpc` transport,且 `opts.codec` 为 `None`,后续调用 `Client.invoke` 会在进入传输层前抛出 `ClientEncodeError("client codec empty")`。
1. **查找 `CLIENT_CODEC`**:调用 `get_client_codec(protocol)`。**如果未找到同名 codec,`set_protocol` 会直接返回**,不会继续替换后续的 checker 和 transport。此时 options 仍保留默认的 `trpc` transport,且 `opts.codec` 为 `None`,后续调用 `TrpcClient.invoke` 会在进入传输层前抛出 `ClientEncodeError("client codec empty")`。
2. **查找 `CLIENT_CHECKER`**:找到 codec 后,继续调用 `get_client_parser(protocol)` 设置分包器。数据库调用由第三方 SDK 自行管理连接与协议解析,不需要框架做 TCP 切帧,因此无需注册同名 checker(`set_parser(None)` 不会影响自定义 `round_trip`)。
3. **查找 `CLIENT_TRANSPORT`**:调用 `get_client_transport(protocol)`。若存在同名实例,则用它替换 `_create_client_options` 默认设置的 `trpc` transport。

Expand Down Expand Up @@ -98,15 +98,15 @@ client:

## 4. 业务侧调用

业务代码通过 `Client().invoke()` 发起调用时,有三个细节需要注意:
业务代码通过 `TrpcClient().invoke()` 发起调用时,有三个细节需要注意:

1. **先在 `message` 上设置被调服务名**:`get_options` 会先用调用时刻 `msg.callee_service_name` 的值去匹配 YAML 配置(`load_client_config`),随后才执行本次传入的 `Options` 覆盖项。因此必须在 `invoke` 之前调用 `msg.set_callee_service_name("trpc.app.server.store")`。如果只在 `Options().set_service_name(...)` 中设置名字,加载 YAML 的阶段已经结束,配置里的 `protocol` 和 `target` 将无法生效。
2. **使用 `SerializationType.Noop` 与空字节请求体**:`NoopSerializer.serialize` 仅接受 `bytes` 或 `Body` 实例,不能直接把自定义的 `StoreCommand` 当作请求体 `req` 传入。正确做法是请求体传 `b""`、响应类型传 `Body`,并将 `command` 放到 `Options().set_req_head(command)` 中(`update_message` 会将其复制到 `msg.client_req_head`)。
2. **使用 `SerializationType.NOOP` 与空字节请求体**:`NoopSerializer.serialize` 仅接受 `bytes` 或 `Body` 实例,不能直接把自定义的 `StoreCommand` 当作请求体 `req` 传入。正确做法是请求体传 `b""`、响应类型传 `Body`,并将 `command` 放到 `Options().set_req_head(command)` 中(`update_message` 会将其复制到 `msg.client_req_head`)。
3. **确保插件模块已被导入**:服务启动时必须先 `import` 定义了 `StoreCodec` 和 `StoreTransport` 的模块,触发 `@register_plugin` 完成注册。

```python
from trpc_sdk.abc import clone_client_message
from trpc_sdk.client import Client
from trpc_sdk.client import TrpcClient
from trpc_sdk.client import Options
from trpc_sdk.serialization import Body
from trpc_sdk.serialization import SerializationType
Expand All @@ -122,14 +122,14 @@ async def execute(ctx, statement: str):
ctx, _ = clone_client_message(ctx)
ctx.get_message().set_callee_service_name("trpc.app.server.store")
command = StoreCommand(statement)
await Client().invoke(
await TrpcClient().invoke(
ctx,
b"",
Body,
[
Options()
.set_req_head(command)
.set_serialization_type(SerializationType.Noop),
.set_serialization_type(SerializationType.NOOP),
],
)
return command.result
Expand Down
10 changes: 5 additions & 5 deletions docs/developer_guide/develop_plugins/naming.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,18 +97,18 @@ The four roles in the chain use these default plugins:
Change the default sub-plugins for every client in the process from code:

```python
from trpc_sdk.naming import set_default_circuitbreaker
from trpc_sdk.naming import set_default_circuit_breaker
from trpc_sdk.naming import set_default_discovery
from trpc_sdk.naming import set_default_loadbalance
from trpc_sdk.naming import set_default_servicerouter
from trpc_sdk.naming import set_default_service_router

set_default_discovery("static_discovery")
set_default_loadbalance("RandomLB")
set_default_circuitbreaker("NoopCB")
set_default_servicerouter("NoopSR")
set_default_circuit_breaker("NoopCB")
set_default_service_router("NoopSR")
```

A single client service can override `discovery`, `loadbalance`, and `circuitbreaker` in YAML. Client YAML has no `servicerouter` field. Set the service router with `set_default_servicerouter`, or with `Options.set_service_router` on the call:
A single client service can override `discovery`, `loadbalance`, and `circuitbreaker` in YAML. Client YAML has no `servicerouter` field. Set the service router with `set_default_service_router`, or with `Options.set_service_router` on the call:

```yaml
client:
Expand Down
10 changes: 5 additions & 5 deletions docs/developer_guide/develop_plugins/naming.zh_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,18 +93,18 @@ client:
你可以通过代码修改进程内所有客户端的默认子插件:

```python
from trpc_sdk.naming import set_default_circuitbreaker
from trpc_sdk.naming import set_default_circuit_breaker
from trpc_sdk.naming import set_default_discovery
from trpc_sdk.naming import set_default_loadbalance
from trpc_sdk.naming import set_default_servicerouter
from trpc_sdk.naming import set_default_service_router

set_default_discovery("static_discovery")
set_default_loadbalance("RandomLB")
set_default_circuitbreaker("NoopCB")
set_default_servicerouter("NoopSR")
set_default_circuit_breaker("NoopCB")
set_default_service_router("NoopSR")
```

也可以在 YAML 中针对单个客户端服务覆盖 `discovery`、`loadbalance` 和 `circuitbreaker`(注:YAML 客户端配置中没有 `servicerouter` 字段,服务路由需通过 `set_default_servicerouter` 或在调用时使用 `Options.set_service_router` 指定):
也可以在 YAML 中针对单个客户端服务覆盖 `discovery`、`loadbalance` 和 `circuitbreaker`(注:YAML 客户端配置中没有 `servicerouter` 字段,服务路由需通过 `set_default_service_router` 或在调用时使用 `Options.set_service_router` 指定):

```yaml
client:
Expand Down
Loading
Loading