diff --git a/.gitignore b/.gitignore index 5b68e51..afbe9a9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ .DS_Store .idea .vscode +.venv .ccls .ccls-cache diff --git a/docs/developer_guide/develop_plugins/config.md b/docs/developer_guide/develop_plugins/config.md index 3195997..83b25a6 100644 --- a/docs/developer_guide/develop_plugins/config.md +++ b/docs/developer_guide/develop_plugins/config.md @@ -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. @@ -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 @@ -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", {}) ``` diff --git a/docs/developer_guide/develop_plugins/config.zh_CN.md b/docs/developer_guide/develop_plugins/config.zh_CN.md index c0483e7..b47ac5f 100644 --- a/docs/developer_guide/develop_plugins/config.zh_CN.md +++ b/docs/developer_guide/develop_plugins/config.zh_CN.md @@ -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` 不能和它一起用。 @@ -57,7 +51,7 @@ class MyDecoder(BaseConfigDecoder): self._options = options ``` -使用时写成 `with_codec("my_decoder")`。 +使用时写成 `ConfigLoaderFactory.sync_load(decoder="my_decoder")`。 ## 数据源 @@ -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", {}) ``` diff --git a/docs/developer_guide/develop_plugins/database.md b/docs/developer_guide/develop_plugins/database.md index 6b8d2b0..9696360 100644 --- a/docs/developer_guide/develop_plugins/database.md +++ b/docs/developer_guide/develop_plugins/database.md @@ -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. @@ -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`. @@ -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 @@ -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 diff --git a/docs/developer_guide/develop_plugins/database.zh_CN.md b/docs/developer_guide/develop_plugins/database.zh_CN.md index 626721d..f627912 100644 --- a/docs/developer_guide/develop_plugins/database.zh_CN.md +++ b/docs/developer_guide/develop_plugins/database.zh_CN.md @@ -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 完成读写,并将结果写回命令对象。 @@ -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。 @@ -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 @@ -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 diff --git a/docs/developer_guide/develop_plugins/naming.md b/docs/developer_guide/develop_plugins/naming.md index 4684b5e..e3d86dc 100644 --- a/docs/developer_guide/develop_plugins/naming.md +++ b/docs/developer_guide/develop_plugins/naming.md @@ -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: diff --git a/docs/developer_guide/develop_plugins/naming.zh_CN.md b/docs/developer_guide/develop_plugins/naming.zh_CN.md index e760d8a..8c78c77 100644 --- a/docs/developer_guide/develop_plugins/naming.zh_CN.md +++ b/docs/developer_guide/develop_plugins/naming.zh_CN.md @@ -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: diff --git a/docs/developer_guide/develop_plugins/protocol.md b/docs/developer_guide/develop_plugins/protocol.md index 52fbd0f..8d0959b 100644 --- a/docs/developer_guide/develop_plugins/protocol.md +++ b/docs/developer_guide/develop_plugins/protocol.md @@ -100,9 +100,9 @@ def setup_line_checker() -> LineCheckerFactory: On the client receive path, bytes first pass the cell labeled **Framer**, which is `BaseClientProtocolParser`, then `decode_data` and deserialization. -Unlike the server, a client checker subclasses `BaseClientProtocolParser` (itself a `BasePlugin`) and is registered directly as a class, so the registry holds one instance. Implement `async def read_frame(self, connection) -> bytes`. The client TCP transport `await`s that method to read one complete response frame from a pooled connection (`PooledConnection`). +Unlike the server, a client checker subclasses `BaseClientProtocolParser` (itself a `BasePlugin`) and is registered directly as a class, so the registry holds one instance. Implement `async def read_frame(self, connection) -> bytes`. The client TCP transport `await`s that method to read one complete response frame from a pooled connection (`Connection`). -`PooledConnection.read(n)` asynchronously reads exactly `n` bytes. The snippet below reads 1 byte at a time until `b"\n"`, to show the idea. When the connection closes or the read fails, the exception is turned into `ClientDecodeError`: +`Connection.read(n)` asynchronously reads exactly `n` bytes. The snippet below reads 1 byte at a time until `b"\n"`, to show the idea. When the connection closes or the read fails, the exception is turned into `ClientDecodeError`: ```python from trpc_sdk.abc import BaseClientProtocolParser @@ -151,7 +151,7 @@ The `line` frame is simple: Server `decode_data` also sets two fields on `message`: 1. **The routed method name (`server_rpc_name`)**. `Service.handle` looks up the registered RPC handler with `message.get_server_rpc_name()`. The name looks like `/service/method`. If the service was registered with `fix_rpc_name=True`, the `service` span is replaced by the service `name` from YAML. A `line` frame carries no method name, so the example below fixes it as `"/trpc.app.server.Greeter/SayHello"`. A real protocol can put the method name in the frame header and parse it in `decode_data`. -2. **The serialization type (`serialization_type`)**. A new `message` defaults to serialization type `0`, which is protobuf. To send and receive raw bytes without protobuf, call `message.set_serialization_type(SerializationType.Noop)` in `decode_data`. +2. **The serialization type (`serialization_type`)**. A new `message` defaults to serialization type `0`, which is protobuf. To send and receive raw bytes without protobuf, call `message.set_serialization_type(SerializationType.NOOP)` in `decode_data`. ```python from typing import Optional @@ -174,7 +174,7 @@ class LineServerCodec(BaseCodec): async def decode_data(self, context: TrpcContext, buffer: Optional[bytes]) -> bytes: message = get_message(context) message.set_server_rpc_name("/trpc.app.server.Greeter/SayHello") - message.set_serialization_type(SerializationType.Noop) + message.set_serialization_type(SerializationType.NOOP) return (buffer or b"").rstrip(b"\n") @@ -191,20 +191,20 @@ class LineClientCodec(BaseCodec): > A few more notes: > -> - **How the HTTP codec works**: The built-in `ServerHttpCodec` does not assemble a TCP frame. It takes the `aiohttp` request and response from `message`. `decode_data` reads the body from the request and ignores `buffer`. `encode_data` writes the status code and response headers onto the response and returns the body. +> - **How the HTTP codec works**: The built-in `HttpServerCodec` does not assemble a TCP frame. It takes the `aiohttp` request and response from `message`. `decode_data` reads the body from the request and ignores `buffer`. `encode_data` writes the status code and response headers onto the response and returns the body. > - **Streaming codecs**: `encode_stream` / `decode_stream` on `BaseCodec` are for the tRPC streaming protocol. An ordinary unary protocol does not implement them. ## 4. Serialization and Compression (Optional) Serialization and compression are two plugin slots independent of the protocol: -- **Serialization (`PluginType.SERIALIZATION`)**: Subclass `BaseSerializer` and implement `serialize` and `deserialize`. The registered name is the integer value of `SerializationType` (`PB = 0`, `JCE = 1`, `JSON = 2`, `FlatBuffer = 3`, `Noop = 4`). -- **Compression (`PluginType.COMPRESS`)**: Subclass `BaseCompress` and implement `compress` and `decompress`. The registered name is the integer value of `CompressType`. The default, no compression, is `CompressType.Noop = 0`. +- **Serialization (`PluginType.SERIALIZATION`)**: Subclass `BaseSerializer` and implement `serialize` and `deserialize`. The registered name is the integer value of `SerializationType` (`PB = 0`, `JSON = 2`, `FLATBUFFER = 3`, `NOOP = 4`). +- **Compression (`PluginType.COMPRESS`)**: Subclass `BaseCompress` and implement `compress` and `decompress`. The registered name is the integer value of `CompressType`. The default, no compression, is `CompressType.NOOP = 0`. -The `line` example has no serialization-type field in the header, so both sides agree on `SerializationType.Noop` (value `4`) and exchange raw bytes: +The `line` example has no serialization-type field in the header, so both sides agree on `SerializationType.NOOP` (value `4`) and exchange raw bytes: -- **Server**: `LineServerCodec.decode_data` above already sets `SerializationType.Noop`. The `Noop` deserializer writes the raw bytes into the `data` attribute of a `trpc_sdk.serialization.Body`. -- **Client**: Set `serialization: 4` in YAML, or call `Options().set_serialization_type(SerializationType.Noop)` on the call. +- **Server**: `LineServerCodec.decode_data` above already sets `SerializationType.NOOP`. The `NOOP` deserializer writes the raw bytes into the `data` attribute of a `trpc_sdk.serialization.Body`. +- **Client**: Set `serialization: 4` in YAML, or call `Options().set_serialization_type(SerializationType.NOOP)` on the call. ## 5. A Custom Transport or a Custom Listener (Optional) @@ -231,7 +231,7 @@ server: ### Client -Besides `protocol: line`, the client needs a target address `target` (`ip://` is a naming-service selector; see [Naming Plugin](naming.md)) and `serialization: 4` (`SerializationType.Noop`): +Besides `protocol: line`, the client needs a target address `target` (`ip://` is a naming-service selector; see [Naming Plugin](naming.md)) and `serialization: 4` (`SerializationType.NOOP`): ```yaml client: diff --git a/docs/developer_guide/develop_plugins/protocol.zh_CN.md b/docs/developer_guide/develop_plugins/protocol.zh_CN.md index d2e0c0d..9d8fd25 100644 --- a/docs/developer_guide/develop_plugins/protocol.zh_CN.md +++ b/docs/developer_guide/develop_plugins/protocol.zh_CN.md @@ -97,9 +97,9 @@ def setup_line_checker() -> LineCheckerFactory: 客户端的接收方向先经过图中标为 **Framer** 的 `BaseClientProtocolParser`,再进入 `decode_data` 和反序列化。 -与服务端不同,客户端切帧器继承 `BaseClientProtocolParser`(本身即为 `BasePlugin` 子类),直接将类注册为单例即可。它需要实现异步方法 `async def read_frame(self, connection) -> bytes`,客户端 TCP 传输层会直接 `await` 该方法从连接池连接(`PooledConnection`)中读取一帧完整响应。 +与服务端不同,客户端切帧器继承 `BaseClientProtocolParser`(本身即为 `BasePlugin` 子类),直接将类注册为单例即可。它需要实现异步方法 `async def read_frame(self, connection) -> bytes`,客户端 TCP 传输层会直接 `await` 该方法从连接池连接(`Connection`)中读取一帧完整响应。 -`PooledConnection.read(n)` 每次会异步读满 `n` 个字节。下面为演示原理,每次读取 1 个字节直到遇到 `b"\n"`(当连接关闭或读取异常时,捕获并统一转换为 `ClientDecodeError`): +`Connection.read(n)` 每次会异步读满 `n` 个字节。下面为演示原理,每次读取 1 个字节直到遇到 `b"\n"`(当连接关闭或读取异常时,捕获并统一转换为 `ClientDecodeError`): ```python from trpc_sdk.abc import BaseClientProtocolParser @@ -145,7 +145,7 @@ class LineClientParser(BaseClientProtocolParser): 在服务端 `decode_data` 中,还需要设置两个关键的 `message` 属性: 1. **设置路由方法名(`server_rpc_name`)**:`Service.handle` 依赖 `message.get_server_rpc_name()` 查找已注册的 RPC 处理函数(格式形如 `/service/method`;若注册服务时指定了 `fix_rpc_name=True`,其中 `service` 段会被替换为 YAML 中的服务 `name`)。由于简单的 `line` 帧里没有携带方法名字段,我们在下面的示例中将其固定设为 `"/trpc.app.server.Greeter/SayHello"`(实际协议可将方法名编入帧头并在 `decode_data` 中解析出来)。 -2. **设置序列化类型(`serialization_type`)**:新建 `message` 的默认序列化类型是 `0`(即 Protobuf)。如果业务希望直接收发原始字节而不走 Protobuf 解析,需要在 `decode_data` 中调用 `message.set_serialization_type(SerializationType.Noop)`。 +2. **设置序列化类型(`serialization_type`)**:新建 `message` 的默认序列化类型是 `0`(即 Protobuf)。如果业务希望直接收发原始字节而不走 Protobuf 解析,需要在 `decode_data` 中调用 `message.set_serialization_type(SerializationType.NOOP)`。 完整代码如下: @@ -170,7 +170,7 @@ class LineServerCodec(BaseCodec): async def decode_data(self, context: TrpcContext, buffer: Optional[bytes]) -> bytes: message = get_message(context) message.set_server_rpc_name("/trpc.app.server.Greeter/SayHello") - message.set_serialization_type(SerializationType.Noop) + message.set_serialization_type(SerializationType.NOOP) return (buffer or b"").rstrip(b"\n") @@ -186,18 +186,18 @@ class LineClientCodec(BaseCodec): ``` > 补充说明: -> - **HTTP Codec 的工作方式**:内置的 `ServerHttpCodec` 不负责拼接 TCP 帧,而是从 `message` 上获取 `aiohttp` 的 request 和 response 对象——在 `decode_data` 中从 request 读取 body(忽略 `buffer` 参数),在 `encode_data` 中将状态码和响应头写入 response 并返回 body。 +> - **HTTP Codec 的工作方式**:内置的 `HttpServerCodec` 不负责拼接 TCP 帧,而是从 `message` 上获取 `aiohttp` 的 request 和 response 对象——在 `decode_data` 中从 request 读取 body(忽略 `buffer` 参数),在 `encode_data` 中将状态码和响应头写入 response 并返回 body。 > - **流式编解码**:`BaseCodec` 上的 `encode_stream` / `decode_stream` 专供 tRPC 流式协议使用,普通一元协议无需实现。 ## 4. 序列化与压缩插件(可选) 序列化与压缩是独立于协议之外的两个插件槽位: -- **序列化(`PluginType.SERIALIZATION`)**:继承 `BaseSerializer`,实现 `serialize` 和 `deserialize`。其注册名使用的是 `SerializationType` 枚举的整型值(`PB = 0`、`JCE = 1`、`JSON = 2`、`FlatBuffer = 3`、`Noop = 4`)。 -- **压缩(`PluginType.COMPRESS`)**:继承 `BaseCompress`,实现 `compress` 和 `decompress`。其注册名使用的是 `CompressType` 枚举的整型值(默认不压缩为 `CompressType.Noop = 0`)。 +- **序列化(`PluginType.SERIALIZATION`)**:继承 `BaseSerializer`,实现 `serialize` 和 `deserialize`。其注册名使用的是 `SerializationType` 枚举的整型值(`PB = 0`、`JSON = 2`、`FLATBUFFER = 3`、`NOOP = 4`)。 +- **压缩(`PluginType.COMPRESS`)**:继承 `BaseCompress`,实现 `compress` 和 `decompress`。其注册名使用的是 `CompressType` 枚举的整型值(默认不压缩为 `CompressType.NOOP = 0`)。 -在本文的 `line` 协议示例中,报文头不包含序列化类型字段,因此双方约定使用 `SerializationType.Noop`(值为 `4`)直接收发原始字节: -- **服务端**:已在上面 `LineServerCodec.decode_data` 中设置为 `SerializationType.Noop`。`Noop` 反序列化器会将原始字节写入 `trpc_sdk.serialization.Body` 对象的 `data` 属性中。 -- **客户端**:在 YAML 中配置 `serialization: 4`,或在调用时通过 `Options().set_serialization_type(SerializationType.Noop)` 指定。 +在本文的 `line` 协议示例中,报文头不包含序列化类型字段,因此双方约定使用 `SerializationType.NOOP`(值为 `4`)直接收发原始字节: +- **服务端**:已在上面 `LineServerCodec.decode_data` 中设置为 `SerializationType.NOOP`。`NOOP` 反序列化器会将原始字节写入 `trpc_sdk.serialization.Body` 对象的 `data` 属性中。 +- **客户端**:在 YAML 中配置 `serialization: 4`,或在调用时通过 `Options().set_serialization_type(SerializationType.NOOP)` 指定。 ## 5. 自定义传输层与自定义监听(可选) @@ -226,7 +226,7 @@ server: ### 客户端配置 -客户端除了指定 `protocol: line` 外,还需配置目标地址 `target`(其中 `ip://` 为名字服务 Selector,详见 [名字服务插件](naming.zh_CN.md))以及 `serialization: 4`(即 `SerializationType.Noop`): +客户端除了指定 `protocol: line` 外,还需配置目标地址 `target`(其中 `ip://` 为名字服务 Selector,详见 [名字服务插件](naming.zh_CN.md))以及 `serialization: 4`(即 `SerializationType.NOOP`): ```yaml client: diff --git a/docs/user_guide/client/connection_mode.md b/docs/user_guide/client/connection_mode.md index fc6505d..5d84c82 100644 --- a/docs/user_guide/client/connection_mode.md +++ b/docs/user_guide/client/connection_mode.md @@ -13,9 +13,9 @@ Keep the following transport behavior in mind: By default the client keeps downstream connections in a pool. Each event loop has its own pool manager and stores connections by downstream address. A request holds the connection exclusively while it runs. When the request finishes, the connection returns to the idle queue for a later request. -Pool parameters live on `ConnPoolOptions`. Set them in YAML or with `Options.set_pool_opts`. The fields correspond as follows: +Pool parameters live on `KeepLiveConnPoolOptions`. Set them in YAML or with `Options.set_pool_opts`. The fields correspond as follows: -| YAML field | `ConnPoolOptions` parameter | Default | Meaning | +| YAML field | `KeepLiveConnPoolOptions` parameter | Default | Meaning | | --- | --- | --- | --- | | `dial_timeout` | `dial_timeout` | `200` | Dial timeout, in milliseconds | | `idle_time` | `idle_timeout` | `60` | How long an idle connection stays in the pool, in seconds. `0` means idle time does not reclaim it | @@ -28,13 +28,13 @@ Set pool parameters in code: ```python from trpc_sdk.client import Options -from trpc_sdk.transport import ConnPoolOptions +from trpc_sdk.transport import KeepLiveConnPoolOptions options = ( Options() .set_target("ip://127.0.0.1:8000") .set_protocol("trpc") - .set_pool_opts(ConnPoolOptions(max_idle=8, idle_timeout=30, max_active=32, wait=True)) + .set_pool_opts(KeepLiveConnPoolOptions(max_idle=8, idle_timeout=30, max_active=32, wait=True)) ) ``` @@ -57,7 +57,7 @@ client: ## 2. Short-Connection Mode -When `short_conn` is `True`, that request uses `ShortConnFactory`: a new TCP connection is opened before the request, closed as soon as the response arrives, and not returned to the idle queue. This fits an infrequent one-shot call, or a downstream service that cannot handle several requests in a row on one connection. +When `short_conn` is `True`, that request uses `ShortConnPool`: a new TCP connection is opened before the request, closed as soon as the response arrives, and not returned to the idle queue. This fits an infrequent one-shot call, or a downstream service that cannot handle several requests in a row on one connection. Turn on short connections in code (this overrides YAML): diff --git a/docs/user_guide/client/connection_mode.zh_CN.md b/docs/user_guide/client/connection_mode.zh_CN.md index 26a0a09..e4ec267 100644 --- a/docs/user_guide/client/connection_mode.zh_CN.md +++ b/docs/user_guide/client/connection_mode.zh_CN.md @@ -10,9 +10,9 @@ 默认情况下,客户端通过连接池管理下游连接。每个事件循环(Event Loop)维护独立的连接池管理器,并按目标下游地址存取连接:请求执行期间独占该连接,请求完成后将其归还至空闲队列供后续请求复用。 -连接池参数封装在 `ConnPoolOptions` 中,可通过 YAML 配置文件或代码中的 `Options.set_pool_opts` 设置(两者的字段对应关系如下): +连接池参数封装在 `KeepLiveConnPoolOptions` 中,可通过 YAML 配置文件或代码中的 `Options.set_pool_opts` 设置(两者的字段对应关系如下): -| YAML 配置字段 | `ConnPoolOptions` 参数名 | 默认值 | 含义说明 | +| YAML 配置字段 | `KeepLiveConnPoolOptions` 参数名 | 默认值 | 含义说明 | | --- | --- | --- | --- | | `dial_timeout` | `dial_timeout` | `200` | 建立连接的超时时间(毫秒) | | `idle_time` | `idle_timeout` | `60` | 空闲连接在池中的最大保留时间(秒);`0` 表示不按空闲时间回收 | @@ -25,13 +25,13 @@ ```python from trpc_sdk.client import Options -from trpc_sdk.transport import ConnPoolOptions +from trpc_sdk.transport import KeepLiveConnPoolOptions options = ( Options() .set_target("ip://127.0.0.1:8000") .set_protocol("trpc") - .set_pool_opts(ConnPoolOptions(max_idle=8, idle_timeout=30, max_active=32, wait=True)) + .set_pool_opts(KeepLiveConnPoolOptions(max_idle=8, idle_timeout=30, max_active=32, wait=True)) ) ``` @@ -54,7 +54,7 @@ client: ## 2. 短连接模式 -当 `short_conn` 设为 `True` 时,该次请求会使用 `ShortConnFactory`:每次请求前新建一条 TCP 连接,收到响应后立即关闭连接,不会将其放入空闲队列。适用于低频单次调用,或下游服务不支持在单条连接上连续处理多个请求的场景。 +当 `short_conn` 设为 `True` 时,该次请求会使用 `ShortConnPool`:每次请求前新建一条 TCP 连接,收到响应后立即关闭连接,不会将其放入空闲队列。适用于低频单次调用,或下游服务不支持在单条连接上连续处理多个请求的场景。 通过代码开启短连接(优先级高于 YAML): diff --git a/docs/user_guide/client/http.md b/docs/user_guide/client/http.md index b4cc9c4..5c64a3c 100644 --- a/docs/user_guide/client/http.md +++ b/docs/user_guide/client/http.md @@ -13,11 +13,11 @@ If you already have a protobuf stub and only want the transport protocol to be H ```python from trpc_sdk.abc import TrpcContext from trpc_sdk.client import Options -from trpc_sdk.http import Client +from trpc_sdk.http import HttpClient async def post_json() -> None: """POST a body and read the response as text.""" - cli = Client() + cli = HttpClient() ctx = TrpcContext() options = [Options().set_timeout(3000)] async with cli.post(ctx, "http://127.0.0.1:8001/test", options, data=b"hello") as rsp: @@ -39,7 +39,7 @@ The URL must include a scheme and a host, for example `"http://127.0.0.1:8001/te ## How the URL Is Parsed and Matched -On each request, `Client` first builds a base `Options` from the URL, then appends the caller's `options` list and applies that list in order. A `set_*` in the caller's list therefore overrides the value derived from the URL. For this client the protocol is fixed as `"http"`, and the serialization type is fixed as `SerializationType.Noop`. The body is sent as raw bytes. +On each request, `Client` first builds a base `Options` from the URL, then appends the caller's `options` list and applies that list in order. A `set_*` in the caller's list therefore overrides the value derived from the URL. For this client the protocol is fixed as `"http"`, and the serialization type is fixed as `SerializationType.NOOP`. The body is sent as raw bytes. ### 1. Scheme and Addressing @@ -53,10 +53,10 @@ async with cli.get(ctx, "trpc://trpc.test.helloworld.Greeter/SayHello") as rsp: ### 2. Matching a YAML Client Entry -The `name` passed to `Client(name)` is the lookup key in `client.service[]` of `trpc_python.yaml`. When it is omitted or `""`, the key is the URL's `host:port`: +The `name` passed to `HttpClient(name)` is the lookup key in `client.service[]` of `trpc_python.yaml`. When it is omitted or `""`, the key is the URL's `host:port`: ```python -cli = Client("example.http") +cli = HttpClient("example.http") ``` The matching configuration: @@ -69,7 +69,7 @@ client: protocol: http ``` -With `Client("example.http")`, a URL of `"http://127.0.0.1:8001/..."` still loads the YAML entry named `"example.http"`. The `target` is still `scheme://host` from the URL itself. +With `HttpClient("example.http")`, a URL of `"http://127.0.0.1:8001/..."` still loads the YAML entry named `"example.http"`. The `target` is still `scheme://host` from the URL itself. ## Reading the Response diff --git a/docs/user_guide/client/http.zh_CN.md b/docs/user_guide/client/http.zh_CN.md index f9644c5..c716c38 100644 --- a/docs/user_guide/client/http.zh_CN.md +++ b/docs/user_guide/client/http.zh_CN.md @@ -11,11 +11,11 @@ ```python from trpc_sdk.abc import TrpcContext from trpc_sdk.client import Options -from trpc_sdk.http import Client +from trpc_sdk.http import HttpClient async def post_json() -> None: """POST a body and read the response as text.""" - cli = Client() + cli = HttpClient() ctx = TrpcContext() options = [Options().set_timeout(3000)] async with cli.post(ctx, "http://127.0.0.1:8001/test", options, data=b"hello") as rsp: @@ -37,7 +37,7 @@ async with cli.request(ctx, "PUT", "http://127.0.0.1:8001/item", data=b"{}") as ## URL 解析与配置匹配规则 -发起请求时,`Client` 会先根据传入的 URL 自动生成一组基础 `Options`,随后将调用方传入的 `options` 列表追加在后面依次执行(因此调用方在 `options` 中设置的 `set_*` 项会覆盖从 URL 推导出的默认值)。在 HTTP 客户端中,协议固定设为 `"http"`,序列化类型固定为 `SerializationType.Noop`(请求体按原始字节发送)。 +发起请求时,`Client` 会先根据传入的 URL 自动生成一组基础 `Options`,随后将调用方传入的 `options` 列表追加在后面依次执行(因此调用方在 `options` 中设置的 `set_*` 项会覆盖从 URL 推导出的默认值)。在 HTTP 客户端中,协议固定设为 `"http"`,序列化类型固定为 `SerializationType.NOOP`(请求体按原始字节发送)。 ### 1. URL Scheme 与寻址推导 @@ -53,10 +53,10 @@ async with cli.get(ctx, "trpc://trpc.test.helloworld.Greeter/SayHello") as rsp: ### 2. 匹配 YAML 中的客户端配置 -构造 `Client(name)` 时传入的 `name` 参数用于作为查找键,去 `trpc_python.yaml` 的 `client.service[]` 中匹配配置(若不传或传入空字符串 `""`,则默认使用 URL 中的 `host:port` 作为查找键): +构造 `HttpClient(name)` 时传入的 `name` 参数用于作为查找键,去 `trpc_python.yaml` 的 `client.service[]` 中匹配配置(若不传或传入空字符串 `""`,则默认使用 URL 中的 `host:port` 作为查找键): ```python -cli = Client("example.http") +cli = HttpClient("example.http") ``` 对应的 YAML 配置示例: @@ -69,7 +69,7 @@ client: protocol: http ``` -当显式指定了 `Client("example.http")` 时,即使请求 URL 写为 `"http://127.0.0.1:8001/..."`,框架依然会按 `"example.http"` 查找并加载上述 YAML 配置,而目标地址 `target` 仍由 URL 自身的 `scheme://host` 决定。 +当显式指定了 `HttpClient("example.http")` 时,即使请求 URL 写为 `"http://127.0.0.1:8001/..."`,框架依然会按 `"example.http"` 查找并加载上述 YAML 配置,而目标地址 `target` 仍由 URL 自身的 `scheme://host` 决定。 ## 读取响应内容 diff --git a/docs/user_guide/client/overview.md b/docs/user_guide/client/overview.md index fa2d4f4..a9b0764 100644 --- a/docs/user_guide/client/overview.md +++ b/docs/user_guide/client/overview.md @@ -4,13 +4,13 @@ English | [中文](overview.zh_CN.md) An outbound RPC call in tRPC-Python is assembled as `Options` and then executed by `Client.invoke`. A protobuf stub (proxy) is only a thin wrapper over that path. The proxy itself does not keep network connections. -The public client API is in `trpc_sdk.client` (`Client`, `get_client`, and `Options`). The call context is `trpc_sdk.abc.TrpcContext`. +The public client API is in `trpc_sdk.client` (`TrpcClient`, `get_client`, and `Options`). The call context is `trpc_sdk.abc.TrpcContext`. ## How Call Options Are Merged On each call, `get_options` builds the final `Options` in this order. A later step overwrites the same field from an earlier step: -1. **Framework defaults.** The selector is `TrpcSelector`, serialization is `SerializationType.PB`, and compression is `CompressType.Noop`. +1. **Framework defaults.** The selector is `TrpcSelector`, serialization is `SerializationType.PB`, and compression is `CompressType.NOOP`. 2. **YAML.** The callee service name on the `TrpcMessage` selects the matching entry under `client` in `trpc_python.yaml`. 3. **Caller `Options`.** The `Options` passed in code for this call are applied last. @@ -139,7 +139,7 @@ A `set_*` in code overrides YAML, and YAML overrides the framework defaults. The | `set_protocol(protocol)` | Protocol name. Looks up and binds the `codec`, `checker`, and `transport` | | `set_network(network)` | Transport network: `tcp` or `udp` | | `set_serialization_type(t)` | Serialization type. Default `SerializationType.PB` | -| `set_compress_type(t)` | Compression type. Default `CompressType.Noop` | +| `set_compress_type(t)` | Compression type. Default `CompressType.NOOP` | | `set_timeout(ms)` | Timeout of this client call, in milliseconds | | `set_namespace(ns)` | Namespace of the callee service | | `set_metadata(key, val)` | Add one cross-process key-value pair. `val` must be `bytes` | @@ -221,26 +221,26 @@ options = Options().set_metadata("key", b"value") ## 11. Serialization, Compression, and Raw Bytes (Noop) -The defaults are `SerializationType.PB` and `CompressType.Noop`. Other common serializations are `SerializationType.JSON` and `SerializationType.Noop`. Compression types are in `trpc_sdk.compressor.CompressType`, for example `Gzip`. YAML `serialization` and `compression` are the integer enum values. `0` is PB and no compression, respectively. +The defaults are `SerializationType.PB` and `CompressType.NOOP`. Other common serializations are `SerializationType.JSON` and `SerializationType.NOOP`. Compression types are in `trpc_sdk.compressor.CompressType`, for example `Gzip`. YAML `serialization` and `compression` are the integer enum values. `0` is PB and no compression, respectively. ### Passing Through Already-Serialized Bytes In a proxy or forwarding path, the request body may already be serialized `bytes` (for example an encoded protobuf payload). This process should not serialize it again, but the frame header should still tell the peer to parse the body as protobuf. Use `trpc_sdk.serialization.Body` together with `set_current_serialization_type`: - `set_serialization_type(SerializationType.PB)` is written on the frame header. It tells the peer that the body format is PB. -- `set_current_serialization_type(SerializationType.Noop)` only decides that **this process** uses `NoopSerializer` to read and write raw bytes. It does not change the serialization type announced on the frame header. +- `set_current_serialization_type(SerializationType.NOOP)` only decides that **this process** uses `NoopSerializer` to read and write raw bytes. It does not change the serialization type announced on the frame header. ```python from trpc_sdk.abc import TrpcContext from trpc_sdk.abc import create_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 ctx = TrpcContext() create_message(ctx) -rsp = await Client().invoke( +rsp = await TrpcClient().invoke( ctx, Body(data=raw_bytes), Body, @@ -249,7 +249,7 @@ rsp = await Client().invoke( .set_target("ip://127.0.0.1:8000") .set_protocol("trpc") .set_serialization_type(SerializationType.PB) - .set_current_serialization_type(SerializationType.Noop), + .set_current_serialization_type(SerializationType.NOOP), ], ) payload = rsp.data diff --git a/docs/user_guide/client/overview.zh_CN.md b/docs/user_guide/client/overview.zh_CN.md index 22d9ed2..9da1143 100644 --- a/docs/user_guide/client/overview.zh_CN.md +++ b/docs/user_guide/client/overview.zh_CN.md @@ -1,14 +1,14 @@ # tRPC-Python 客户端开发向导 -在 tRPC-Python 中,发起一次出站 RPC 调用的核心流程是:先组装调用选项 `Options`,再交由 `Client.invoke` 执行。Protobuf 生成的桩代码(Proxy)只是对这一流程的轻量封装,其自身并不维护网络连接。 +在 tRPC-Python 中,发起一次出站 RPC 调用的核心流程是:先组装调用选项 `Options`,再交由 `TrpcClient.invoke` 执行。Protobuf 生成的桩代码(Proxy)只是对这一流程的轻量封装,其自身并不维护网络连接。 -客户端核心公开接口位于 `trpc_sdk.client` 模块(包括 `Client`、`get_client`、`Options`),调用上下文使用 `trpc_sdk.abc.TrpcContext`。 +客户端核心公开接口位于 `trpc_sdk.client` 模块(包括 `TrpcClient`、`get_client`、`Options`),调用上下文使用 `trpc_sdk.abc.TrpcContext`。 ## 调用选项合并与执行顺序 每次调用时,`get_options` 会严格按以下优先级顺序组装最终的 `Options`(后执行的覆盖先执行的同名字段): -1. **框架默认值**:路由选点器(Selector)默认为 `TrpcSelector`,序列化类型默认为 `SerializationType.PB`(Protobuf),压缩类型默认为 `CompressType.Noop`(不压缩)。 +1. **框架默认值**:路由选点器(Selector)默认为 `TrpcSelector`,序列化类型默认为 `SerializationType.PB`(Protobuf),压缩类型默认为 `CompressType.NOOP`(不压缩)。 2. **YAML 配置文件**:根据 `TrpcMessage` 上的被调服务名,匹配并应用 `trpc_python.yaml` 中 `client` 段的配置。 3. **调用方传入的 `Options`**:最后应用本次调用时通过代码传入的 `Options` 参数。 @@ -88,8 +88,8 @@ async def say_hello() -> pb.HelloReply: ## 3. 使用生成的桩代码(Proxy) Protobuf 生成的 `GreeterClientProxyImpl` 会在调用前自动将完整 RPC 路径、被调服务名(Callee)和方法名写入 `TrpcMessage`,然后调用 `get_client()` 发送请求: -- **异步调用**:`await proxy.asyncSayHello(ctx, req, options)`(底层调用 `Client.invoke`)。 -- **同步调用**:`proxy.SayHello(ctx, req, options)`(底层调用 `Client.invoke_sync`)。 +- **异步调用**:`await proxy.asyncSayHello(ctx, req, options)`(底层调用 `TrpcClient.invoke`)。 +- **同步调用**:`proxy.SayHello(ctx, req, options)`(底层调用 `TrpcClient.invoke_sync`)。 关于 Proxy 的使用细节: - **自定义服务名(`service_name`)**:构造 `GreeterClientProxyImpl(service_name=...)` 时,默认使用 `.proto` 文件中定义的服务名,并以此作为查找 YAML 配置的键。若传入了自定义服务名,则 YAML 查找键和请求中的 RPC 路径都会替换为该名称;若同时传入 `fix_rpc_name=False`,则仅替换 YAML 查找键,发出的 RPC 路径仍保持 `.proto` 中的原始定义。 @@ -104,10 +104,10 @@ options = [ reply = proxy.SayHello(ctx, req, options) ``` -- **轻量实例化**:Proxy 实例非常轻量,可在每次调用时按需创建。`get_client()` 返回的 `Client` 是进程内单例,底层的连接池维护在 `transport` 层而非 Proxy 实例上。 +- **轻量实例化**:Proxy 实例非常轻量,可在每次调用时按需创建。`get_client()` 返回的 `TrpcClient` 是进程内单例,底层的连接池维护在 `transport` 层而非 Proxy 实例上。 - **切换为泛 HTTP RPC**:使用同一套桩代码,只需设置 `Options().set_protocol("http")`,即可改用 HTTP 协议承载该 RPC 调用(若不通过桩代码、直接按 URL 发送标准 HTTP 请求,请参考 [HTTP 客户端使用指南](http.zh_CN.md))。 -## 4. 不使用桩代码直接调用(`Client.invoke`) +## 4. 不使用桩代码直接调用(`TrpcClient.invoke`) 如果不使用生成的桩代码,直接调用 `get_client().invoke(...)`,则需要调用方自行在 `TrpcMessage` 上设置被调服务名、RPC 路径和方法名,并传入响应类型 `rsp_cls`(框架会调用 `rsp_cls()` 构造空实例并反序列化填充): @@ -137,7 +137,7 @@ reply = await get_client().invoke(ctx, req, pb.HelloReply, options) | `set_protocol(protocol)` | 设置协议名称,用于查找并绑定对应的 `codec`、`checker` 和 `transport` | | `set_network(network)` | 设置传输层网络类型:`tcp` 或 `udp` | | `set_serialization_type(t)` | 设置序列化类型,默认为 `SerializationType.PB` | -| `set_compress_type(t)` | 设置压缩类型,默认为 `CompressType.Noop` | +| `set_compress_type(t)` | 设置压缩类型,默认为 `CompressType.NOOP` | | `set_timeout(ms)` | 设置本次客户端调用的超时时间(毫秒) | | `set_namespace(ns)` | 设置被调服务所在的命名空间 | | `set_metadata(key, val)` | 添加一条跨进程透传的键值对(`val` 必须为 `bytes`) | @@ -206,8 +206,8 @@ options = Options().set_target("ip://127.0.0.1:8000").set_protocol("trpc").set_f ## 9. 同步与异步调用方式 -- **异步调用(推荐)**:`await proxy.asyncSayHello(...)` 和 `await Client.invoke(...)` 均为协程函数,直接在当前运行的事件循环中 `await` 即可。 -- **同步调用**:`proxy.SayHello(...)` 和 `Client.invoke_sync(...)` 会在当前线程阻塞运行直至调用完成。如果当前线程尚未创建事件循环,框架会自动新建一个并绑定到当前线程;**注意:如果当前线程的事件循环已经处于运行状态(例如在 `async def` 协程内部),请勿调用同步入口,否则会导致事件循环冲突报错。** +- **异步调用(推荐)**:`await proxy.asyncSayHello(...)` 和 `await TrpcClient.invoke(...)` 均为协程函数,直接在当前运行的事件循环中 `await` 即可。 +- **同步调用**:`proxy.SayHello(...)` 和 `TrpcClient.invoke_sync(...)` 会在当前线程阻塞运行直至调用完成。如果当前线程尚未创建事件循环,框架会自动新建一个并绑定到当前线程;**注意:如果当前线程的事件循环已经处于运行状态(例如在 `async def` 协程内部),请勿调用同步入口,否则会导致事件循环冲突报错。** ## 10. 超时与链路透传 @@ -220,26 +220,26 @@ options = Options().set_metadata("key", b"value") ## 11. 序列化、压缩与二进制透传(Noop) -框架默认使用 `SerializationType.PB`(Protobuf 序列化)与 `CompressType.Noop`(不压缩)。常用序列化类型还包括 `SerializationType.JSON` 和 `SerializationType.Noop`;压缩类型定义在 `trpc_sdk.compressor.CompressType`(如 `Gzip`)。YAML 配置中的 `serialization` 和 `compression` 填写对应的整数枚举值(`0` 分别代表 PB 和不压缩)。 +框架默认使用 `SerializationType.PB`(Protobuf 序列化)与 `CompressType.NOOP`(不压缩)。常用序列化类型还包括 `SerializationType.JSON` 和 `SerializationType.NOOP`;压缩类型定义在 `trpc_sdk.compressor.CompressType`(如 `Gzip`)。YAML 配置中的 `serialization` 和 `compression` 填写对应的整数枚举值(`0` 分别代表 PB 和不压缩)。 ### 已序列化字节流直通(转发场景) 在某些代理或转发场景下,业务手头的请求体已经是序列化好的 `bytes`(例如已经是编码后的 Protobuf 字节),不希望当前进程再次执行序列化,但仍需在协议帧头中告知对端按 Protobuf 解析。此时可配合使用 `trpc_sdk.serialization.Body` 与 `set_current_serialization_type`: - `set_serialization_type(SerializationType.PB)`:写入协议帧头,告知对端该包体的实际数据格式为 PB。 -- `set_current_serialization_type(SerializationType.Noop)`:仅控制**当前进程**使用 `NoopSerializer` 直接读写原始字节,不修改协议帧头中声明的序列化类型。 +- `set_current_serialization_type(SerializationType.NOOP)`:仅控制**当前进程**使用 `NoopSerializer` 直接读写原始字节,不修改协议帧头中声明的序列化类型。 ```python from trpc_sdk.abc import TrpcContext from trpc_sdk.abc import create_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 ctx = TrpcContext() create_message(ctx) -rsp = await Client().invoke( +rsp = await TrpcClient().invoke( ctx, Body(data=raw_bytes), Body, @@ -248,7 +248,7 @@ rsp = await Client().invoke( .set_target("ip://127.0.0.1:8000") .set_protocol("trpc") .set_serialization_type(SerializationType.PB) - .set_current_serialization_type(SerializationType.Noop), + .set_current_serialization_type(SerializationType.NOOP), ], ) payload = rsp.data diff --git a/docs/user_guide/server/overview.md b/docs/user_guide/server/overview.md index 88dd817..68d1d35 100644 --- a/docs/user_guide/server/overview.md +++ b/docs/user_guide/server/overview.md @@ -279,4 +279,3 @@ When each callback runs: - `after_in_parent`: in the parent, **after** `fork`. - `after_in_child`: in each child, immediately after that child is forked. - `register_child_callback(func, process_type)`: immediately after `after_in_child`, filtered by child role. `ProcessType.WORKER` runs only in a business worker child. `ProcessType.TASK` runs only in a task child. -- `register_before_loop_run_in_child(func)`: after the child has finished plugin initialization, and before it enters `loop.run_forever()`. diff --git a/docs/user_guide/server/overview.zh_CN.md b/docs/user_guide/server/overview.zh_CN.md index 6e9e01f..a94d5bf 100644 --- a/docs/user_guide/server/overview.zh_CN.md +++ b/docs/user_guide/server/overview.zh_CN.md @@ -271,4 +271,3 @@ register_child_callback(after_worker, ProcessType.WORKER) - `after_in_parent`:父进程完成 `fork` **之后**在父进程内触发。 - `after_in_child`:每个子进程被 `fork` 出来后立即在子进程内触发。 - `register_child_callback(func, process_type)`:紧接在 `after_in_child` 之后触发,但支持按子进程角色过滤——指定 `ProcessType.WORKER` 时仅在业务 Worker 子进程中执行,指定 `ProcessType.TASK` 时仅在 Task 任务子进程中执行。 -- `register_before_loop_run_in_child(func)`:在子进程完成所有插件初始化之后、正式进入事件循环 `loop.run_forever()` 之前触发。 diff --git a/examples/hellostream/stub/trpc_py_stream_helloworld/rpc.py b/examples/hellostream/stub/trpc_py_stream_helloworld/rpc.py index 264277d..3ca6347 100644 --- a/examples/hellostream/stub/trpc_py_stream_helloworld/rpc.py +++ b/examples/hellostream/stub/trpc_py_stream_helloworld/rpc.py @@ -17,10 +17,10 @@ from trpc_sdk import codec from trpc_sdk import server from trpc_sdk.abc import TrpcContext -from trpc_sdk.stream import ClientStreamDesc +from trpc_sdk.abc import ClientStreamDesc from trpc_sdk.stream import ServerStream from trpc_sdk.stream import create_stream_dispatcher -from trpc_sdk.stream import default_stream_client +from trpc_sdk.stream import get_default_client_stream_factory from trpc_sdk.utils import get_or_create_event_loop from . import rpc_stream @@ -252,7 +252,7 @@ class GreeterClientProxyImpl(GreeterClientProxy): def __init__(self, service_name: str = None, fix_rpc_name: bool = True): self.client = client.get_client() self.options = {} - self.stream_client = default_stream_client + self.stream_factory = get_default_client_stream_factory() self.service_name = service_name self.fix_rpc_name = fix_rpc_name @@ -316,9 +316,9 @@ def SayHelloReq(self, options = options or [] ctx, _ = self._clone_client_message(ctx, '/trpc.py_stream.helloworld.Greeter/SayHelloReq', 'SayHelloReqStream') - desc = ClientStreamDesc('/trpc.py_stream.helloworld.Greeter/SayHelloReq', True) + desc = ClientStreamDesc(name='/trpc.py_stream.helloworld.Greeter/SayHelloReq') loop = get_or_create_event_loop() - task = loop.create_task(self.stream_client.create_client_stream(ctx, desc, desc.stream_name, options)) + task = loop.create_task(self.stream_factory.create_client_stream(ctx, desc, options)) loop.run_until_complete(task) rsp = rpc_stream.GreeterClientStream.SayHelloReq(task.result()) @@ -336,8 +336,8 @@ async def asyncSayHelloReq(self, options = options or [] ctx, _ = self._clone_client_message(ctx, '/trpc.py_stream.helloworld.Greeter/SayHelloReq', 'SayHelloReqStream') - desc = ClientStreamDesc('/trpc.py_stream.helloworld.Greeter/SayHelloReq', True) - stream = await self.stream_client.create_client_stream(ctx, desc, desc.stream_name, options) + desc = ClientStreamDesc(name='/trpc.py_stream.helloworld.Greeter/SayHelloReq') + stream = await self.stream_factory.create_client_stream(ctx, desc, options) rsp = rpc_stream.GreeterClientStream.SayHelloReq(stream) return rsp @@ -355,8 +355,8 @@ def SayHelloRsp(self, options = options or [] ctx, _ = self._clone_client_message(ctx, '/trpc.py_stream.helloworld.Greeter/SayHelloRsp', 'SayHelloRspStream') - desc = ClientStreamDesc('/trpc.py_stream.helloworld.Greeter/SayHelloRsp', True) - stream = self.stream_client.create_client_stream(ctx, desc, desc.stream_name, options) + desc = ClientStreamDesc(name='/trpc.py_stream.helloworld.Greeter/SayHelloRsp') + stream = self.stream_factory.create_client_stream(ctx, desc, options) rsp = rpc_stream.GreeterClientStream.SayHelloRsp(stream) loop = get_or_create_event_loop() @@ -377,8 +377,8 @@ async def asyncSayHelloRsp(self, options = options or [] ctx, _ = self._clone_client_message(ctx, '/trpc.py_stream.helloworld.Greeter/SayHelloRsp', 'SayHelloRspStream') - desc = ClientStreamDesc('/trpc.py_stream.helloworld.Greeter/SayHelloRsp', True) - stream = await self.stream_client.create_client_stream(ctx, desc, desc.stream_name, options) + desc = ClientStreamDesc(name='/trpc.py_stream.helloworld.Greeter/SayHelloRsp') + stream = await self.stream_factory.create_client_stream(ctx, desc, options) rsp = rpc_stream.GreeterClientStream.SayHelloRsp(stream) await rsp.client_stream.send_msg(request) @@ -396,9 +396,9 @@ def SayHelloAll(self, options = options or [] ctx, _ = self._clone_client_message(ctx, '/trpc.py_stream.helloworld.Greeter/SayHelloAll', 'SayHelloAllStream') - desc = ClientStreamDesc('/trpc.py_stream.helloworld.Greeter/SayHelloAll', True) + desc = ClientStreamDesc(name='/trpc.py_stream.helloworld.Greeter/SayHelloAll') loop = get_or_create_event_loop() - task = loop.create_task(self.stream_client.create_client_stream(ctx, desc, desc.stream_name, options)) + task = loop.create_task(self.stream_factory.create_client_stream(ctx, desc, options)) loop.run_until_complete(task) rsp = rpc_stream.GreeterClientStream.SayHelloAll(task.result()) @@ -416,8 +416,8 @@ async def asyncSayHelloAll(self, options = options or [] ctx, _ = self._clone_client_message(ctx, '/trpc.py_stream.helloworld.Greeter/SayHelloAll', 'SayHelloAllStream') - desc = ClientStreamDesc('/trpc.py_stream.helloworld.Greeter/SayHelloAll', True) - stream = await self.stream_client.create_client_stream(ctx, desc, desc.stream_name, options) + desc = ClientStreamDesc(name='/trpc.py_stream.helloworld.Greeter/SayHelloAll') + stream = await self.stream_factory.create_client_stream(ctx, desc, options) rsp = rpc_stream.GreeterClientStream.SayHelloAll(stream) return rsp diff --git a/examples/helloworld/features/http/_client.py b/examples/helloworld/features/http/_client.py index bb815a0..14cf661 100644 --- a/examples/helloworld/features/http/_client.py +++ b/examples/helloworld/features/http/_client.py @@ -9,7 +9,7 @@ import asyncio from trpc_sdk.abc import TrpcContext from trpc_sdk.serialization import SerializationType -from trpc_sdk.http import Client as HttpClient +from trpc_sdk.http import HttpClient from trpc_sdk.http import get_http_header_in_client from trpc_sdk.http import get_http_status_in_client diff --git a/examples/helloworld/features/peer/_check.py b/examples/helloworld/features/peer/_check.py index 3b7fac0..459642f 100644 --- a/examples/helloworld/features/peer/_check.py +++ b/examples/helloworld/features/peer/_check.py @@ -52,15 +52,15 @@ from trpc_sdk.abc import TrpcContext # noqa: E402 from trpc_sdk.abc import get_message # noqa: E402 +from trpc_sdk.abc import ClientStreamDesc # noqa: E402 from trpc_sdk.client import Options # noqa: E402 from trpc_sdk.config import TrpcConfig # noqa: E402 from trpc_sdk.config import default_worker_num # noqa: E402 from trpc_sdk.plugin import init_plugins # noqa: E402 from trpc_sdk.serialization import SerializationType # noqa: E402 -from trpc_sdk.stream import ClientStreamDesc # noqa: E402 -from trpc_sdk.stream import default_stream_client # noqa: E402 +from trpc_sdk.stream import get_default_client_stream_factory # noqa: E402 from trpc_sdk.transport import get_default_client_transport # noqa: E402 -from trpc_sdk.transport import ClientConn # noqa: E402 +from trpc_sdk.transport import ClientStreamConn # noqa: E402 from features.peer._servicer import HTTP_PATH # noqa: E402 from features.peer._servicer import STREAM_METHOD # noqa: E402 @@ -826,7 +826,7 @@ async def _open_two_streams(port: int, service: str) -> List[Tuple[int, int]]: async def _start_stream(ctx, options) -> None: stream_id = get_message(ctx).stream_id - transport.stream_id_to_conn[stream_id] = ClientConn(shared.conn(stream_id), options) + transport.stream_id_to_conn[stream_id] = ClientStreamConn(shared.conn(stream_id), options) transport.start_stream = _start_stream try: @@ -839,8 +839,9 @@ async def _start_stream(ctx, options) -> None: msg.set_serialization_type(SerializationType.PB) options = (Options().set_target(f"ip://127.0.0.1:{port}").set_network("tcp").set_protocol("trpc"). set_serialization_type(SerializationType.PB).set_namespace("Development").set_timeout(8000)) - desc = ClientStreamDesc(method, False) - stream = await default_stream_client.create_client_stream(ctx, desc, method, [options]) + desc = ClientStreamDesc(name=method) + stream_factory = get_default_client_stream_factory() + stream = await stream_factory.create_client_stream(ctx, desc, [options]) reply = pb.HelloReply() await stream.recv_msg(reply) match = _STREAM_RE.search(reply.msg) diff --git a/examples/helloworld/features/separate/_check.py b/examples/helloworld/features/separate/_check.py index 900a69d..28a6d2a 100644 --- a/examples/helloworld/features/separate/_check.py +++ b/examples/helloworld/features/separate/_check.py @@ -53,14 +53,14 @@ from trpc_sdk.abc import TrpcContext # noqa: E402 from trpc_sdk.abc import get_message # noqa: E402 +from trpc_sdk.abc import ClientStreamDesc # noqa: E402 from trpc_sdk.client import Options # noqa: E402 from trpc_sdk.config import TrpcConfig # noqa: E402 from trpc_sdk.plugin import init_plugins # noqa: E402 from trpc_sdk.serialization import SerializationType # noqa: E402 -from trpc_sdk.stream import ClientStreamDesc # noqa: E402 -from trpc_sdk.stream import default_stream_client # noqa: E402 +from trpc_sdk.stream import get_default_client_stream_factory # noqa: E402 from trpc_sdk.transport import get_default_client_transport # noqa: E402 -from trpc_sdk.transport import ClientConn # noqa: E402 +from trpc_sdk.transport import ClientStreamConn # noqa: E402 from features.separate._servicer import HTTP_PATH # noqa: E402 from features.separate._servicer import STREAM_METHOD # noqa: E402 @@ -794,7 +794,7 @@ async def _open_two_streams(port: int, service: str) -> List[Tuple[int, int]]: async def _start_stream(ctx, options) -> None: stream_id = get_message(ctx).stream_id - transport.stream_id_to_conn[stream_id] = ClientConn(shared.conn(stream_id), options) + transport.stream_id_to_conn[stream_id] = ClientStreamConn(shared.conn(stream_id), options) transport.start_stream = _start_stream try: @@ -807,8 +807,9 @@ async def _start_stream(ctx, options) -> None: msg.set_serialization_type(SerializationType.PB) options = (Options().set_target(f"ip://127.0.0.1:{port}").set_network("tcp").set_protocol("trpc"). set_serialization_type(SerializationType.PB).set_namespace("Development").set_timeout(8000)) - desc = ClientStreamDesc(method, False) - stream = await default_stream_client.create_client_stream(ctx, desc, method, [options]) + desc = ClientStreamDesc(name=method) + stream_factory = get_default_client_stream_factory() + stream = await stream_factory.create_client_stream(ctx, desc, [options]) reply = pb.HelloReply() await stream.recv_msg(reply) match = _STREAM_RE.search(reply.msg) diff --git a/examples/http/client/_client.py b/examples/http/client/_client.py index 388cf89..7b16bc4 100644 --- a/examples/http/client/_client.py +++ b/examples/http/client/_client.py @@ -11,7 +11,7 @@ import asyncio from trpc_sdk.abc import TrpcContext from trpc_sdk.serialization import SerializationType -from trpc_sdk.http import Client as HttpClient +from trpc_sdk.http import HttpClient from trpc_sdk.http import get_http_header_in_client from trpc_sdk.http import get_http_status_in_client diff --git a/format.sh b/format.sh index 2a6bfa9..c9a2d29 100644 --- a/format.sh +++ b/format.sh @@ -6,13 +6,13 @@ pip3 install yapf # 查找并格式化 Python 文件 -# find . -name "*.py" -not -path "./venv/*" \ -# -not -name "helloworld_pb2.py" \ -# -exec yapf -i {} \; +find trpc_sdk/ -name "*.py" -not -path "./.venv/*" \ + -not -path "trpc_sdk/_inner/pb/*" \ + -exec yapf -i {} \; # find ./examples/helloworld/ -type f -name "*.py" -not -path "*/__pycache__/*" -not -name "helloworld_pb2.py" -exec yapf -i {} \; # find ./examples/hellostream/ -type f -name "*.py" -not -path "*/__pycache__/*" -not -name "helloworld_pb2.py" -exec yapf -i {} \; -find trpc_sdk/ -type f -name "*.py" -not -path "*/__pycache__/*" -not -name "*_pb2.py" -exec yapf -i {} \; +find trpc/ -type f -name "*.py" -not -path "*/__pycache__/*" -not -name "*_pb2.py" -exec yapf -i {} \; diff --git a/tests/abc/test_abc_task.py b/tests/abc/test_abc_task.py index 702717c..b85e6d4 100644 --- a/tests/abc/test_abc_task.py +++ b/tests/abc/test_abc_task.py @@ -24,13 +24,10 @@ def test_task(): assert not task.thread_num assert not task.model_path assert not task.model_info - assert task.use_c_task is False - assert not task.c_task_driver_params assert not task.on_fork assert not task.pause_heartbeat assert task.task_num == 0 task = TaskInfo(name="worker", handler=handler, task_num=1) - assert task.use_c_task is False assert task.task_num == 1 assert task.handler is handler diff --git a/tests/client/test_client.py b/tests/client/test_client.py index 1ac69eb..437c36b 100644 --- a/tests/client/test_client.py +++ b/tests/client/test_client.py @@ -105,7 +105,7 @@ async def test_send_request_compress_snappy(): pytest.importorskip("snappy") ctx, request = _hello_context() reply = await get_client().invoke( - ctx, request, helloworld_pb2.HelloReply, _invoke_options(CompressType.Snappy)) + ctx, request, helloworld_pb2.HelloReply, _invoke_options(CompressType.SNAPPY)) assert reply.msg == "hi: hello: " @@ -114,7 +114,7 @@ async def test_send_request_compress_gzip(): """Test compress gzip""" ctx, request = _hello_context() reply = await get_client().invoke( - ctx, request, helloworld_pb2.HelloReply, _invoke_options(CompressType.Gzip)) + ctx, request, helloworld_pb2.HelloReply, _invoke_options(CompressType.GZIP)) assert reply.msg == "hi: hello: " @@ -123,7 +123,7 @@ async def test_send_request_compress_zlib(): """Test compress zlib""" ctx, request = _hello_context() reply = await get_client().invoke( - ctx, request, helloworld_pb2.HelloReply, _invoke_options(CompressType.ZLib)) + ctx, request, helloworld_pb2.HelloReply, _invoke_options(CompressType.ZLIB)) assert reply.msg == "hi: hello: " diff --git a/tests/client/test_client_invoke_errors.py b/tests/client/test_client_invoke_errors.py index 9b2f6ad..0ebfff5 100644 --- a/tests/client/test_client_invoke_errors.py +++ b/tests/client/test_client_invoke_errors.py @@ -101,7 +101,7 @@ async def test_invoke_empty_codec_raises_encode_error(monkeypatch): opts = _prepare_invoke(monkeypatch, codec=None) with pytest.raises(ClientEncodeError, match="client codec empty"): - await client_mod.Client().invoke(_Context(), object(), SimpleNamespace, []) + await client_mod.TrpcClient().invoke(_Context(), object(), SimpleNamespace, []) opts.selector.report.assert_awaited_once() @@ -111,7 +111,7 @@ async def test_invoke_timeout_is_wrapped(monkeypatch): opts = _prepare_invoke(monkeypatch, asyncio.TimeoutError()) with pytest.raises(ClientTimeoutError, match="client request timeout") as raised: - await client_mod.Client().invoke(_Context(), object(), SimpleNamespace, []) + await client_mod.TrpcClient().invoke(_Context(), object(), SimpleNamespace, []) assert raised.value.timeout_type == ClientTimeoutReason.DOWNSTREAM_TIMEOUT opts.selector.report.assert_awaited_once() @@ -123,7 +123,7 @@ async def test_invoke_unknown_exception_is_reraised(monkeypatch): monkeypatch.setattr(client_mod.logger, "error", MagicMock()) with pytest.raises(ValueError, match="unexpected"): - await client_mod.Client().invoke(_Context(), object(), SimpleNamespace, []) + await client_mod.TrpcClient().invoke(_Context(), object(), SimpleNamespace, []) opts.selector.report.assert_awaited_once() @@ -131,7 +131,7 @@ async def test_invoke_unknown_exception_is_reraised(monkeypatch): def test_invoke_sync_creates_loop_when_thread_has_none(monkeypatch): created = [] original_new_event_loop = asyncio.new_event_loop - client = client_mod.Client() + client = client_mod.TrpcClient() def new_loop(): loop = original_new_event_loop() diff --git a/tests/client/test_client_options.py b/tests/client/test_client_options.py index 3a77330..15fb8db 100644 --- a/tests/client/test_client_options.py +++ b/tests/client/test_client_options.py @@ -19,7 +19,7 @@ from trpc_sdk.config import ClientServiceConfig from trpc_sdk.serialization import SerializationType from trpc_sdk.transport import ClientTransport -from trpc_sdk.transport import ConnPoolOptions +from trpc_sdk.transport import KeepLiveConnPoolOptions def test_options(): @@ -56,17 +56,14 @@ def test_options(): opts.set_timeout(1000) assert opts.timeout == 1000 - opts.set_current_serialization_type(SerializationType.JCE) - assert opts.current_serialization_type == SerializationType.JCE - opts.set_serialization_type(SerializationType.JSON) assert opts.serialization_type == SerializationType.JSON - opts.set_current_compress_type(CompressType.Snappy) - assert opts.current_compress_type == CompressType.Snappy + opts.set_current_compress_type(CompressType.SNAPPY) + assert opts.current_compress_type == CompressType.SNAPPY - opts.set_compress_type(CompressType.ZLib) - assert opts.compress_type == CompressType.ZLib + opts.set_compress_type(CompressType.ZLIB) + assert opts.compress_type == CompressType.ZLIB opts.set_transport(ClientTransport()) assert isinstance(opts.transport, ClientTransport) @@ -107,16 +104,16 @@ def test_options(): opts.set_callee_setname('test_callee_setname') assert opts.selector_options.dst_setname == 'test_callee_setname' - opts.set_caller_envname('test_caller_envname') + opts.set_caller_env_name('test_caller_envname') assert opts.selector_options.src_env_name == 'test_caller_envname' - opts.set_callee_envname('test_callee_envname') + opts.set_callee_env_name('test_callee_envname') assert opts.selector_options.dst_env_name == 'test_callee_envname' opts.set_max_window_size(65536) assert opts.max_window_size == 65536 - conn_pool_opts = ConnPoolOptions(dial_timeout=100) + conn_pool_opts = KeepLiveConnPoolOptions(dial_timeout=100) opts.set_pool_opts(conn_pool_opts) assert opts.call_options.pool_opts == conn_pool_opts assert opts.call_options.pool_opts.dial_timeout == 100 @@ -221,7 +218,7 @@ def test_load_client_config_discovery_and_connection_flags(monkeypatch): ("set_caller_namespace", "source-ns", lambda o: o.selector_options.src_namespace == "source-ns"), ("set_disable_service_router", True, lambda o: o.selector_options.disable_service_router is True), ("set_env_key", "env-key", lambda o: o.selector_options.env_key == "env-key"), - ("set_servicerouter_name", "router", lambda o: o.selector_options.service_router == "router"), + ("set_service_router_name", "router", lambda o: o.selector_options.service_router == "router"), ("set_key", "hash-key", lambda o: o.selector_options.key == "hash-key"), ("set_socket_type", "unix", lambda o: o.socket_type == "unix"), ("set_unix_path", "/tmp/service.sock", lambda o: o.unix_path == "/tmp/service.sock"), diff --git a/tests/client/test_client_transport.py b/tests/client/test_client_transport.py index 033ea81..8a220f3 100644 --- a/tests/client/test_client_transport.py +++ b/tests/client/test_client_transport.py @@ -16,7 +16,7 @@ from trpc_sdk.exceptions import ServerSystemError from trpc_sdk.transport import ClientTransport from trpc_sdk.transport import RoundTripOptions -from trpc_sdk.transport._client._client_transport_tcp import tcp_round_trip +from trpc_sdk.transport._client._tcp_round_trip import tcp_round_trip from trpc_sdk.utils import now_ms @@ -98,7 +98,7 @@ async def _refused(*_args, **_kwargs): raise ConnectionRefusedError(111, "Connection refused") monkeypatch.setattr( - "trpc_sdk.transport._client._client_transport_tcp.get_pool_connection", + "trpc_sdk.transport._client._tcp_round_trip.get_pool_connection", _refused, ) client_transport = ClientTransport() @@ -231,7 +231,7 @@ async def _get_conn(*_args, **_kwargs): return fake monkeypatch.setattr( - "trpc_sdk.transport._client._client_transport_tcp.get_pool_connection", + "trpc_sdk.transport._client._tcp_round_trip.get_pool_connection", _get_conn, ) options = RoundTripOptions() @@ -254,7 +254,7 @@ async def _open(*_args, **_kwargs): return udp monkeypatch.setattr( - "trpc_sdk.transport._client._client_transport_udp.open_datagram_endpoint", + "trpc_sdk.transport._client._udp_round_trip.open_datagram_endpoint", _open, ) options.set_network("udp") @@ -272,7 +272,7 @@ async def _get_conn(*_args, **_kwargs): return fake monkeypatch.setattr( - "trpc_sdk.transport._client._client_transport_tcp.get_pool_connection", + "trpc_sdk.transport._client._tcp_round_trip.get_pool_connection", _get_conn, ) ctx, msg = _context() diff --git a/tests/client/test_client_transport_stream.py b/tests/client/test_client_transport_stream.py index 71853d0..b4ec752 100644 --- a/tests/client/test_client_transport_stream.py +++ b/tests/client/test_client_transport_stream.py @@ -10,7 +10,7 @@ from trpc_sdk.codec import create_message from trpc_sdk.exceptions import ClientInvokeError from trpc_sdk.exceptions import ClientTimeoutError -from trpc_sdk.transport import ClientConn +from trpc_sdk.transport import ClientStreamConn from trpc_sdk.transport import ClientTransport from trpc_sdk.transport import RoundTripOptions @@ -82,7 +82,7 @@ async def test_recv_frame(): """Recv frame turns parser failures into client errors.""" timeout_options = RoundTripOptions() timeout_options.set_parser(_Parser(error=TimeoutError("slow"))) - client_conn = ClientConn(conn=_FakeConn(), options=timeout_options) + client_conn = ClientStreamConn(conn=_FakeConn(), options=timeout_options) ctx = TrpcContext() ctx.deadline = 0 with pytest.raises(ClientTimeoutError): @@ -90,7 +90,7 @@ async def test_recv_frame(): error_options = RoundTripOptions() error_options.set_parser(_Parser(error=RuntimeError("test err"))) - client_conn = ClientConn(conn=_FakeConn(), options=error_options) + client_conn = ClientStreamConn(conn=_FakeConn(), options=error_options) with pytest.raises(ClientInvokeError, match="test err"): await client_conn.recv_frame(ctx) @@ -100,6 +100,6 @@ def test_client_conn_close_marks_force(): fake = _FakeConn() options = RoundTripOptions() options.parser = _Parser() - client_conn = ClientConn(conn=fake, options=options) + client_conn = ClientStreamConn(conn=fake, options=options) client_conn.close(True) assert fake.closed is True diff --git a/tests/client/test_zclient.py b/tests/client/test_zclient.py index 1bd9afa..b0cca85 100644 --- a/tests/client/test_zclient.py +++ b/tests/client/test_zclient.py @@ -15,7 +15,7 @@ from examples.helloworld.stub.trpc_trpc_python_group_helloworld import helloworld_pb2 from tests.common_util import unused_port from trpc_sdk.abc import TrpcContext -from trpc_sdk.client import Client +from trpc_sdk.client import TrpcClient from trpc_sdk.client import Options from trpc_sdk.codec import create_message from trpc_sdk.config import ClientServiceConfig @@ -62,7 +62,7 @@ def test_client(self): req = helloworld_pb2.HelloRequest() req.msg = 'hello' rsp_cls = helloworld_pb2.HelloReply - cli = Client() + cli = TrpcClient() with pytest.raises(Exception, match="empty service_name"): cli.invoke_sync(ctx, req, rsp_cls, Options()) diff --git a/tests/codec/test_compress.py b/tests/codec/test_compress.py index b0f7a46..51c91a3 100644 --- a/tests/codec/test_compress.py +++ b/tests/codec/test_compress.py @@ -19,29 +19,30 @@ def test_class_attribute_access(): """Test accessing class attributes.""" - assert CompressType.Noop == 0 - assert CompressType.Gzip == 1 - assert CompressType.Snappy == 2 - assert CompressType.ZLib == 3 - assert CompressType.SnappyStream == 4 - assert CompressType.SnappyBlock == 5 - assert CompressType.Lz4Frame == 6 - assert CompressType.Lz4Block == 7 - assert CompressType.Zstd == 8 - - -def test_instance_attribute_access(): - """Test accessing instance attributes.""" - compress_type = CompressType() - assert compress_type.Noop == 0 - assert compress_type.Gzip == 1 - assert compress_type.Snappy == 2 - assert compress_type.ZLib == 3 - assert compress_type.SnappyStream == 4 - assert compress_type.SnappyBlock == 5 - assert compress_type.Lz4Frame == 6 - assert compress_type.Lz4Block == 7 - assert compress_type.Zstd == 8 + assert CompressType.NOOP == 0 + assert CompressType.GZIP == 1 + assert CompressType.SNAPPY == 2 + assert CompressType.ZLIB == 3 + assert CompressType.SNAPPY_STREAM == 4 + assert CompressType.SNAPPY_BLOCK == 5 + assert CompressType.LZ4_FRAME == 6 + assert CompressType.LZ4_BLOCK == 7 + assert CompressType.ZSTD == 8 + + +def test_lookup_by_wire_value(): + """Test resolving a decoded content_encoding back to its member.""" + assert CompressType(0) is CompressType.NOOP + assert CompressType(1) is CompressType.GZIP + assert CompressType(2) is CompressType.SNAPPY + assert CompressType(3) is CompressType.ZLIB + assert CompressType(4) is CompressType.SNAPPY_STREAM + assert CompressType(5) is CompressType.SNAPPY_BLOCK + assert CompressType(6) is CompressType.LZ4_FRAME + assert CompressType(7) is CompressType.LZ4_BLOCK + assert CompressType(8) is CompressType.ZSTD + with pytest.raises(ValueError): + CompressType(99) def test_attribute_not_found(): @@ -52,33 +53,33 @@ def test_attribute_not_found(): def test_get_compress(): """Test get_compress function.""" - compressor = get_compress(CompressType.Noop) + compressor = get_compress(CompressType.NOOP) assert isinstance(compressor, CompressNoop) - compressor = get_compress(CompressType.Gzip) + compressor = get_compress(CompressType.GZIP) assert isinstance(compressor, CompressGZip) - compressor = get_compress(CompressType.Snappy) + compressor = get_compress(CompressType.SNAPPY) assert isinstance(compressor, CompressSnappy) - compressor = get_compress(CompressType.SnappyStream) + compressor = get_compress(CompressType.SNAPPY_STREAM) assert isinstance(compressor, CompressStreamSnappy) - compressor = get_compress(CompressType.SnappyBlock) + compressor = get_compress(CompressType.SNAPPY_BLOCK) assert isinstance(compressor, CompressSnappy) - compressor = get_compress(CompressType.ZLib) + compressor = get_compress(CompressType.ZLIB) assert isinstance(compressor, CompressZlib) def test_compress(): """Test compress function.""" src = b'test_data' - compress_result = compress(CompressType.Gzip, src) - decompress_result = decompress(CompressType.Gzip, compress_result) + compress_result = compress(CompressType.GZIP, src) + decompress_result = decompress(CompressType.GZIP, compress_result) assert decompress_result == src - compress_result = compress(CompressType.Noop, src) - decompress_result = decompress(CompressType.Noop, compress_result) + compress_result = compress(CompressType.NOOP, src) + decompress_result = decompress(CompressType.NOOP, compress_result) assert decompress_result == src - compress_result = compress(CompressType.ZLib, src) - decompress_result = decompress(CompressType.ZLib, compress_result) + compress_result = compress(CompressType.ZLIB, src) + decompress_result = decompress(CompressType.ZLIB, compress_result) assert decompress_result == src @@ -86,16 +87,16 @@ def test_snappy_compress(): """Test snappy compress function when python-snappy is installed.""" pytest.importorskip("snappy") src = b'test_data' - compress_result = compress(CompressType.Snappy, src) - decompress_result = decompress(CompressType.Snappy, compress_result) + compress_result = compress(CompressType.SNAPPY, src) + decompress_result = decompress(CompressType.SNAPPY, compress_result) assert decompress_result == src - compress_result = compress(CompressType.SnappyStream, src) - decompress_result = decompress(CompressType.SnappyStream, compress_result) + compress_result = compress(CompressType.SNAPPY_STREAM, src) + decompress_result = decompress(CompressType.SNAPPY_STREAM, compress_result) assert decompress_result == src - compress_result = compress(CompressType.SnappyBlock, src) - decompress_result = decompress(CompressType.SnappyBlock, compress_result) + compress_result = compress(CompressType.SNAPPY_BLOCK, src) + decompress_result = decompress(CompressType.SNAPPY_BLOCK, compress_result) assert decompress_result == src @@ -104,7 +105,7 @@ def test_actual_compress_operations(): unsupport_compress = get_compress(99) assert unsupport_compress is None - noop_compress = get_compress(CompressType.Noop) + noop_compress = get_compress(CompressType.NOOP) assert noop_compress.compress(b'') == b'' assert noop_compress.decompress(b'') == b'' body = b"this is noop test data" @@ -112,7 +113,7 @@ def test_actual_compress_operations(): assert noop_compress.compress(body) == compress_body assert noop_compress.decompress(compress_body) == body - zlib_compress = get_compress(CompressType.ZLib) + zlib_compress = get_compress(CompressType.ZLIB) assert zlib_compress.compress(b'') == b'' assert zlib_compress.decompress(b'') == b'' body = b"this is zlib test data" @@ -120,7 +121,7 @@ def test_actual_compress_operations(): assert zlib_compress.compress(body) == compress_body assert zlib_compress.decompress(compress_body) == body - gzip_compress = get_compress(CompressType.Gzip) + gzip_compress = get_compress(CompressType.GZIP) assert gzip_compress.compress(b'') == b'' assert gzip_compress.decompress(b'') == b'' body = b"this is gzip test data" @@ -134,7 +135,7 @@ def test_actual_compress_operations(): def test_actual_snappy_operations(): """Test snappy byte layout when python-snappy is installed.""" pytest.importorskip("snappy") - snappy_compress = get_compress(CompressType.Snappy) + snappy_compress = get_compress(CompressType.SNAPPY) assert snappy_compress.compress(b'') == b'' assert snappy_compress.decompress(b'') == b'' body = b"this is snappy test data" diff --git a/tests/codec/test_message.py b/tests/codec/test_message.py index a0b6293..13b467d 100644 --- a/tests/codec/test_message.py +++ b/tests/codec/test_message.py @@ -35,8 +35,8 @@ def test_message(): assert 1000 == msg.timeout msg.set_serialization_type(SerializationType.PB) assert SerializationType.PB == msg.serialization_type - msg.set_compress_type(CompressType.Noop) - assert CompressType.Noop == msg.compress_type + msg.set_compress_type(CompressType.NOOP) + assert CompressType.NOOP == msg.compress_type msg.set_dyeing(True) assert True is msg.dyeing msg.set_dyeing_key("hellotrpc") diff --git a/tests/config/test_config.py b/tests/config/test_config.py index d0f43a2..dc23b5a 100644 --- a/tests/config/test_config.py +++ b/tests/config/test_config.py @@ -19,8 +19,6 @@ from trpc_sdk.config import TrpcConfig from trpc_sdk.config import TrpcConfigParser from trpc_sdk.config import YamlDecoder -from trpc_sdk.config import with_codec -from trpc_sdk.config import with_provider from trpc_sdk.http import register_http_session_params from trpc_sdk.http._client_transport import _http_session_params from trpc_sdk.plugin import get_plugin @@ -195,7 +193,7 @@ def test_load_global_config(): def test_load_config_from_file(): """Load an application YAML through the file provider and yaml decoder.""" file_path = './tests/test_config_data/trpc_python.yaml' - test_config = ConfigLoaderFactory.sync_load(file_path, with_provider('file'), with_codec('yaml')) + test_config = ConfigLoaderFactory.sync_load(file_path, provider='file', decoder='yaml') assert test_config.get('server', '').get('app') == 'test' diff --git a/tests/http/test_http_client.py b/tests/http/test_http_client.py index 793cfd2..0d3d69f 100644 --- a/tests/http/test_http_client.py +++ b/tests/http/test_http_client.py @@ -21,7 +21,7 @@ from trpc_sdk import exceptions from trpc_sdk.abc import TrpcContext from trpc_sdk.client import Options -from trpc_sdk.http import Client +from trpc_sdk.http import HttpClient from trpc_sdk.http import SSEClient from trpc_sdk.http import get_http_header_in_client from trpc_sdk.http import get_http_status_in_client @@ -205,7 +205,7 @@ async def _handler(request: web.Request) -> web.Response: async def test_http_client_post(): """Test http client post""" - cli = Client() + cli = HttpClient() ctx = TrpcContext() rsp = await cli.post(ctx, f"http://{_HOST}:{_port}/", data="text") body = await rsp.text() @@ -214,7 +214,7 @@ async def test_http_client_post(): async def test_http_client_post_json(): """Test http client post json""" - cli = Client() + cli = HttpClient() ctx = TrpcContext() rsp = await cli.post(ctx, f"http://{_HOST}:{_port}/json", json={"key": "value"}) body = await rsp.json() @@ -224,7 +224,7 @@ async def test_http_client_post_json(): async def test_http_client_post_json_context_manager(): """Test http client post json context manager""" - cli = Client() + cli = HttpClient() ctx = TrpcContext() async with cli.post(ctx, f"http://{_HOST}:{_port}/json", json={"key": "value"}) as rsp: body = await rsp.json() @@ -233,7 +233,7 @@ async def test_http_client_post_json_context_manager(): async def test_http_client_post_pb(): """Test http client post pb""" - cli = Client() + cli = HttpClient() ctx = TrpcContext() req = helloworld_pb2.HelloRequest() req.msg = "hello" @@ -247,7 +247,7 @@ async def test_http_client_post_pb(): async def test_http_client_post_pb_with_short_conn(): """Test http client post pb""" - cli = Client() + cli = HttpClient() ctx = TrpcContext() req = helloworld_pb2.HelloRequest() req.msg = "hello" @@ -268,7 +268,7 @@ async def test_http_client_post_pb_with_short_conn(): async def test_http_client_post_stream_pb(): """Test http client post pb""" - cli = Client() + cli = HttpClient() ctx = TrpcContext() req = helloworld_pb2.HelloRequest() req.msg = "hello" @@ -287,7 +287,7 @@ async def test_http_client_post_stream_pb(): async def test_http_client_post_stream_data(): """Test http client post pb""" - cli = Client() + cli = HttpClient() ctx = TrpcContext() req = helloworld_pb2.HelloRequest() req.msg = "hello" @@ -304,7 +304,7 @@ async def test_http_client_post_stream_data(): async def test_http_client_post_pb_timeout(): """Test http client post pb timeout""" - cli = Client() + cli = HttpClient() ctx = TrpcContext() req = helloworld_pb2.HelloRequest() req.msg = "hello" @@ -322,7 +322,7 @@ async def test_http_client_post_pb_timeout(): async def test_http_client_post_pb_timeout2(): """Test http client post timeout""" - cli = Client() + cli = HttpClient() ctx = TrpcContext() ctx.deadline = time.time() * 1000 - 100 @@ -343,7 +343,7 @@ async def test_http_client_post_pb_timeout2(): async def test_http_client_get(): """Test http client get""" - cli = Client() + cli = HttpClient() ctx = TrpcContext() rsp = await cli.get(ctx, f"http://{_HOST}:{_port}/img?id=123") body = await rsp.content.read(4) @@ -353,7 +353,7 @@ async def test_http_client_get(): async def test_http_client_stream_upload(): """Test http client get""" - cli = Client() + cli = HttpClient() ctx = TrpcContext() check_recv_data = [] @@ -394,7 +394,7 @@ async def test_trpc_http_client(): async def test_http_client_invalid_url(): """Test http client invalid url""" - cli = Client() + cli = HttpClient() ctx = TrpcContext() req = helloworld_pb2.HelloRequest() req.msg = "hello" @@ -412,7 +412,7 @@ async def test_http_client_invalid_url(): async def test_https_client_post(): """Test https client post""" - cli = Client() + cli = HttpClient() ctx = TrpcContext() cert = "./examples/helloworld/cert/domain_srv_localhost.crt" opts = [ @@ -433,7 +433,7 @@ async def test_https_client_post(): async def test_http_client_naming_service(): """Test http client naming""" - cli = Client() + cli = HttpClient() ctx = TrpcContext() req = helloworld_pb2.HelloRequest() req.msg = "hello" diff --git a/tests/http/test_http_codec.py b/tests/http/test_http_codec.py index 4cdc11d..e01186f 100644 --- a/tests/http/test_http_codec.py +++ b/tests/http/test_http_codec.py @@ -21,10 +21,10 @@ from trpc_sdk.exceptions import TrpcErrorType from trpc_sdk.exceptions import TrpcException from trpc_sdk.http import HTTP_TRPC_HEADER -from trpc_sdk.http import ClientHttpCodec +from trpc_sdk.http import HttpClientCodec from trpc_sdk.http import HttpClientReqHeader from trpc_sdk.http import HttpClientRspHeader -from trpc_sdk.http import ServerHttpCodec +from trpc_sdk.http import HttpServerCodec from trpc_sdk.http import set_http_ok_codes from trpc_sdk.serialization import SerializationType @@ -53,10 +53,10 @@ def _client_ctx_with_rsp(status: int, headers=None, body: bytes = b"") -> TrpcCo async def test_server_decode_get_uses_query_string(): ctx = _server_ctx("GET", "/trpc.app.server.Greeter/SayHello?a=1&b=2", headers={HTTP_TRPC_HEADER.trpc_request_id: "7"}) - body = await ServerHttpCodec().decode_data(ctx, b"") + body = await HttpServerCodec().decode_data(ctx, b"") msg = get_message(ctx) assert body == b"a=1&b=2" - assert msg.serialization_type == SerializationType.Form + assert msg.serialization_type == SerializationType.FORM assert msg.server_rpc_name == "/trpc.app.server.Greeter/SayHello" assert msg.callee_service_name == "trpc.app.server.Greeter" assert msg.server_req_head.request_id == 7 @@ -72,7 +72,7 @@ async def test_server_decode_post_reads_body_and_trans_info(): }, payload=b'{"msg": "hi"}', ) - body = await ServerHttpCodec().decode_data(ctx, b"") + body = await HttpServerCodec().decode_data(ctx, b"") msg = get_message(ctx) assert body == b'{"msg": "hi"}' assert msg.serialization_type == SerializationType.JSON @@ -84,7 +84,7 @@ def test_server_encode_sets_content_type_and_error_headers(): msg = get_message(ctx) msg.set_server_rsp_err(TrpcException(TrpcErrorType.BUSINESS, 1001, "biz failed")) - assert ServerHttpCodec().encode_data(ctx, b"payload") == b"payload" + assert HttpServerCodec().encode_data(ctx, b"payload") == b"payload" rsp = msg.server_raw_rsp assert rsp.headers[hdrs.CONTENT_TYPE] == "application/x-protobuf" @@ -95,13 +95,13 @@ def test_server_encode_sets_content_type_and_error_headers(): def test_client_encode_fills_method_and_caller(): ctx = TrpcContext() - assert ClientHttpCodec().encode_data(ctx, b"") == b"" + assert HttpClientCodec().encode_data(ctx, b"") == b"" msg = get_message(ctx) assert msg.client_req_head.method == hdrs.METH_GET assert msg.caller_service ctx = TrpcContext() - ClientHttpCodec().encode_data(ctx, b"body") + HttpClientCodec().encode_data(ctx, b"body") assert get_message(ctx).client_req_head.method == hdrs.METH_POST @@ -109,13 +109,13 @@ def test_client_encode_keeps_existing_head(): ctx = TrpcContext() msg = get_message(ctx) msg.set_client_req_head(HttpClientReqHeader(hdrs.METH_PUT)) - ClientHttpCodec().encode_data(ctx, b"body") + HttpClientCodec().encode_data(ctx, b"body") assert msg.client_req_head.method == hdrs.METH_PUT def test_client_decode_success_returns_body(): ctx = _client_ctx_with_rsp(200, body=b"ok") - assert ClientHttpCodec().decode_data(ctx, b"") == b"ok" + assert HttpClientCodec().decode_data(ctx, b"") == b"ok" assert get_message(ctx).client_rsp_err is None @@ -124,7 +124,7 @@ def test_client_decode_maps_error_headers(): HTTP_TRPC_HEADER.trpc_user_func_error_code: "42", HTTP_TRPC_HEADER.trpc_error_message: "bad", }) - ClientHttpCodec().decode_data(ctx, b"") + HttpClientCodec().decode_data(ctx, b"") err = get_message(ctx).client_rsp_err assert err.type == TrpcErrorType.BUSINESS assert err.code == 42 @@ -132,15 +132,15 @@ def test_client_decode_maps_error_headers(): def test_client_decode_status_codes(): ctx = _client_ctx_with_rsp(404) - ClientHttpCodec().decode_data(ctx, b"") + HttpClientCodec().decode_data(ctx, b"") assert isinstance(get_message(ctx).client_rsp_err, ClientInvokeError) ctx = _client_ctx_with_rsp(404) set_http_ok_codes(ctx, {404}) - ClientHttpCodec().decode_data(ctx, b"") + HttpClientCodec().decode_data(ctx, b"") assert get_message(ctx).client_rsp_err is None def test_client_decode_requires_rsp_head(): with pytest.raises(ClientInvokeError): - ClientHttpCodec().decode_data(TrpcContext(), b"") + HttpClientCodec().decode_data(TrpcContext(), b"") diff --git a/tests/http/test_http_server_worker.py b/tests/http/test_http_server_worker.py index b95e6fa..df08187 100644 --- a/tests/http/test_http_server_worker.py +++ b/tests/http/test_http_server_worker.py @@ -10,8 +10,8 @@ from trpc_sdk.abc import BaseServerTransportOption from trpc_sdk.http import HttpServerTransport -from trpc_sdk.http import RegisteredRoutes -from trpc_sdk.http import StaticFileRouters +from trpc_sdk.http import get_registered_routes +from trpc_sdk.http import get_static_file_routers from trpc_sdk.http import register_static from trpc_sdk.http import route from trpc_sdk.server import ServiceOption @@ -73,13 +73,13 @@ def test_https_without_cert(): def test_register_static(): """Test register static""" - saved = dict(StaticFileRouters) + saved = dict(get_static_file_routers()) try: register_static("/static", "static") - assert StaticFileRouters["/static"] == "static" + assert get_static_file_routers()["/static"] == "static" finally: - StaticFileRouters.clear() - StaticFileRouters.update(saved) + get_static_file_routers().clear() + get_static_file_routers().update(saved) async def _service_1(_, __) -> bytes: # return rsp @@ -96,10 +96,10 @@ async def _other_service(_, __) -> bytes: def test_many_service(): """User routes for this service, and only this service, land on the app.""" - saved_routes = dict(RegisteredRoutes) - saved_static = dict(StaticFileRouters) - RegisteredRoutes.clear() - StaticFileRouters.clear() + saved_routes = dict(get_registered_routes()) + saved_static = dict(get_static_file_routers()) + get_registered_routes().clear() + get_static_file_routers().clear() try: route("/test", service_name="trpc_sdk.test.many.service")(_service_1) route("/test1")(_service_2) @@ -123,7 +123,7 @@ def test_many_service(): assert "/other" not in paths assert any(isinstance(resource, web.StaticResource) for resource in web_app.router.resources()) finally: - RegisteredRoutes.clear() - RegisteredRoutes.update(saved_routes) - StaticFileRouters.clear() - StaticFileRouters.update(saved_static) + get_registered_routes().clear() + get_registered_routes().update(saved_routes) + get_static_file_routers().clear() + get_static_file_routers().update(saved_static) diff --git a/tests/inner/test_fork_hook.py b/tests/inner/test_fork_hook.py index 210f1b2..b32d5d8 100644 --- a/tests/inner/test_fork_hook.py +++ b/tests/inner/test_fork_hook.py @@ -12,11 +12,9 @@ from trpc_sdk.common import execute_after_in_child from trpc_sdk.common import execute_after_in_parent from trpc_sdk.common import execute_before_in_parent -from trpc_sdk.common import execute_before_loop_run_in_child from trpc_sdk.common import register_at_fork from trpc_sdk.common import register_child_callback from trpc_sdk.common import set_current_process_var -from trpc_sdk.common._process_hook import register_before_loop_run_in_child def _func(var: ProcessType = None): @@ -24,7 +22,6 @@ def _func(var: ProcessType = None): if var: set_current_process_var('type', var) execute_after_in_child() - execute_before_loop_run_in_child() def _create_child_process(var: ProcessType = None): @@ -62,7 +59,6 @@ def _before_loop_in_child(): test_val.value += 1 register_at_fork(before=_before, after_in_parent=_after, after_in_child=_after_in_child) - register_before_loop_run_in_child(_before_loop_in_child) print(f"master pid: {os.getpid()}") multiprocessing.set_start_method("fork", force=True) diff --git a/tests/pool/test_pool.py b/tests/pool/test_pool.py index a6fb43b..d1f3937 100644 --- a/tests/pool/test_pool.py +++ b/tests/pool/test_pool.py @@ -25,11 +25,11 @@ from trpc_sdk.config import SocketType from trpc_sdk.exceptions import ClientPoolClosedError from trpc_sdk.exceptions import ClientPoolLimitError -from trpc_sdk.transport import ConnPoolOptions -from trpc_sdk.transport import ConnectionPoolManager -from trpc_sdk.transport import PooledConnection +from trpc_sdk.transport import KeepLiveConnPoolOptions +from trpc_sdk.transport import KeepLiveConnPoolManager +from trpc_sdk.transport import Connection from trpc_sdk.transport import get_pool_connection -from trpc_sdk.transport._pool import ConnectionPool +from trpc_sdk.transport._client._pool import KeepLiveConnPool from trpc_sdk.utils import TcpState from trpc_sdk.utils import close_socket from trpc_sdk.utils import get_async_lib @@ -190,7 +190,7 @@ def stop(self): os.remove(self.addr[0]) -def _create_pool_options() -> Tuple[BaseClientTransportOption, ConnPoolOptions]: +def _create_pool_options() -> Tuple[BaseClientTransportOption, KeepLiveConnPoolOptions]: """Create default connection pool options for testing Returns: @@ -200,7 +200,7 @@ def _create_pool_options() -> Tuple[BaseClientTransportOption, ConnPoolOptions]: trans_opt.network = "tcp" trans_opt.socket_type = SocketType.UNIX trans_opt.address = ("./trpc_local", 0) - options = ConnPoolOptions(max_idle=2, max_active=10) + options = KeepLiveConnPoolOptions(max_idle=2, max_active=10) return trans_opt, options @@ -233,7 +233,7 @@ async def dial(self, options: BaseClientTransportOption, timeout: float, loop: a host, _port = options.address return await asyncio.open_unix_connection(host) - def new_pool(self, trans_opt: BaseClientTransportOption, options: ConnPoolOptions): + def new_pool(self, trans_opt: BaseClientTransportOption, options: KeepLiveConnPoolOptions): """Create new connection pool Args: @@ -243,7 +243,7 @@ def new_pool(self, trans_opt: BaseClientTransportOption, options: ConnPoolOption Returns: New connection pool instance """ - return ConnectionPool(self.dial, trans_opt=trans_opt, options=options) + return KeepLiveConnPool(self.dial, trans_opt=trans_opt, options=options) @pytest.mark.asyncio async def test_pool_get(self): @@ -325,7 +325,7 @@ async def dial(self, options: BaseClientTransportOption, timeout: float, loop: a assert writer.get_extra_info("socket") is not None return reader, writer - def new_pool(self, trans_opt: BaseClientTransportOption, options: ConnPoolOptions) -> ConnectionPool: + def new_pool(self, trans_opt: BaseClientTransportOption, options: KeepLiveConnPoolOptions) -> KeepLiveConnPool: """Create new connection pool Args: @@ -335,7 +335,7 @@ def new_pool(self, trans_opt: BaseClientTransportOption, options: ConnPoolOption Returns: New connection pool instance """ - return ConnectionPool(self.dial, trans_opt=trans_opt, options=options) + return KeepLiveConnPool(self.dial, trans_opt=trans_opt, options=options) @pytest.mark.asyncio async def test_pool_get(self): @@ -503,8 +503,8 @@ async def test_clean_timeout_idle_conn(self): def test_check_remote_error_close_wait(monkeypatch): """Test check_remote_error with socket in CLOSE_WAIT state""" - monkeypatch.setattr("trpc_sdk.transport._pool._pooled_connection.is_valid_socket", lambda _sock: True) - monkeypatch.setattr("trpc_sdk.transport._pool._pooled_connection.is_close_wait", lambda _sock: True) + monkeypatch.setattr("trpc_sdk.transport._client._pool._connection.is_valid_socket", lambda _sock: True) + monkeypatch.setattr("trpc_sdk.transport._client._pool._connection.is_close_wait", lambda _sock: True) reader = mock.MagicMock() writer = mock.MagicMock() sock = mock.MagicMock(spec=socket.socket) @@ -516,12 +516,12 @@ def test_check_remote_error_close_wait(monkeypatch): writer.is_closing.return_value = False reader.at_eof.return_value = False reader._buffer = b"" - pool_conn = PooledConnection(reader=reader, - writer=writer, - loop=mock.MagicMock(), - pool=mock.MagicMock(), - address=("127.0.0.1", 8080), - is_short=False) + pool_conn = Connection(reader=reader, + writer=writer, + loop=mock.MagicMock(), + pool=mock.MagicMock(), + address=("127.0.0.1", 8080), + is_short=False) result = pool_conn.check_remote_error() assert result is True @@ -570,7 +570,7 @@ async def test_dial_with_unix_socket(self): # Test dial with Unix socket loop = asyncio.get_running_loop() - _reader, writer = await ConnectionPoolManager.dial(options=trans_opt, timeout=1.0, loop=loop) + _reader, writer = await KeepLiveConnPoolManager.dial(options=trans_opt, timeout=1.0, loop=loop) assert writer is not None assert writer.get_extra_info("socket") is not None @@ -597,7 +597,7 @@ async def test_dial_with_tcp_socket(self): # Test dial with TCP socket loop = asyncio.get_running_loop() - _reader, writer = await ConnectionPoolManager.dial(options=trans_opt, timeout=1.0, loop=loop) + _reader, writer = await KeepLiveConnPoolManager.dial(options=trans_opt, timeout=1.0, loop=loop) assert writer is not None assert writer.get_extra_info("socket") is not None @@ -607,7 +607,7 @@ async def test_dial_with_tcp_socket(self): @pytest.mark.asyncio async def test_pool_get_with_socket_address(self): - """Test ConnectionPoolManager.get with socket address (lines 383-395)""" + """Test KeepLiveConnPoolManager.get with socket address (lines 383-395)""" port = getattr(self, "port") # Create a TCP socket @@ -622,7 +622,7 @@ async def test_pool_get_with_socket_address(self): # Create connection pool manager loop = asyncio.get_running_loop() - pool_mgr = ConnectionPoolManager(loop=loop) + pool_mgr = KeepLiveConnPoolManager(loop=loop) # Get connection from pool with socket conn = await pool_mgr.get(trans_opt, timeout=1.0) @@ -641,7 +641,7 @@ async def test_pool_get_with_socket_address(self): @pytest.mark.asyncio async def test_pool_get_with_local_addr(self): - """Test ConnectionPoolManager.get with local_addr (lines 383-395)""" + """Test KeepLiveConnPoolManager.get with local_addr (lines 383-395)""" port = getattr(self, "port") # Create transport options with local_addr @@ -652,7 +652,7 @@ async def test_pool_get_with_local_addr(self): # Create connection pool manager loop = asyncio.get_running_loop() - pool_mgr = ConnectionPoolManager(loop=loop) + pool_mgr = KeepLiveConnPoolManager(loop=loop) # Get connection from pool conn = await pool_mgr.get(trans_opt, timeout=1.0) @@ -667,7 +667,7 @@ async def test_pool_get_with_local_addr(self): @pytest.mark.asyncio async def test_pool_get_without_local_addr(self): - """Test ConnectionPoolManager.get without local_addr (lines 383-395)""" + """Test KeepLiveConnPoolManager.get without local_addr (lines 383-395)""" port = getattr(self, "port") # Create transport options without local_addr @@ -677,7 +677,7 @@ async def test_pool_get_without_local_addr(self): # Create connection pool manager loop = asyncio.get_running_loop() - pool_mgr = ConnectionPoolManager(loop=loop) + pool_mgr = KeepLiveConnPoolManager(loop=loop) # Get connection from pool conn = await pool_mgr.get(trans_opt, timeout=1.0) @@ -702,7 +702,7 @@ async def test_dial_with_ipv6_address(self): # This test may fail if IPv6 is not available, so we catch the exception try: - _reader, writer = await ConnectionPoolManager.dial(options=trans_opt, timeout=1.0, loop=loop) + _reader, writer = await KeepLiveConnPoolManager.dial(options=trans_opt, timeout=1.0, loop=loop) except OSError as err: # IPv6 may not be available in test environment print(f"IPv6 test skipped: {err}") diff --git a/tests/pool/test_pool_multiplexed.py b/tests/pool/test_pool_multiplexed.py index 978ba84..6252744 100644 --- a/tests/pool/test_pool_multiplexed.py +++ b/tests/pool/test_pool_multiplexed.py @@ -15,9 +15,9 @@ from trpc_sdk.abc import BaseClientTransportOption from trpc_sdk.config import SocketType from trpc_sdk.exceptions import ClientPoolConnClosedError -from trpc_sdk.transport import ConnPoolOptions -from trpc_sdk.transport import ConnectionPoolManager -from trpc_sdk.transport._pool import ConnectionPool +from trpc_sdk.transport import KeepLiveConnPoolOptions +from trpc_sdk.transport import KeepLiveConnPoolManager +from trpc_sdk.transport._client._pool import KeepLiveConnPool class ThreadTcpServer(object): @@ -71,12 +71,12 @@ def teardown_class(self): print("stop simple tcpserver") self.tcpsrv.stop() - def _pool(self) -> ConnectionPool: + def _pool(self) -> KeepLiveConnPool: trans_opt = BaseClientTransportOption() trans_opt.address = ("127.0.0.1", self.port) trans_opt.socket_type = SocketType.NET - options = ConnPoolOptions(max_idle=2, max_active=4) - return ConnectionPool(dial=ConnectionPoolManager.dial, trans_opt=trans_opt, options=options) + options = KeepLiveConnPoolOptions(max_idle=2, max_active=4) + return KeepLiveConnPool(dial=KeepLiveConnPoolManager.dial, trans_opt=trans_opt, options=options) @pytest.mark.asyncio async def test_get_conn(self): diff --git a/tests/serialization/test_serialization.py b/tests/serialization/test_serialization.py index 2658d6f..de9e06f 100644 --- a/tests/serialization/test_serialization.py +++ b/tests/serialization/test_serialization.py @@ -17,20 +17,20 @@ def test_serialization(): # unsupported body = helloworld_pb2.HelloRequest() body.msg = 'test' - assert serialize(SerializationType.Unsupported, body) == b'' + assert serialize(SerializationType.UNSUPPORTED, body) == b'' body = helloworld_pb2.HelloRequest() data = b'\n\x04test' - assert deserialize(SerializationType.Unsupported, data, body) is None + assert deserialize(SerializationType.UNSUPPORTED, data, body) is None # Noop body = Body() body.data = b'test' - assert serialize(SerializationType.Noop, body) == b'test' + assert serialize(SerializationType.NOOP, body) == b'test' body = Body() data = b'\n\x04test' - assert deserialize(SerializationType.Noop, data, body) is None + assert deserialize(SerializationType.NOOP, data, body) is None assert body.data == data # body or data empty diff --git a/tests/server/test_server.py b/tests/server/test_server.py index e09115d..4e55f96 100644 --- a/tests/server/test_server.py +++ b/tests/server/test_server.py @@ -50,7 +50,7 @@ def _request() -> bytes: msg.set_callee_service_name("trpc.test.Greeter") msg.set_caller_service_name("trpc.test.Caller") msg.set_timeout(1000) - msg.set_serialization_type(SerializationType.Noop) + msg.set_serialization_type(SerializationType.NOOP) msg.set_compress_type(0) return TrpcClientCodec().encode_data(ctx, b"hello") diff --git a/tests/server/test_server_task.py b/tests/server/test_server_task.py index f3a1508..3d5bedb 100644 --- a/tests/server/test_server_task.py +++ b/tests/server/test_server_task.py @@ -37,8 +37,7 @@ def _task_info(**extra): def test_task_process_keeps_the_python_handler(): - """``use_c_task`` is stored, but the child is still a Python ``TaskProcess``.""" - info = _task_info(use_c_task=True, c_task_driver_params={"log_level": 4, "log_file": "./test.log"}) + info = _task_info() process = TaskProcess(info, _adapter()) assert process.__class__ is TaskProcess @@ -47,12 +46,6 @@ def test_task_process_keeps_the_python_handler(): assert process.task_initializer is None assert process.block is True assert process._controlled is False - assert process.task_info.c_task_driver_params["log_level"] == 4 - assert process.task_info.use_c_task is True - - info.c_task_driver_params = {} - again = TaskProcess(info, _adapter()) - assert again.task_info.c_task_driver_params == {} def test_separate_mode_task_is_a_controlled_child(): diff --git a/tests/stream/test_stream_client.py b/tests/stream/test_stream_client.py index da46fb8..bb6df89 100644 --- a/tests/stream/test_stream_client.py +++ b/tests/stream/test_stream_client.py @@ -14,16 +14,16 @@ from trpc_sdk._inner import trpc_pb2 from trpc_sdk.abc import TrpcContext from trpc_sdk.abc import get_message +from trpc_sdk.abc import ClientStreamDesc from trpc_sdk.client import Options from trpc_sdk.codec import FrameHead from trpc_sdk.exceptions import ClientDecodeError from trpc_sdk.exceptions import ClientTimeoutError from trpc_sdk.exceptions import ServerSystemError from trpc_sdk.stream import ClientStream -from trpc_sdk.stream import ClientStreamDesc from trpc_sdk.stream import ReceiveControl from trpc_sdk.stream import SendControl -from trpc_sdk.stream import create_stream_client +from trpc_sdk.stream import create_client_stream_factory from trpc_sdk.stream import get_window_size from trpc_sdk.stream._constants import MAX_INIT_WINDOW_SIZE from trpc_sdk.stream._constants import STREAM_ID @@ -33,7 +33,7 @@ def _client_stream(): ctx = TrpcContext() get_message(ctx) - stream = ClientStream(ctx, ClientStreamDesc(stream_name="/method", client_streams=True), 101, "/method") + stream = ClientStream(ctx, ClientStreamDesc(name="/method"), 101) stream.stream = SimpleNamespace(send=AsyncMock(), recv=AsyncMock(), close=MagicMock(), start=AsyncMock()) stream.opts = Options() stream.opts.r_control = None @@ -44,8 +44,8 @@ def _client_stream(): def test_create_stream_client_starts_after_reserved_ids(): - client = create_stream_client() - assert client.stream_id == STREAM_ID + factory = create_client_stream_factory() + assert factory.stream_id == STREAM_ID @pytest.mark.asyncio diff --git a/tests/stream/test_stream_server.py b/tests/stream/test_stream_server.py index 9145741..5d07df1 100644 --- a/tests/stream/test_stream_server.py +++ b/tests/stream/test_stream_server.py @@ -25,7 +25,7 @@ def _options(): opts = ServiceOption() opts.set_protocol("trpc") - opts.current_serialization_type = SerializationType.Noop + opts.current_serialization_type = SerializationType.NOOP opts.stream_transport = MagicMock() return opts diff --git a/tests/task/test_task_stream.py b/tests/task/test_task_stream.py index 32eaf58..69ac352 100644 --- a/tests/task/test_task_stream.py +++ b/tests/task/test_task_stream.py @@ -54,7 +54,7 @@ def _capture(index, package): opts = ServiceOption() opts.set_protocol("trpc") - opts.current_serialization_type = SerializationType.Noop + opts.current_serialization_type = SerializationType.NOOP ctx = TrpcContext() get_message(ctx).stream_id = 1 server_stream = ServerStream(ctx, 1, opts) diff --git a/tests/test_cython_excludes.py b/tests/test_cython_excludes.py new file mode 100644 index 0000000..a0ba31a --- /dev/null +++ b/tests/test_cython_excludes.py @@ -0,0 +1,85 @@ +# Tencent is pleased to support the open source community by making tRPC-Python available. +# +# Copyright (C) 2026 Tencent. All rights reserved. +# +# tRPC-Python is licensed under Apache-2.0. +"""Guard the hatch-cython exclude list in pyproject.toml against rot. + +The exclude patterns are matched with ``re.match()`` against paths such as +``trpc_sdk/transport/_cython/_ipc_codec.pyx``. Stale patterns inherited from +the old package layout matched nothing for a long time while claiming that +production modules must not be compiled. These tests pin two invariants: + +* every exclude pattern still matches at least one real file, so dead + patterns are removed instead of silently accumulating; +* no ``.pyx`` file is ever excluded, so a "fixed" pattern cannot drop a + production Cython extension (e.g. the inner-IPC codec) from the wheel. +""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import List + +REPO_ROOT = Path(__file__).resolve().parents[1] +PACKAGE_ROOT = REPO_ROOT / "trpc_sdk" +SOURCE_SUFFIXES = (".py", ".pyx", ".pxd") + + +def _load_exclude_patterns() -> List[str]: + """Return the hatch-cython exclude patterns declared in pyproject.toml. + + ``tomllib`` only exists on Python 3.11+, while the package still supports + 3.8, so older interpreters fall back to extracting the quoted strings of + the ``exclude`` list directly from the TOML text. + + Returns: + The exclude patterns in declaration order. + """ + pyproject_path = REPO_ROOT / "pyproject.toml" + try: + import tomllib + except ModuleNotFoundError: + text = pyproject_path.read_text(encoding="utf-8") + section = text.split("[tool.hatch.build.hooks.cython.options.files]", 1)[1] + block = section.split("exclude = [", 1)[1].split("]", 1)[0] + # TOML basic strings escape backslashes ("\\." in the file is the + # two-character regex "\."), so undo that escaping after extraction. + return [pattern.replace("\\\\", "\\") for pattern in re.findall(r'"([^"]+)"', block)] + with pyproject_path.open("rb") as file: + config = tomllib.load(file) + files_options = config["tool"]["hatch"]["build"]["hooks"]["cython"]["options"]["files"] + return list(files_options.get("exclude", [])) + + +def _source_paths() -> List[str]: + """Return package source paths in the form hatch-cython matches against.""" + return sorted( + path.relative_to(REPO_ROOT).as_posix() + for path in PACKAGE_ROOT.rglob("*") + if path.is_file() and path.suffix in SOURCE_SUFFIXES + ) + + +def _excluded_paths(patterns: List[str], paths: List[str]) -> List[str]: + """Return the subset of ``paths`` matched by any exclude pattern.""" + return [path for path in paths if any(re.match(pattern, path) for pattern in patterns)] + + +def test_every_exclude_pattern_matches_a_real_file(): + patterns = _load_exclude_patterns() + paths = _source_paths() + dead = [pattern for pattern in patterns if not any(re.match(pattern, path) for path in paths)] + assert not dead, f"exclude patterns match no file and must be removed: {dead}" + + +def test_no_pyx_file_is_excluded(): + excluded = _excluded_paths(_load_exclude_patterns(), _source_paths()) + excluded_pyx = [path for path in excluded if path.endswith(".pyx")] + assert not excluded_pyx, f"production Cython sources must be compiled, excluded: {excluded_pyx}" + + +def test_ipc_codec_is_compiled(): + excluded = _excluded_paths(_load_exclude_patterns(), _source_paths()) + assert "trpc_sdk/transport/_cython/_ipc_codec.pyx" not in excluded diff --git a/tests/transport/test_transport_util.py b/tests/transport/test_transport_util.py index 38c36b2..b0c8c77 100644 --- a/tests/transport/test_transport_util.py +++ b/tests/transport/test_transport_util.py @@ -7,7 +7,7 @@ from trpc_sdk.abc import BaseClientTransportOption from trpc_sdk.abc import BaseServerTransportOption -from trpc_sdk.transport import ConnPoolOptions +from trpc_sdk.transport import KeepLiveConnPoolOptions from trpc_sdk.transport import RoundTripOptions from trpc_sdk.transport._cython import inner_decode_rsp from trpc_sdk.transport._cython import inner_encode_rsp @@ -23,7 +23,7 @@ def test_client_transport_option_defaults(): def test_round_trip_options_carry_pool_settings(): - pool = ConnPoolOptions(dial_timeout=100, idle_timeout=1, max_idle=2, max_active=4) + pool = KeepLiveConnPoolOptions(dial_timeout=100, idle_timeout=1, max_idle=2, max_active=4) options = RoundTripOptions() options.set_network("udp") options.set_pool_options(pool) diff --git a/trpc_sdk/__init__.py b/trpc_sdk/__init__.py index a5378dd..0d2c1d1 100644 --- a/trpc_sdk/__init__.py +++ b/trpc_sdk/__init__.py @@ -1,5 +1,6 @@ -# -*- coding: utf-8 -*- -""" -Init for trpc -""" - +# Tencent is pleased to support the open source community by making tRPC-Python available. +# +# Copyright (C) 2026 Tencent. All rights reserved. +# +# tRPC-Python is licensed under Apache-2.0. +"""Init for tRPC-Python.""" diff --git a/trpc_sdk/_inner/__init__.py b/trpc_sdk/_inner/__init__.py index 2246d43..2761573 100644 --- a/trpc_sdk/_inner/__init__.py +++ b/trpc_sdk/_inner/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Private inner symbols re-exported for the rest of the SDK. :class:`MemoryInspector` is resolved lazily: it pulls in tracemalloc, diff --git a/trpc_sdk/_inner/memory_inspection/__init__.py b/trpc_sdk/_inner/memory_inspection/__init__.py index 060477a..bbc89a6 100644 --- a/trpc_sdk/_inner/memory_inspection/__init__.py +++ b/trpc_sdk/_inner/memory_inspection/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Memory inspection module.""" from ._inspector import MemoryInspector diff --git a/trpc_sdk/_inner/memory_inspection/_inspector.py b/trpc_sdk/_inner/memory_inspection/_inspector.py index 9e8fe52..6e14ca1 100644 --- a/trpc_sdk/_inner/memory_inspection/_inspector.py +++ b/trpc_sdk/_inner/memory_inspection/_inspector.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Per-process tracemalloc snapshots dumped to files on demand. Workers construct :class:`MemoryInspecter` only when diff --git a/trpc_sdk/_inner/multiprocessing.py b/trpc_sdk/_inner/multiprocessing.py deleted file mode 100644 index edf2a24..0000000 --- a/trpc_sdk/_inner/multiprocessing.py +++ /dev/null @@ -1,11 +0,0 @@ -""" - trpc multiprocessing -""" -import multiprocessing - -PROCESS = multiprocessing.Process - - -def set_default_process(process_cls): - global PROCESS - PROCESS = process_cls diff --git a/trpc_sdk/_inner/pb/__init__.py b/trpc_sdk/_inner/pb/__init__.py index 84e483b..7ae2c95 100644 --- a/trpc_sdk/_inner/pb/__init__.py +++ b/trpc_sdk/_inner/pb/__init__.py @@ -3,6 +3,7 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. +"""Generated tRPC protocol buffer modules.""" from . import trpc_pb2 diff --git a/trpc_sdk/_inner/pb/trpc_pb2.py b/trpc_sdk/_inner/pb/trpc_pb2.py index 2518e6d..f8ea72d 100644 --- a/trpc_sdk/_inner/pb/trpc_pb2.py +++ b/trpc_sdk/_inner/pb/trpc_pb2.py @@ -11,13 +11,11 @@ _v = Version(protobuf_version) if Version("2.5") <= _v < Version("3.20.0"): - from ._v3_trpc_pb2 import * + from ._v3_trpc_pb2 import * # noqa: F401,F403 elif Version("4.21.0") <= _v < Version("5.26.0"): - from ._v4_trpc_pb2 import * + from ._v4_trpc_pb2 import * # noqa: F401,F403 elif _v >= Version("5.26.0"): - from ._v5_trpc_pb2 import * + from ._v5_trpc_pb2 import * # noqa: F401,F403 else: - raise ImportError( - f"unsupported protobuf version: {protobuf_version}; " - "require 3.x, >=4.21,<5.26, or >=5.26" - ) + raise ImportError(f"unsupported protobuf version: {protobuf_version}; " + "require 3.x, >=4.21,<5.26, or >=5.26") diff --git a/trpc_sdk/abc/__init__.py b/trpc_sdk/abc/__init__.py index d0da391..b5527da 100644 --- a/trpc_sdk/abc/__init__.py +++ b/trpc_sdk/abc/__init__.py @@ -3,12 +3,11 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """tRPC-Python ABC module""" -from ._circuit_breaker import BaseCircuitBreaker from ._codec import TaskCodec from ._client import BaseClient +from ._client import ClientStreamDesc from ._client import BaseClientStream from ._client import BaseClientStreamConnection from ._compress import BaseCompress @@ -30,14 +29,12 @@ from ._cython import create_message # pyright: ignore[reportMissingModuleSource] from ._cython import get_message # pyright: ignore[reportMissingModuleSource] from ._cython import parse_frame_head # pyright: ignore[reportMissingModuleSource] -from ._discovery import BaseDiscovery from ._filter import BaseFilter from ._filter import FilterHandleType from ._filter import FilterAsyncGenHandleType from ._filter import FilterAsyncGenReturnType from ._filter import FilterReturnType from ._filter import FilterStreamResultType -from ._loadbalance import BaseLoadBalance from ._log import LOG_LEVEL_NAMES from ._log import BaseLogger from ._log import BaseWriter @@ -53,16 +50,20 @@ from ._metrics import ReportStatus from ._metrics import StatPolicy from ._metrics import StatValue -from ._node import Node +from ._naming import BaseCircuitBreaker +from ._naming import BaseDiscovery +from ._naming import BaseLoadBalance +from ._naming import BaseSelector +from ._naming import BaseServiceRegistry +from ._naming import BaseServiceRouter +from ._naming import SelectorOption +from ._naming import ServerRouterOption +from ._naming import ServiceNameExtractor +from ._naming import Node from ._plugin import BasePlugin from ._plugin import BasePluginFactory from ._plugin import PluginInitPos from ._plugin import PluginType -from ._selector import BaseSelector -from ._selector import BaseServiceRouter -from ._selector import SelectorOption -from ._selector import ServerRouterOption -from ._selector import ServiceNameExtractor from ._serializer import BaseSerializer from ._server import BaseServer from ._server import BaseServerStream @@ -71,9 +72,8 @@ from ._server import ProcessType from ._server import ServiceDesc from ._server import StreamDesc -from ._service_registry import BaseServiceRegistry -from ._task_info import TaskInfo -from ._timer_hook import TimerHook +from ._types import TaskInfo +from ._timer import TimerHook from ._transport import AddrType from ._transport import BaseClientStreamTransport from ._transport import BaseClientTransport @@ -88,6 +88,7 @@ "BaseCircuitBreaker", "BaseClient", "BaseClientProtocolParser", + "ClientStreamDesc", "BaseClientStream", "BaseClientStreamConnection", "BaseClientStreamTransport", diff --git a/trpc_sdk/abc/_client.py b/trpc_sdk/abc/_client.py index 39a7ce0..d72477b 100644 --- a/trpc_sdk/abc/_client.py +++ b/trpc_sdk/abc/_client.py @@ -3,16 +3,17 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Client-side extension interfaces. This module defines the abstract contracts for unary RPC clients, application streams, and stream transports used by pluggable client implementations. """ + from __future__ import annotations from abc import ABC from abc import abstractmethod +from dataclasses import dataclass from typing import Any from typing import List @@ -44,6 +45,17 @@ async def invoke( ... +@dataclass +class ClientStreamDesc: + """Describes one client-side streaming method. + + Attributes: + name: RPC name written onto the INIT / DATA frames. + """ + + name: str = "" + + class BaseClientStream(ABC): """Define application-level client stream operations.""" diff --git a/trpc_sdk/abc/_codec.py b/trpc_sdk/abc/_codec.py index c3e78ce..9b5cb36 100644 --- a/trpc_sdk/abc/_codec.py +++ b/trpc_sdk/abc/_codec.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Pure-Python contracts for compression, serialization, and the task body codec. These interfaces are distinct from the Cython context-first protocol diff --git a/trpc_sdk/abc/_compress.py b/trpc_sdk/abc/_compress.py index 75148e8..e818338 100644 --- a/trpc_sdk/abc/_compress.py +++ b/trpc_sdk/abc/_compress.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Pure-Python contracts for frame-body compression.""" from abc import abstractmethod diff --git a/trpc_sdk/abc/_config.py b/trpc_sdk/abc/_config.py index 2ee5bbb..704ba43 100644 --- a/trpc_sdk/abc/_config.py +++ b/trpc_sdk/abc/_config.py @@ -3,12 +3,12 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Configuration extension interfaces. This module defines the abstract contracts for configuration loading, data providers, and decoders used by pluggable configuration backends. """ + from __future__ import annotations from abc import abstractmethod @@ -29,13 +29,7 @@ class BaseConfig(BasePlugin): hydration helpers. """ - def __init__( - self, - provider_name: str, - decoder_name: str, - provider_options: Dict, - decoder_options: Dict - ) -> None: + def __init__(self, provider_name: str, decoder_name: str, provider_options: Dict, decoder_options: Dict) -> None: """Initialize the configuration backend identity and options. Args: diff --git a/trpc_sdk/abc/_cython/__init__.py b/trpc_sdk/abc/_cython/__init__.py index d365365..bd52aee 100644 --- a/trpc_sdk/abc/_cython/__init__.py +++ b/trpc_sdk/abc/_cython/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Cython implementations of the core tRPC interfaces.""" from ._codec import BaseClientProtocolParser # pyright: ignore[reportMissingModuleSource] diff --git a/trpc_sdk/abc/_cython/_message.pxd b/trpc_sdk/abc/_cython/_message.pxd index e3c1dde..a4df601 100644 --- a/trpc_sdk/abc/_cython/_message.pxd +++ b/trpc_sdk/abc/_cython/_message.pxd @@ -15,7 +15,7 @@ cimport cython cdef class TrpcFrameHead: cdef: - public uint16_t stx # Protocol magic number identifying a tRPC frame. + public uint16_t magic # Protocol magic number identifying a tRPC frame. public uint8_t frame_type # Payload type encoded by this frame. public uint8_t frame_state # Streaming lifecycle state represented by the frame. public uint32_t package_len # Total frame size in bytes, including the header. @@ -26,7 +26,7 @@ cdef class TrpcFrameHead: # Setters mirror the public fields one for one. They exist so Python # callers and statically typed Cython callers share a single spelling; # every one of them stores the host-endian value unchanged. - cpdef void set_stx(self, uint16_t stx) except * + cpdef void set_magic(self, uint16_t magic) except * cpdef void set_frame_type(self, uint8_t frame_type) except * cpdef void set_frame_state(self, uint8_t frame_state) except * cpdef void set_package_len(self, uint32_t package_len) except * diff --git a/trpc_sdk/abc/_cython/_message.pyi b/trpc_sdk/abc/_cython/_message.pyi index 1538d5c..158013f 100644 --- a/trpc_sdk/abc/_cython/_message.pyi +++ b/trpc_sdk/abc/_cython/_message.pyi @@ -10,7 +10,7 @@ from typing import Any class TrpcFrameHead: """Mutable tRPC transport frame header.""" - stx: int + magic: int frame_type: int frame_state: int package_len: int @@ -18,7 +18,7 @@ class TrpcFrameHead: stream_id: int frame_reserved: int - def set_stx(self, stx: int) -> None: ... + def set_magic(self, magic: int) -> None: ... def set_frame_type(self, frame_type: int) -> None: ... def set_frame_state(self, frame_state: int) -> None: ... def set_package_len(self, package_len: int) -> None: ... diff --git a/trpc_sdk/abc/_cython/_message.pyx b/trpc_sdk/abc/_cython/_message.pyx index 2893eec..5d52bab 100644 --- a/trpc_sdk/abc/_cython/_message.pyx +++ b/trpc_sdk/abc/_cython/_message.pyx @@ -26,7 +26,7 @@ cdef class TrpcFrameHead: """ def __cinit__(self): - self.stx = 0 + self.magic = 0 self.frame_type = 0 self.frame_state = 0 self.package_len = 0 @@ -34,13 +34,13 @@ cdef class TrpcFrameHead: self.stream_id = 0 self.frame_reserved = 0 - cpdef void set_stx(self, uint16_t stx) except *: + cpdef void set_magic(self, uint16_t magic) except *: """Set the protocol magic number. Args: - stx: Host-endian magic; a decode mismatch invalidates the frame. + magic: Host-endian magic; a decode mismatch invalidates the frame. """ - self.stx = stx + self.magic = magic cpdef void set_frame_type(self, uint8_t frame_type) except *: """Set the payload type carried by this frame. diff --git a/trpc_sdk/abc/_cython/_message_builder.pyx b/trpc_sdk/abc/_cython/_message_builder.pyx index b9c8997..3da159e 100644 --- a/trpc_sdk/abc/_cython/_message_builder.pyx +++ b/trpc_sdk/abc/_cython/_message_builder.pyx @@ -40,7 +40,7 @@ cpdef TrpcFrameHead create_frame_head( ): """Create a frame header with the supplied routing fields. - ``stx``, ``package_len``, and ``head_len`` stay 0; the pack paths fill + ``magic``, ``package_len``, and ``head_len`` stay 0; the pack paths fill them when the frame is serialized. Args: @@ -82,7 +82,7 @@ cpdef TrpcFrameHead parse_frame_head(bytes data): frame_head = TrpcFrameHead() memcpy(&value16, data_ptr, sizeof(uint16_t)) - frame_head.stx = ntohs(value16) + frame_head.magic = ntohs(value16) frame_head.frame_type = data_ptr[2] frame_head.frame_state = data_ptr[3] @@ -103,7 +103,7 @@ cdef inline void _copy_frame_head( TrpcFrameHead target, ) noexcept: """Copy native frame-header fields without sharing mutable state.""" - target.stx = source.stx + target.magic = source.magic target.frame_type = source.frame_type target.frame_state = source.frame_state target.package_len = source.package_len diff --git a/trpc_sdk/abc/_filter.py b/trpc_sdk/abc/_filter.py index 224a7df..de259b6 100644 --- a/trpc_sdk/abc/_filter.py +++ b/trpc_sdk/abc/_filter.py @@ -3,12 +3,12 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Filter extension interfaces. This module defines the abstract contracts and shared result types used by pluggable filters that intercept unary and streaming RPC call chains. """ + from __future__ import annotations from abc import abstractmethod diff --git a/trpc_sdk/abc/_log.py b/trpc_sdk/abc/_log.py index 4343c0b..bb8fefb 100644 --- a/trpc_sdk/abc/_log.py +++ b/trpc_sdk/abc/_log.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Logging extension interfaces and shared configuration models. This module defines severity levels, output configuration dataclasses, and the @@ -148,39 +147,38 @@ def __init__(self): self._version = "" self._output_config: OutputConfig = None - self._fmt: str = ( - "[%(asctime)s][%(levelname)s][%(filename)s:%(lineno)s]" - "[%(process)d][%(message)s]" - ) + self._fmt: str = ("[%(asctime)s][%(levelname)s][%(filename)s:%(lineno)s]" + "[%(process)d][%(message)s]") self._time_fmt: str = "%Y-%m-%d %H:%M:%S" self._handler: Optional[logging.Handler] = None self._level: Optional[int] = None - + @property def output_config(self) -> OutputConfig: """Get the output configuration.""" return self._output_config - + @property def fmt(self) -> str: """Get the message format template.""" return self._fmt - + @property def time_fmt(self) -> str: """Get the timestamp format string.""" return self._time_fmt - + @property def handler(self) -> Optional[logging.Handler]: """Get the backend-specific handler instance.""" return self._handler - + @property def level(self) -> Optional[int]: """Get the effective severity threshold for this writer.""" return self._level + class BaseLogger(BasePlugin): """Define the pluggable logger API used by the framework.""" diff --git a/trpc_sdk/abc/_metrics.py b/trpc_sdk/abc/_metrics.py index 96abc0d..7bbd728 100644 --- a/trpc_sdk/abc/_metrics.py +++ b/trpc_sdk/abc/_metrics.py @@ -3,12 +3,12 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Metrics extension interfaces and shared report models. This module defines statistics policies, call-dimension payloads, and the abstract metrics reporter used by pluggable monitoring backends. """ + from __future__ import annotations from abc import abstractmethod diff --git a/trpc_sdk/abc/_naming/__init__.py b/trpc_sdk/abc/_naming/__init__.py new file mode 100644 index 0000000..868e679 --- /dev/null +++ b/trpc_sdk/abc/_naming/__init__.py @@ -0,0 +1,30 @@ +# Tencent is pleased to support the open source community by making tRPC-Python available. +# +# Copyright (C) 2026 Tencent. All rights reserved. +# +# tRPC-Python is licensed under Apache-2.0. +"""Naming module.""" + +from ._circuit_breaker import BaseCircuitBreaker +from ._discovery import BaseDiscovery +from ._loadbalance import BaseLoadBalance +from ._selector import BaseSelector +from ._selector import ServerRouterOption +from ._selector import SelectorOption +from ._selector import ServiceNameExtractor +from ._selector import BaseServiceRouter +from ._service_registry import BaseServiceRegistry +from ._types import Node + +__all__ = [ + "BaseCircuitBreaker", + "BaseDiscovery", + "BaseLoadBalance", + "BaseSelector", + "ServerRouterOption", + "SelectorOption", + "ServiceNameExtractor", + "BaseServiceRouter", + "BaseServiceRegistry", + "Node", +] diff --git a/trpc_sdk/abc/_circuit_breaker.py b/trpc_sdk/abc/_naming/_circuit_breaker.py similarity index 96% rename from trpc_sdk/abc/_circuit_breaker.py rename to trpc_sdk/abc/_naming/_circuit_breaker.py index c924326..63a9903 100644 --- a/trpc_sdk/abc/_circuit_breaker.py +++ b/trpc_sdk/abc/_naming/_circuit_breaker.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Circuit breaker extension interfaces. This module defines the abstract contract used by pluggable circuit breaker @@ -16,8 +15,8 @@ from abc import abstractmethod from typing import NoReturn -from ._node import Node -from ._plugin import BasePlugin +from .._plugin import BasePlugin +from ._types import Node class BaseCircuitBreaker(BasePlugin): diff --git a/trpc_sdk/abc/_discovery.py b/trpc_sdk/abc/_naming/_discovery.py similarity index 96% rename from trpc_sdk/abc/_discovery.py rename to trpc_sdk/abc/_naming/_discovery.py index 2c643ac..828f70d 100644 --- a/trpc_sdk/abc/_discovery.py +++ b/trpc_sdk/abc/_naming/_discovery.py @@ -3,12 +3,12 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Service discovery extension interfaces. This module defines the abstract contract used by pluggable discovery implementations that list service endpoints and select one node for a call. """ + from __future__ import annotations from abc import abstractmethod @@ -16,8 +16,8 @@ from typing import List from typing import Optional -from ._node import Node -from ._plugin import BasePlugin +from .._plugin import BasePlugin +from ._types import Node class BaseDiscovery(BasePlugin): diff --git a/trpc_sdk/abc/_loadbalance.py b/trpc_sdk/abc/_naming/_loadbalance.py similarity index 85% rename from trpc_sdk/abc/_loadbalance.py rename to trpc_sdk/abc/_naming/_loadbalance.py index 3234994..7dea554 100644 --- a/trpc_sdk/abc/_loadbalance.py +++ b/trpc_sdk/abc/_naming/_loadbalance.py @@ -3,15 +3,15 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Load balancing service selection.""" + from __future__ import annotations from abc import abstractmethod from typing import List -from ._node import Node -from ._plugin import BasePlugin +from .._plugin import BasePlugin +from ._types import Node class BaseLoadBalance(BasePlugin): @@ -19,8 +19,7 @@ class BaseLoadBalance(BasePlugin): @abstractmethod async def select(self, service_name: str, node_list: List[Node], namespace: str) -> Node: - """ - Select one endpoint for the given service and options. + """Select one endpoint for the given service and options. Args: service_name: Logical service name to select from. diff --git a/trpc_sdk/abc/_selector.py b/trpc_sdk/abc/_naming/_selector.py similarity index 97% rename from trpc_sdk/abc/_selector.py rename to trpc_sdk/abc/_naming/_selector.py index 1487c33..1db064c 100644 --- a/trpc_sdk/abc/_selector.py +++ b/trpc_sdk/abc/_naming/_selector.py @@ -3,13 +3,13 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Service selector extension interfaces and routing options. This module defines routing option models and the abstract selector, service-router, and DSN extractor contracts used to choose a service node and report call outcomes. """ + from __future__ import annotations from abc import ABC @@ -21,9 +21,9 @@ from typing import Optional from typing import Tuple -from ._cython import TrpcContext # pyright: ignore[reportMissingModuleSource] -from ._node import Node -from ._plugin import BasePlugin +from .._cython import TrpcContext # pyright: ignore[reportMissingModuleSource] +from .._plugin import BasePlugin +from ._types import Node @dataclass @@ -290,11 +290,7 @@ class BaseServiceRouter(BasePlugin): """ @abstractmethod - async def filter( - self, - service_name: str, - nodes: List[Node], - opt: ServerRouterOption) -> List[Node]: + async def filter(self, service_name: str, nodes: List[Node], opt: ServerRouterOption) -> List[Node]: """Return the nodes that are legal for this call. Args: diff --git a/trpc_sdk/abc/_service_registry.py b/trpc_sdk/abc/_naming/_service_registry.py similarity index 97% rename from trpc_sdk/abc/_service_registry.py rename to trpc_sdk/abc/_naming/_service_registry.py index 34d0c61..97ebec3 100644 --- a/trpc_sdk/abc/_service_registry.py +++ b/trpc_sdk/abc/_naming/_service_registry.py @@ -3,18 +3,18 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Service registry extension interfaces. This module defines the abstract contract used by pluggable registry backends that publish and withdraw service endpoint addresses. """ + from __future__ import annotations from abc import abstractmethod from typing import Tuple -from ._plugin import BasePlugin +from .._plugin import BasePlugin class BaseServiceRegistry(BasePlugin): diff --git a/trpc_sdk/abc/_node.py b/trpc_sdk/abc/_naming/_types.py similarity index 89% rename from trpc_sdk/abc/_node.py rename to trpc_sdk/abc/_naming/_types.py index 11e5040..b5e52d3 100644 --- a/trpc_sdk/abc/_node.py +++ b/trpc_sdk/abc/_naming/_types.py @@ -3,13 +3,10 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. +"""Types used by the tRPC naming module.""" -"""Service node data model. - -This module defines the ``Node`` dataclass used by naming, load balancing, and -circuit breaker components to describe one selectable service endpoint. -""" from __future__ import annotations + from dataclasses import dataclass diff --git a/trpc_sdk/abc/_plugin.py b/trpc_sdk/abc/_plugin.py index 34ec820..0cbf162 100644 --- a/trpc_sdk/abc/_plugin.py +++ b/trpc_sdk/abc/_plugin.py @@ -1,8 +1,8 @@ -# Tencent is pleased to support the open source community by making tRPC-Agent-Python available. +# Tencent is pleased to support the open source community by making tRPC-Python available. # # Copyright (C) 2026 Tencent. All rights reserved. # -# tRPC-Agent-Python is licensed under Apache-2.0. +# tRPC-Python is licensed under Apache-2.0. """Plugin abstract base class""" from __future__ import annotations @@ -78,7 +78,6 @@ class PluginType(IntEnum): LOG_COMPONENT = 53 - # plugin - trace TRACE = 60 @@ -119,22 +118,22 @@ def __init__(self): self._version: str = "" self._type: PluginType = PluginType.UNKNOWN self._init_pos: PluginInitPos = PluginInitPos.UNKNOWN - + @property def name(self) -> str: """Get plugin name""" return self._name - + @property def version(self) -> str: """Get plugin version""" return self._version - + @property def type(self) -> PluginType: """Get plugin type""" return self._type - + @property def type_name(self) -> str: """Get plugin type name""" @@ -144,7 +143,7 @@ def type_name(self) -> str: def init_pos(self) -> PluginInitPos: """Get plugin init position""" return self._init_pos - + def init(self): """Initialize plugin""" return @@ -152,7 +151,7 @@ def init(self): def start(self): """Start plugin""" return - + def stop(self): """Stop plugin""" return diff --git a/trpc_sdk/abc/_serializer.py b/trpc_sdk/abc/_serializer.py index 3b07b77..cf02c91 100644 --- a/trpc_sdk/abc/_serializer.py +++ b/trpc_sdk/abc/_serializer.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Pure-Python contracts for serialization """ diff --git a/trpc_sdk/abc/_server.py b/trpc_sdk/abc/_server.py index 6ff9a53..bea6df3 100644 --- a/trpc_sdk/abc/_server.py +++ b/trpc_sdk/abc/_server.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Server-side descriptors and extension interfaces. This module defines service method descriptors, streaming interfaces, process @@ -69,7 +68,7 @@ class StreamDesc: name: str impl_func: Callable[..., Any] - server_stream: Any + server_stream: "BaseServerStream" @dataclass diff --git a/trpc_sdk/abc/_timer_hook.py b/trpc_sdk/abc/_timer.py similarity index 99% rename from trpc_sdk/abc/_timer_hook.py rename to trpc_sdk/abc/_timer.py index 1379042..e4e52d3 100644 --- a/trpc_sdk/abc/_timer_hook.py +++ b/trpc_sdk/abc/_timer.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Abstract lifecycle contract for dedicated timer processes. The public SDK no longer ships a timer-process implementation, so nothing diff --git a/trpc_sdk/abc/_transport.py b/trpc_sdk/abc/_transport.py index 28dd590..c20d582 100644 --- a/trpc_sdk/abc/_transport.py +++ b/trpc_sdk/abc/_transport.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Transport extension interfaces and shared option models. This module defines the abstract contracts for server and client transports, diff --git a/trpc_sdk/abc/_task_info.py b/trpc_sdk/abc/_types.py similarity index 77% rename from trpc_sdk/abc/_task_info.py rename to trpc_sdk/abc/_types.py index 5aa4de5..24fa91d 100644 --- a/trpc_sdk/abc/_task_info.py +++ b/trpc_sdk/abc/_types.py @@ -3,15 +3,12 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. +"""Types used by the tRPC framework.""" -"""User-defined task description models. - -This module defines the ``TaskInfo`` dataclass used to describe worker-process -handlers, initialization hooks, and optional C-task driver settings. -""" from __future__ import annotations from dataclasses import dataclass + from typing import Any from typing import Callable from typing import Dict @@ -32,9 +29,6 @@ class TaskInfo: thread_num: Number of worker threads used by the task. model_path: Optional path to a model artifact loaded by the task. model_info: Optional opaque model metadata. - use_c_task: Whether the task should run through the C-task driver. - c_task_driver_params: Optional parameters forwarded to the C-task - driver. on_fork: Optional hook invoked after the worker process forks. task_num: Number of task processes to start; 0 means not set, so YAML ``global.processmodel.task_num`` (default 1) applies. @@ -48,8 +42,6 @@ class TaskInfo: thread_num: int = 0 model_path: str = "" model_info: Optional[Any] = None - use_c_task: bool = False - c_task_driver_params: Optional[Dict[str, Any]] = None on_fork: Optional[Callable[[None], None]] = None task_num: int = 0 pause_heartbeat: bool = False diff --git a/trpc_sdk/admin/__init__.py b/trpc_sdk/admin/__init__.py index e7eae8e..dab797b 100644 --- a/trpc_sdk/admin/__init__.py +++ b/trpc_sdk/admin/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """tRPC-Python admin plugin. The package is split by responsibility: @@ -39,7 +38,6 @@ from ._loglevel import set_log_level from ._plugin import AdminPlugin - __all__ = [ "AdminPlugin", "get_log_level", diff --git a/trpc_sdk/admin/_client.py b/trpc_sdk/admin/_client.py index 4cf7d2d..aa6ed8f 100644 --- a/trpc_sdk/admin/_client.py +++ b/trpc_sdk/admin/_client.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Worker-side admin WS client. Each worker process dials the admin HTTP server's WS endpoint and serves the diff --git a/trpc_sdk/admin/_constants.py b/trpc_sdk/admin/_constants.py index b220cba..c8a8821 100644 --- a/trpc_sdk/admin/_constants.py +++ b/trpc_sdk/admin/_constants.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Constants shared by the admin HTTP server and the worker WS client.""" from __future__ import annotations diff --git a/trpc_sdk/admin/_hooks.py b/trpc_sdk/admin/_hooks.py index e330198..d40f3ae 100644 --- a/trpc_sdk/admin/_hooks.py +++ b/trpc_sdk/admin/_hooks.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """User callbacks run when the admin endpoints start. The lists are consumed by :meth:`~trpc_sdk.admin.AdminPlugin.on_master_start` diff --git a/trpc_sdk/admin/_loglevel.py b/trpc_sdk/admin/_loglevel.py index c09fb2b..0a8779d 100644 --- a/trpc_sdk/admin/_loglevel.py +++ b/trpc_sdk/admin/_loglevel.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Log level accessors used by the admin ``loglevel`` commands.""" from __future__ import annotations diff --git a/trpc_sdk/admin/_plugin.py b/trpc_sdk/admin/_plugin.py index 7b8337a..9cdd8d5 100644 --- a/trpc_sdk/admin/_plugin.py +++ b/trpc_sdk/admin/_plugin.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Admin plugin that starts the admin HTTP server and worker WS clients.""" from __future__ import annotations diff --git a/trpc_sdk/admin/_server.py b/trpc_sdk/admin/_server.py index f3723f4..fc2f0d4 100644 --- a/trpc_sdk/admin/_server.py +++ b/trpc_sdk/admin/_server.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Admin HTTP server. Runs in the root process on its own thread and event loop. It serves the diff --git a/trpc_sdk/client/__init__.py b/trpc_sdk/client/__init__.py index 8d831f1..c934f3e 100644 --- a/trpc_sdk/client/__init__.py +++ b/trpc_sdk/client/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """tRPC-Python client package: how one outbound call is assembled. Public symbols are re-exported here. Callers should @@ -21,14 +20,14 @@ from ._options import Options from ._options import get_options from ._options import normalize_options -from ._client import Client +from ._client import TrpcClient from ._client import get_client -from ._client import select_node -from ._client import set_timeout -from ._client import update_message +from ._utils import select_node +from ._utils import set_timeout +from ._utils import update_message __all__ = [ - "Client", + "TrpcClient", "Options", "get_client", "get_options", diff --git a/trpc_sdk/client/_client.py b/trpc_sdk/client/_client.py index 104c080..048b16c 100644 --- a/trpc_sdk/client/_client.py +++ b/trpc_sdk/client/_client.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Unary tRPC client invoke path. Consumes the :class:`Options` built by :mod:`trpc_sdk.client._options`, @@ -25,23 +24,17 @@ from typing import Union from trpc_sdk.abc import BaseClient -from trpc_sdk.abc import Node from trpc_sdk.abc import TrpcContext -from trpc_sdk.abc import TrpcMessage from trpc_sdk.common import get_or_create_event_loop from trpc_sdk.compressor import compress from trpc_sdk.compressor import decompress -from trpc_sdk.config import SocketType from trpc_sdk.config import TrpcConfig from trpc_sdk.exceptions import ClientConnectionError from trpc_sdk.exceptions import ClientEncodeError -from trpc_sdk.exceptions import ClientRouteError from trpc_sdk.exceptions import ClientTimeoutError from trpc_sdk.exceptions import TrpcErrorCode from trpc_sdk.exceptions import TrpcException -from trpc_sdk.exceptions import UnknownError from trpc_sdk.log import logger -from trpc_sdk.naming import get_selector from trpc_sdk.serialization import deserialize from trpc_sdk.serialization import serialize from trpc_sdk.transport import ClientTimeoutReason @@ -51,15 +44,9 @@ from trpc_sdk.utils import singleton from ._options import Options from ._options import get_options - - -def get_client(): - """Return the process-wide :class:`Client` singleton. - - ``Client`` is decorated with :func:`~trpc_sdk.utils.singleton`, - so concurrent callers share one instance. - """ - return Client() +from ._utils import update_message +from ._utils import select_node +from ._utils import set_timeout async def _invoke_backend(ctx: TrpcContext, req: Any, rsp: Any, opts: Options) -> Any: @@ -102,13 +89,14 @@ async def _invoke_backend(ctx: TrpcContext, req: Any, rsp: Any, opts: Options) - rsp_buff = await client_ts.round_trip(ctx, req_buff, opts.call_options) logger.debug("Client invoke backend request %s end", opts.endpoint) except ConnectionError as err: - raise ClientConnectionError(f"Client invoke backend bad connection to {opts.call_options.address} {err}") from err + raise ClientConnectionError( + f"Client invoke backend bad connection to {opts.call_options.address} {err}") from err if opts.call_options.req_type == RequestType.SEND_ONLY: return rsp_body = client_codec.decode_data(ctx, rsp_buff) - if len(rsp_body) > 0: + if rsp_body: # Prefer types from the backend response, then the same per-call overrides. serialization_type = msg.serialization_type compress_type = msg.compress_type @@ -123,130 +111,8 @@ async def _invoke_backend(ctx: TrpcContext, req: Any, rsp: Any, opts: Options) - return rsp -def update_message(msg: TrpcMessage, opts: Options) -> None: - """Copy caller-facing option fields onto the outbound message. - - Covers metadata, caller service name, serialization / compress types, - and optional custom request / response heads. ``req_head`` replaces - the codec request head; ``rsp_head`` is a caller-owned buffer that - the codec fills with the backend response head. - - Args: - msg: Outbound client message to mutate. - opts: Per-call options already assembled by :func:`get_options`. - """ - if opts.metadata: - meta_data = msg.client_meta_data or {} - meta_data.update(opts.metadata) - msg.set_client_meta_data(meta_data) - - if opts.caller_service_name: - msg.set_caller_service_name(opts.caller_service_name) - - if opts.serialization_type >= 0: - msg.set_serialization_type(opts.serialization_type) - - if opts.compress_type >= 0: - msg.set_compress_type(opts.compress_type) - - if opts.req_head: - msg.set_client_req_head(opts.req_head) - if opts.rsp_head: - msg.set_client_rsp_head(opts.rsp_head) - - -async def select_node(msg: TrpcMessage, opts: Options) -> Node: - """Resolve the downstream node and copy its address onto ``msg``. - - Unix-socket calls rewrite ``opts.target`` first. An explicit - ``target`` of the form ``scheme://endpoint`` overrides the default - Polar selector. - - Args: - msg: Outbound message; remote address and env transfer are set. - opts: Per-call options; selector and endpoint may be replaced. - - Returns: - The selected :class:`~trpc_sdk.abc.Node`. - - Raises: - ClientRouteError: ``target`` has no ``scheme://endpoint``, or - the selector returned no addressable node. - UnknownError: ``opts.selector`` is missing. - """ - if opts.socket_type == SocketType.UNIX: - opts.target = "ip://" + opts.unix_path + ":0" - - if opts.target: - targets = opts.target.split("://") - if len(targets) != 2: - raise ClientRouteError("Client select node target schema invalid") - opts.selector = get_selector(targets[0]) - opts.endpoint = targets[1] - - if not opts.selector: - raise UnknownError("Client select node selector not exist") - - logger.debug("%s|select node", opts.endpoint) - node = await opts.selector.select(opts.endpoint, opts.selector_options) - logger.debug("%s|select end node=%s", opts.endpoint, node) - - if node is None or not node.address: - raise ClientRouteError("cannot find downstream node") - - opts.load_node_config(node) - opts.call_options.set_endpoint(opts.endpoint) - - msg.set_remote_addr(node.address) - msg.set_callee_container_name(node.container_name) - if len(msg.env_transfer) == 0: - msg.set_env_transfer(node.env_key) - - return node - - -def set_timeout(ctx: TrpcContext, msg: TrpcMessage, opts: Options, begin: int) -> ClientTimeoutReason: - """Apply the tighter of the client timeout and the server deadline. - - When the client deadline is sooner (or the server set none), a later - timeout is blamed on the downstream and reported to the selector as - :attr:`~trpc_sdk.transport.ClientTimeoutReason.DOWNSTREAM_TIMEOUT`. When - the server deadline is sooner, the timeout is - :attr:`~trpc_sdk.transport.ClientTimeoutReason.CURRENT_SERVICE_TIMEOUT` - and is not treated as downstream failure. - - Args: - ctx: Request context; ``deadline`` and ``timeout`` are updated. - msg: Outbound message; remaining timeout is written for the peer. - opts: Per-call options; ``timeout`` is in milliseconds. - begin: ``now_ms()`` at the start of this attempt. - - Returns: - Which side should be blamed if this call times out. - - Raises: - ClientTimeoutError: Remaining time is already negative. - """ - timeout_reason = ClientTimeoutReason.DOWNSTREAM_TIMEOUT - if opts.timeout > 0: - client_deadline = begin + opts.timeout - if client_deadline < ctx.deadline or ctx.deadline == 0: - ctx.deadline = client_deadline - ctx.timeout = opts.timeout - else: - ctx.timeout = ctx.deadline - begin - timeout_reason = ClientTimeoutReason.CURRENT_SERVICE_TIMEOUT - if ctx.timeout < 0: - raise ClientTimeoutError("client reach deadline") - msg.set_timeout(ctx.timeout) - else: - ctx.timeout = 0 - - return timeout_reason - - @singleton -class Client(BaseClient): +class TrpcClient(BaseClient): """Default tRPC unary client. ``invoke`` builds a fresh :class:`Options` per request so concurrent @@ -254,11 +120,8 @@ class Client(BaseClient): :func:`_invoke_backend`. """ - def __init__(self): - pass - @staticmethod - def check_handle_error(err, timeout_reason: ClientTimeoutReason): + def _check_handle_error(err, timeout_reason: ClientTimeoutReason): """Return whether ``err`` should be reported to the selector. Only a connect failure, or an invoke timeout blamed on the @@ -269,13 +132,15 @@ def check_handle_error(err, timeout_reason: ClientTimeoutReason): err: Exception caught during invoke, or ``None``. timeout_reason: Value returned by :func:`set_timeout`. """ - return err is not None and isinstance(err, TrpcException) and \ - (err.code == TrpcErrorCode.TRPC_CLIENT_CONNECT_ERR or - (err.code == TrpcErrorCode.TRPC_CLIENT_INVOKE_TIMEOUT_ERR and - timeout_reason == ClientTimeoutReason.DOWNSTREAM_TIMEOUT)) + # yapf: disable + return (err is not None and isinstance(err, TrpcException) + and (err.code == TrpcErrorCode.TRPC_CLIENT_CONNECT_ERR or + (err.code == TrpcErrorCode.TRPC_CLIENT_INVOKE_TIMEOUT_ERR # noqa: E128 + and timeout_reason == ClientTimeoutReason.DOWNSTREAM_TIMEOUT))) + # yapf: enable @staticmethod - def check_client_rsp_err(err, msg): + def _check_client_rsp_err(err, msg): """Return whether the codec stored a framework error on ``msg``. Used after a successful filter-chain return to surface connect @@ -286,10 +151,13 @@ def check_client_rsp_err(err, msg): err: Exception already captured, or ``None``. msg: Client message that may hold ``client_rsp_err``. """ - return err is None and msg.client_rsp_err is not None and \ - msg.client_rsp_err.code != TrpcErrorCode.TRPC_INVOKE_SUCCESS + return (err is None and msg.client_rsp_err is not None + and msg.client_rsp_err.code != TrpcErrorCode.TRPC_INVOKE_SUCCESS) - def invoke_sync(self, ctx: TrpcContext, req: Any, rsp_cls: Any, + def invoke_sync(self, + ctx: TrpcContext, + req: Any, + rsp_cls: Any, options: Optional[Union[Options, Callable, Sequence]] = None): """Run :meth:`invoke` to completion on the current event loop. @@ -311,7 +179,10 @@ def invoke_sync(self, ctx: TrpcContext, req: Any, rsp_cls: Any, return loop.run_until_complete(self.invoke(ctx, req, rsp_cls, options)) - async def invoke(self, ctx: TrpcContext, req: Any, rsp_cls: Any, + async def invoke(self, + ctx: TrpcContext, + req: Any, + rsp_cls: Any, options: Optional[Union[Options, Callable, Sequence]] = None) -> Any: """Invoke a unary backend RPC. @@ -363,12 +234,12 @@ async def invoke(self, ctx: TrpcContext, req: Any, rsp_cls: Any, finally: cost = now_ms() - begin - if self.check_handle_error(err, timeout_reason): + if self._check_handle_error(err, timeout_reason): await opts.selector.report(node, cost, err.code) else: await opts.selector.report(node, cost, 0) - if self.check_client_rsp_err(err, msg): + if self._check_client_rsp_err(err, msg): err = msg.client_rsp_err if opts.node: @@ -380,3 +251,12 @@ async def invoke(self, ctx: TrpcContext, req: Any, rsp_cls: Any, if isinstance(err, ClientTimeoutError): err.set_timeout_type(timeout_reason) raise err + + +def get_client(): + """Return the process-wide :class:`TrpcClient` singleton. + + ``Client`` is decorated with :func:`~trpc_sdk.utils.singleton`, + so concurrent callers share one instance. + """ + return TrpcClient() diff --git a/trpc_sdk/client/_config.py b/trpc_sdk/client/_config.py index e11cfb6..0de1299 100644 --- a/trpc_sdk/client/_config.py +++ b/trpc_sdk/client/_config.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Deprecated client-config shim over :class:`~trpc_sdk.config.TrpcConfig`. Prefer the corresponding :class:`~trpc_sdk.config.TrpcConfig` classmethods. diff --git a/trpc_sdk/client/_options.py b/trpc_sdk/client/_options.py index bb93e0a..d9eff67 100644 --- a/trpc_sdk/client/_options.py +++ b/trpc_sdk/client/_options.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Client option module. Holds the per-call :class:`Options` container with chainable ``set_*`` @@ -17,6 +16,7 @@ import ssl from typing import Any from typing import Callable +from typing import Dict from typing import List from typing import Mapping from typing import Optional @@ -25,6 +25,8 @@ from typing import Union from trpc_sdk.abc import BaseFilter +from trpc_sdk.abc import BaseCodec +from trpc_sdk.abc import BaseSelector from trpc_sdk.abc import Node from trpc_sdk.abc import SelectorOption from trpc_sdk.abc import TrpcMessage @@ -37,7 +39,7 @@ from trpc_sdk.naming import TrpcSelector from trpc_sdk.serialization import SerializationType from trpc_sdk.transport import ClientTransport -from trpc_sdk.transport import ConnPoolOptions +from trpc_sdk.transport import KeepLiveConnPoolOptions from trpc_sdk.transport import RoundTripOptions from trpc_sdk.transport import get_client_transport from trpc_sdk.transport import get_default_client_transport @@ -46,8 +48,7 @@ # pylint: disable=too-many-instance-attributes,too-many-public-methods class Options: - """ - Client options for TRPC service invocation + """Client options for TRPC service invocation. This class encapsulates all configuration parameters needed for making TRPC client calls, including service discovery, load balancing, circuit breaking, transport settings, and more. @@ -60,13 +61,13 @@ def __init__(self): """Initialize client options with default values""" self._appliers: List[Callable[["Options"], None]] = [] - self.namespace = "" + self.namespace: str = "" - self.selector = None + self.selector: Optional[BaseSelector] = None self.selector_options: SelectorOption = SelectorOption() self.filters: FilterChain = FilterChain(False) - self.metadata: dict = {} + self.metadata: Dict[str, Any] = {} self.service_name: str = "" self.caller_service_name: str = "" @@ -77,20 +78,20 @@ def __init__(self): self.unix_path: str = "" self.network: str = "" - self.transport: ClientTransport = None + self.transport: Optional[ClientTransport] = None self.call_options = RoundTripOptions() - self.codec = None + self.codec: Optional[BaseCodec] = None self.current_serialization_type: int = -1 self.serialization_type: int = -1 self.current_compress_type: int = -1 self.compress_type: int = -1 - self.req_head = None - self.rsp_head = None + self.req_head: Any = None + self.rsp_head: Any = None - self.node: Node = None + self.node: Optional[Node] = None self.timeout: int = 0 # stream @@ -112,8 +113,7 @@ def _record(self, apply: Callable[["Options"], None]) -> "Options": return self def load_client_config(self, name: str): - """ - Load client configuration from service name + """Load client configuration from service name. Retrieves backend configuration based on the service name (typically from proto file) @@ -170,12 +170,12 @@ def load_client_config(self, name: str): if service.short_conn is not None: self.call_options.set_short_conn(service.short_conn) - pool_opts = ConnPoolOptions(dial_timeout=service.dial_timeout, - idle_timeout=service.idle_time, - max_conn_lifetime=service.max_conn_lifetime, - max_idle=service.max_idle_conn, - max_active=service.max_active_conn, - wait=service.is_wait_active_conn) + pool_opts = KeepLiveConnPoolOptions(dial_timeout=service.dial_timeout, + idle_timeout=service.idle_time, + max_conn_lifetime=service.max_conn_lifetime, + max_idle=service.max_idle_conn, + max_active=service.max_active_conn, + wait=service.is_wait_active_conn) self.call_options.set_pool_options(pool_opts) if service.set_name: @@ -189,8 +189,7 @@ def load_client_config(self, name: str): return self def load_node_config(self, node: Node): - """ - Configure options using node information from registry center + """Configure options using node information from registry center. Sets parameters based on the node information returned by the service registry @@ -266,11 +265,11 @@ def apply(opts: Options): return self._record(apply) - def set_caller_envname(self, caller_envname: str) -> "Options": + def set_caller_env_name(self, caller_env_name: str) -> "Options": """Set caller service environment name.""" def apply(opts: Options): - opts.selector_options.set_src_env_name(caller_envname) + opts.selector_options.set_src_env_name(caller_env_name) return self._record(apply) @@ -282,11 +281,11 @@ def apply(opts: Options): return self._record(apply) - def set_callee_envname(self, callee_envname: str) -> "Options": - """Set callee service environment.""" + def set_callee_env_name(self, callee_env_name: str) -> "Options": + """Set callee service environment name.""" def apply(opts: Options): - opts.selector_options.set_dst_env_name(callee_envname) + opts.selector_options.set_dst_env_name(callee_env_name) return self._record(apply) @@ -314,11 +313,11 @@ def apply(opts: Options): return self._record(apply) - def set_servicerouter_name(self, servicerouter_name: str) -> "Options": + def set_service_router_name(self, service_router_name: str) -> "Options": """Set service router by name.""" def apply(opts: Options): - opts.selector_options.set_service_router(servicerouter_name) + opts.selector_options.set_service_router(service_router_name) return self._record(apply) @@ -531,7 +530,7 @@ def apply(opts: Options): return self._record(apply) - def set_pool_opts(self, pool_opts: ConnPoolOptions) -> "Options": + def set_pool_opts(self, pool_opts: KeepLiveConnPoolOptions) -> "Options": """Set connection pool configuration options.""" def apply(opts: Options): @@ -590,7 +589,7 @@ def _create_client_options(msg: TrpcMessage) -> Options: opts.selector = TrpcSelector() opts.endpoint = msg.callee_service_name opts.serialization_type = SerializationType.PB - opts.compress_type = CompressType.Noop + opts.compress_type = CompressType.NOOP return opts @@ -605,8 +604,7 @@ def _update_namespace_of_option(msg: TrpcMessage, opts: Options): opts.selector_options.set_src_setname(msg.set_name) -def normalize_options( - options: Optional[Union[Options, Callable, Sequence]] = None) -> List[Callable]: +def normalize_options(options: Optional[Union[Options, Callable, Sequence]] = None) -> List[Callable]: """Normalize user options into a list of callables. Accepts a single :class:`Options`, a single callable, a sequence of either, diff --git a/trpc_sdk/client/_utils.py b/trpc_sdk/client/_utils.py new file mode 100644 index 0000000..625a700 --- /dev/null +++ b/trpc_sdk/client/_utils.py @@ -0,0 +1,143 @@ +# Tencent is pleased to support the open source community by making tRPC-Python available. +# +# Copyright (C) 2026 Tencent. All rights reserved. +# +# tRPC-Python is licensed under Apache-2.0. +"""Client utility module.""" + +from __future__ import annotations + +from trpc_sdk.abc import Node +from trpc_sdk.abc import TrpcContext +from trpc_sdk.abc import TrpcMessage +from trpc_sdk.config import SocketType +from trpc_sdk.exceptions import ClientRouteError +from trpc_sdk.exceptions import ClientTimeoutError +from trpc_sdk.exceptions import UnknownError +from trpc_sdk.log import logger +from trpc_sdk.naming import get_selector +from trpc_sdk.transport import ClientTimeoutReason + +from ._options import Options + + +def update_message(msg: TrpcMessage, opts: Options) -> None: + """Copy caller-facing option fields onto the outbound message. + + Covers metadata, caller service name, serialization / compress types, + and optional custom request / response heads. ``req_head`` replaces + the codec request head; ``rsp_head`` is a caller-owned buffer that + the codec fills with the backend response head. + + Args: + msg: Outbound client message to mutate. + opts: Per-call options already assembled by :func:`get_options`. + """ + if opts.metadata: + meta_data = msg.client_meta_data or {} + meta_data.update(opts.metadata) + msg.set_client_meta_data(meta_data) + + if opts.caller_service_name: + msg.set_caller_service_name(opts.caller_service_name) + + if opts.serialization_type >= 0: + msg.set_serialization_type(opts.serialization_type) + + if opts.compress_type >= 0: + msg.set_compress_type(opts.compress_type) + + if opts.req_head: + msg.set_client_req_head(opts.req_head) + if opts.rsp_head: + msg.set_client_rsp_head(opts.rsp_head) + + +async def select_node(msg: TrpcMessage, opts: Options) -> Node: + """Resolve the downstream node and copy its address onto ``msg``. + + Unix-socket calls rewrite ``opts.target`` first. An explicit + ``target`` of the form ``scheme://endpoint`` overrides the default + Polar selector. + + Args: + msg: Outbound message; remote address and env transfer are set. + opts: Per-call options; selector and endpoint may be replaced. + + Returns: + The selected :class:`~trpc_sdk.abc.Node`. + + Raises: + ClientRouteError: ``target`` has no ``scheme://endpoint``, or + the selector returned no addressable node. + UnknownError: ``opts.selector`` is missing. + """ + if opts.socket_type == SocketType.UNIX: + opts.target = "ip://" + opts.unix_path + ":0" + + if opts.target: + targets = opts.target.split("://") + if len(targets) != 2: + raise ClientRouteError("Client select node target schema invalid") + opts.selector = get_selector(targets[0]) + opts.endpoint = targets[1] + + if not opts.selector: + raise UnknownError("Client select node selector not exist") + + logger.debug("%s|select node", opts.endpoint) + node = await opts.selector.select(opts.endpoint, opts.selector_options) + logger.debug("%s|select end node=%s", opts.endpoint, node) + + if node is None or not node.address: + raise ClientRouteError("cannot find downstream node") + + opts.load_node_config(node) + opts.call_options.set_endpoint(opts.endpoint) + + msg.set_remote_addr(node.address) + msg.set_callee_container_name(node.container_name) + if len(msg.env_transfer) == 0: + msg.set_env_transfer(node.env_key) + + return node + + +def set_timeout(ctx: TrpcContext, msg: TrpcMessage, opts: Options, begin: int) -> ClientTimeoutReason: + """Apply the tighter of the client timeout and the server deadline. + + When the client deadline is sooner (or the server set none), a later + timeout is blamed on the downstream and reported to the selector as + :attr:`~trpc_sdk.transport.ClientTimeoutReason.DOWNSTREAM_TIMEOUT`. When + the server deadline is sooner, the timeout is + :attr:`~trpc_sdk.transport.ClientTimeoutReason.CURRENT_SERVICE_TIMEOUT` + and is not treated as downstream failure. + + Args: + ctx: Request context; ``deadline`` and ``timeout`` are updated. + msg: Outbound message; remaining timeout is written for the peer. + opts: Per-call options; ``timeout`` is in milliseconds. + begin: ``now_ms()`` at the start of this attempt. + + Returns: + Which side should be blamed if this call times out. + + Raises: + ClientTimeoutError: Remaining time is already negative. + """ + timeout_reason = ClientTimeoutReason.DOWNSTREAM_TIMEOUT + if opts.timeout > 0: + client_deadline = begin + opts.timeout + if client_deadline < ctx.deadline or ctx.deadline == 0: + ctx.deadline = client_deadline + ctx.timeout = opts.timeout + else: + ctx.timeout = ctx.deadline - begin + timeout_reason = ClientTimeoutReason.CURRENT_SERVICE_TIMEOUT + if ctx.timeout < 0: + raise ClientTimeoutError("client reach deadline") + msg.set_timeout(ctx.timeout) + else: + ctx.timeout = 0 + + return timeout_reason diff --git a/trpc_sdk/codec/__init__.py b/trpc_sdk/codec/__init__.py index 5fc46d7..71d294d 100644 --- a/trpc_sdk/codec/__init__.py +++ b/trpc_sdk/codec/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """tRPC-Python codec package: what a frame means, not how it travels. Public symbols are re-exported here. Implementation lives in ``_``-prefixed @@ -11,8 +10,10 @@ The package is split by responsibility: -- :mod:`~trpc_sdk.codec._codec` — Python ``TrpcClientCodec`` / ``TrpcServerCodec`` plugins (``BaseCodec`` subclasses) that - hold a unary and a stream Cython codec and dispatch between them; the server INIT meta cache lives here +- :mod:`~trpc_sdk.codec._codec` — Python ``TrpcClientCodec`` / + ``TrpcServerCodec`` plugins (``BaseCodec`` subclasses) that hold a unary + and a stream Cython codec and dispatch between them; the server INIT meta + cache lives here - :mod:`~trpc_sdk.codec._cython._codec` / :mod:`~trpc_sdk.codec._cython._codec_stream` — private Cython unary / stream codecs, both derived from the C-level ``_Codec`` root in :mod:`trpc_sdk.abc` - :mod:`~trpc_sdk.codec._cython._codec_parser` — TCP sticky-packet splitter (``TrpcServerProtocolParser``) diff --git a/trpc_sdk/codec/_codec.py b/trpc_sdk/codec/_codec.py index 29a95c4..fa971d3 100644 --- a/trpc_sdk/codec/_codec.py +++ b/trpc_sdk/codec/_codec.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Unary/stream dispatch layer for the ``"trpc"`` codec plugins. ``TrpcClientCodec`` and ``TrpcServerCodec`` own no packing logic of their own. diff --git a/trpc_sdk/codec/_constants.py b/trpc_sdk/codec/_constants.py index bff6fa6..6b5fc56 100644 --- a/trpc_sdk/codec/_constants.py +++ b/trpc_sdk/codec/_constants.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Shared constants for the codec package. Frame-head length and ``trans_info`` keys are the single source for @@ -16,8 +15,7 @@ from __future__ import annotations - -# tRPC wire frame head (stx + type + state + package_len + head_len + +# tRPC wire frame head (magic + type + state + package_len + head_len + # stream_id + reserved). Not the transport IPC envelope, which is 6 bytes. FRAME_HEAD_LEN = 16 diff --git a/trpc_sdk/codec/_cython/__init__.py b/trpc_sdk/codec/_cython/__init__.py index 4026e63..e17d90d 100644 --- a/trpc_sdk/codec/_cython/__init__.py +++ b/trpc_sdk/codec/_cython/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Cython unary/stream codecs and the TCP frame parser. The ``_``-prefixed codec types are framework internals used only by diff --git a/trpc_sdk/codec/_cython/_codec.pyi b/trpc_sdk/codec/_cython/_codec.pyi index c6a9688..61b44de 100644 --- a/trpc_sdk/codec/_cython/_codec.pyi +++ b/trpc_sdk/codec/_cython/_codec.pyi @@ -3,11 +3,11 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Type hints for the unary Cython client / server codec. Python :class:`~trpc_sdk.codec.TrpcClientCodec` / ``TrpcServerCodec`` hold one -instance each as ``self.codec`` and dispatch unary frames here. Stream frames use :mod:`trpc_sdk.codec._cython._codec_stream`. +instance each as ``self.codec`` and dispatch unary frames here. Stream +frames use :mod:`trpc_sdk.codec._cython._codec_stream`. """ from __future__ import annotations diff --git a/trpc_sdk/codec/_cython/_codec_parser.pyi b/trpc_sdk/codec/_cython/_codec_parser.pyi index 8f72dee..b97ccea 100644 --- a/trpc_sdk/codec/_cython/_codec_parser.pyi +++ b/trpc_sdk/codec/_cython/_codec_parser.pyi @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Type hints for the length-only tRPC frame splitter. ``TrpcServerProtocolParser`` checks magic ``2352`` and ``package_len`` diff --git a/trpc_sdk/codec/_cython/_codec_parser.pyx b/trpc_sdk/codec/_cython/_codec_parser.pyx index eb2eb0e..495518a 100644 --- a/trpc_sdk/codec/_cython/_codec_parser.pyx +++ b/trpc_sdk/codec/_cython/_codec_parser.pyx @@ -39,7 +39,7 @@ from trpc_sdk.exceptions import ServerDecodeError cdef uint16_t TRPC_MAGIC_VALUE = 2352 -cdef uint32_t FRAME_HEAD_LEN = 16 +cdef int FRAME_HEAD_LEN = 16 cdef class TrpcServerProtocolParser(BaseServerProtocolParser): @@ -100,13 +100,13 @@ cdef class TrpcServerProtocolParser(BaseServerProtocolParser): results = [] cdef int scan_end = 0 - cdef uint16_t stx = 0 + cdef uint16_t magic = 0 cdef uint32_t package_len = 0 while self.length >= scan_end+FRAME_HEAD_LEN: - stx = ntohs(dereference((self.buf+scan_end))) + magic = ntohs(dereference((self.buf+scan_end))) - if stx != TRPC_MAGIC_VALUE: + if magic != TRPC_MAGIC_VALUE: raise ServerDecodeError("framer head magic not match") package_len = ntohl(dereference((self.buf+4+scan_end))) diff --git a/trpc_sdk/codec/_cython/_codec_stream.pyi b/trpc_sdk/codec/_cython/_codec_stream.pyi index 55db4fd..4ce2845 100644 --- a/trpc_sdk/codec/_cython/_codec_stream.pyi +++ b/trpc_sdk/codec/_cython/_codec_stream.pyi @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Type hints for the stream-frame Cython client / server codec. Python :class:`~trpc_sdk.codec.TrpcClientCodec` / ``TrpcServerCodec`` hold one diff --git a/trpc_sdk/codec/_cython/_codec_stream.pyx b/trpc_sdk/codec/_cython/_codec_stream.pyx index b22d63c..5588ec7 100644 --- a/trpc_sdk/codec/_cython/_codec_stream.pyx +++ b/trpc_sdk/codec/_cython/_codec_stream.pyx @@ -443,7 +443,7 @@ cdef class _TrpcServerStreamCodec(_Codec): init_meta.content_type = message.serialization_type init_meta.content_encoding = message.compress_type rsp_meta = trpc_pb2.TrpcStreamInitResponseMeta() - + err = message.server_rsp_err rsp_meta.error_msg = err.msg.encode('utf8') if err.type == TrpcErrorType.BUSINESS: @@ -546,7 +546,7 @@ cdef class _TrpcServerStreamCodec(_Codec): message.set_server_rpc_name(req.func.decode('utf8')) message.set_compress_type(init_meta.content_encoding) - message.set_serialization_type(init_meta.content_type) + message.set_serialization_type(init_meta.content_type) message.set_dyeing((req.message_type & trpc_pb2.TRPC_DYEING_MESSAGE) != 0) # Parse tracing metadata and store it on the msg. @@ -615,7 +615,7 @@ cdef class _TrpcServerStreamCodec(_Codec): feedback.ParseFromString(body[FRAME_HEAD_LEN:]) message.set_stream_frame(feedback) return b'' - + cpdef bytes _common_pack(TrpcFrameHead frame_head, bytes body): """Hand-pack a stream frame: 16-byte head plus body, ``head_len`` = 0. diff --git a/trpc_sdk/codec/_factory.py b/trpc_sdk/codec/_factory.py index dd48c11..2be1ca9 100644 --- a/trpc_sdk/codec/_factory.py +++ b/trpc_sdk/codec/_factory.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Plugin factories, protocol parsers, and codec lookups for tRPC. Importing this module registers the ``"trpc"`` entries for @@ -38,7 +37,7 @@ from ._cython import TrpcServerProtocolParser if TYPE_CHECKING: - from trpc_sdk.transport import PooledConnection + from trpc_sdk.transport import Connection class TrpcServerParserFactory(BasePluginFactory): @@ -77,7 +76,7 @@ def get_server_parser(name: str) -> Optional[TrpcServerParserFactory]: class TrpcClientParser(BaseClientProtocolParser): """Read one complete tRPC frame off a pooled client connection.""" - async def read_frame(self, conn: PooledConnection) -> bytes: + async def read_frame(self, conn: Connection) -> bytes: """Read the 16-byte head, then the rest of the frame. Args: @@ -87,7 +86,7 @@ async def read_frame(self, conn: PooledConnection) -> bytes: The complete frame, head included. Raises: - ClientDecodeError: ``stx`` is not ``trpc_pb2.TRPC_MAGIC_VALUE``. The + ClientDecodeError: ``magic`` is not ``trpc_pb2.TRPC_MAGIC_VALUE``. The connection is closed first because the stream can no longer be resynchronized. """ @@ -95,7 +94,7 @@ async def read_frame(self, conn: PooledConnection) -> bytes: frame_head: TrpcFrameHead = parse_frame_head(frame_head_buff) - if frame_head.stx != trpc_pb2.TRPC_MAGIC_VALUE: + if frame_head.magic != trpc_pb2.TRPC_MAGIC_VALUE: conn.close(True) report_attr("trpc_codec_invalid_magic_number", 1) raise ClientDecodeError("invalid magic number") diff --git a/trpc_sdk/codec/_types.py b/trpc_sdk/codec/_types.py index dbc9bb5..826aadd 100644 --- a/trpc_sdk/codec/_types.py +++ b/trpc_sdk/codec/_types.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Shared type definitions for the codec package.""" from __future__ import annotations diff --git a/trpc_sdk/codec/_utils.py b/trpc_sdk/codec/_utils.py index df026fc..c211d8e 100644 --- a/trpc_sdk/codec/_utils.py +++ b/trpc_sdk/codec/_utils.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Attachment accessors for the raw bytes carried after a tRPC body. The attachment accessors are the public read/write path for the raw diff --git a/trpc_sdk/common/__init__.py b/trpc_sdk/common/__init__.py index d3232c1..5169ca1 100644 --- a/trpc_sdk/common/__init__.py +++ b/trpc_sdk/common/__init__.py @@ -16,7 +16,6 @@ from ._process_hook import execute_before_in_parent from ._process_hook import execute_after_in_parent from ._process_hook import execute_after_in_child -from ._process_hook import execute_before_loop_run_in_child from ._process_helper import ProcessType from ._process_helper import bind_lifetime_to_parent from ._process_helper import is_task_process @@ -39,7 +38,6 @@ "execute_before_in_parent", "execute_after_in_parent", "execute_after_in_child", - "execute_before_loop_run_in_child", "ProcessType", "bind_lifetime_to_parent", "is_task_process", diff --git a/trpc_sdk/common/_maxprocs.py b/trpc_sdk/common/_maxprocs.py index 11ec007..5c730b5 100644 --- a/trpc_sdk/common/_maxprocs.py +++ b/trpc_sdk/common/_maxprocs.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Container-aware CPU count. On Linux the CPU quota is read from the cgroup the current process belongs diff --git a/trpc_sdk/common/_process_helper.py b/trpc_sdk/common/_process_helper.py index 2b647cd..3f207f9 100644 --- a/trpc_sdk/common/_process_helper.py +++ b/trpc_sdk/common/_process_helper.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Process role stamps and parent-death binding. :class:`trpc_sdk.abc.ProcessType` is the single source of truth for process diff --git a/trpc_sdk/common/_process_hook.py b/trpc_sdk/common/_process_hook.py index ed96d30..caf28c9 100644 --- a/trpc_sdk/common/_process_hook.py +++ b/trpc_sdk/common/_process_hook.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Fork hook list""" from __future__ import annotations @@ -30,12 +29,12 @@ def register_child_callback(cb: Union[HookType, List[HookType]], type: ProcessType): """Register callback in child - + Args: cb: The callback to register type: The type of process to register the callback for """ - global _child_cbs + global _child_cbs # noqa: F824 if type not in _child_cbs: _child_cbs[type] = [] if isinstance(cb, list): @@ -46,20 +45,20 @@ def register_child_callback(cb: Union[HookType, List[HookType]], type: ProcessTy def get_child_callback(type: ProcessType) -> List[Callable[[], None]]: """Get callback in child - + Args: type: The type of process to get the callback for Returns: The callback list """ - global _child_cbs + global _child_cbs # noqa: F824 return _child_cbs.get(type, []) @unique class ProcessHookType(Enum): """The type of hook - + Attributes: BEFORE_FORK_IN_PARENT: The hook before fork in parent AFTER_FORK_IN_PARENT: The hook after fork in parent @@ -75,7 +74,7 @@ class ProcessHookType(Enum): def _save_process_hooks(hook_type: ProcessHookType, hook: Optional[HookType] = None): """Save hook - + Args: hook_type: The type of hook hook: The hook to save, default is None @@ -88,7 +87,7 @@ def register_at_fork(before: Optional[HookType] = None, after_in_parent: Optional[HookType] = None, after_in_child: Optional[HookType] = None): """Register hook at fork - + Args: before: The callback before fork in parent after_in_parent: The callback after fork in parent @@ -101,7 +100,7 @@ def register_at_fork(before: Optional[HookType] = None, def _execute_process_hook(hook_type: ProcessHookType): """Execute hook - + Args: hook_type: The type of hook """ @@ -120,7 +119,7 @@ def execute_before_in_parent(): def execute_after_in_parent(): """Execute process after in parent - + Must call after fork in parent """ _execute_process_hook(ProcessHookType.AFTER_FORK_IN_PARENT) @@ -128,11 +127,11 @@ def execute_after_in_parent(): def execute_after_in_child(): """Execute fork after in child - + Must call after fork in child """ _execute_process_hook(ProcessHookType.AFTER_FORK_IN_CHILD) - global _child_cbs + global _child_cbs # noqa: F824 if is_task_process(): cbs = _child_cbs.get(ProcessType.TASK, []) for cb in cbs: @@ -141,26 +140,3 @@ def execute_after_in_child(): cbs = _child_cbs.get(ProcessType.WORKER, []) for cb in cbs: cb() - - -_before_loop_run_in_child_hooks: List[HookType] = [] - - -def register_before_loop_run_in_child(hook: HookType) -> None: - """Register a hook that runs in the child after plugins, before the loop. - - Args: - hook: Zero-argument callback invoked by - :func:`execute_before_loop_run_in_child`. - """ - _before_loop_run_in_child_hooks.append(hook) - - -def execute_before_loop_run_in_child() -> None: - """Run child hooks after plugin init and before ``loop.run_forever()``. - - Must be called in the child after ``_init_plugins()``. With no - registrations the hook list is empty and this is a no-op. - """ - for hook in _before_loop_run_in_child_hooks: - hook() diff --git a/trpc_sdk/compressor/__init__.py b/trpc_sdk/compressor/__init__.py index af3f420..9a181d6 100644 --- a/trpc_sdk/compressor/__init__.py +++ b/trpc_sdk/compressor/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """tRPC-Python compressor package: ContentEncoding plugins and lookups. Public symbols are re-exported here. Implementation lives in ``_``-prefixed @@ -14,7 +13,7 @@ - :mod:`~trpc_sdk.compressor._types` — ``CompressType`` ContentEncoding codes - :mod:`~trpc_sdk.compressor._compressor` — built-in gzip / zlib / snappy plugins - :mod:`~trpc_sdk.compressor._utils` — ``compress`` / ``decompress`` / ``get_compress`` -- :mod:`~trpc_sdk.compressor._constants` — ``CompressCode`` wire values +- :mod:`~trpc_sdk.compressor._constants` — ``CompressType`` wire values Importing this package registers every built-in compressor. """ @@ -26,7 +25,7 @@ from ._compressor import CompressSnappy from ._compressor import CompressStreamSnappy from ._compressor import CompressZlib -from ._types import CompressType +from ._constants import CompressType from ._utils import compress from ._utils import decompress from ._utils import get_compress diff --git a/trpc_sdk/compressor/_compressor.py b/trpc_sdk/compressor/_compressor.py index be88f54..8edefdb 100644 --- a/trpc_sdk/compressor/_compressor.py +++ b/trpc_sdk/compressor/_compressor.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Built-in ContentEncoding plugin implementations. Importing this module (which :mod:`trpc_sdk.compressor` does) registers @@ -26,12 +25,12 @@ from trpc_sdk.abc import PluginInitPos from trpc_sdk.abc import PluginType from trpc_sdk.plugin import register_plugin -from ._types import CompressType +from ._constants import CompressType -@register_plugin(PluginType.COMPRESS, CompressType.Noop, init_pos=PluginInitPos.WORKER) +@register_plugin(PluginType.COMPRESS, CompressType.NOOP, init_pos=PluginInitPos.WORKER) class CompressNoop(BaseCompress): - """Identity compressor registered as ``CompressType.Noop``. + """Identity compressor registered as ``CompressType.NOOP``. Empty or non-empty input is returned unchanged. Used when the frame head says the body is already raw bytes. @@ -54,9 +53,9 @@ def decompress(self, data: bytes) -> bytes: return data -@register_plugin(PluginType.COMPRESS, CompressType.Gzip, init_pos=PluginInitPos.WORKER) +@register_plugin(PluginType.COMPRESS, CompressType.GZIP, init_pos=PluginInitPos.WORKER) class CompressGZip(BaseCompress): - """gzip compressor registered as ``CompressType.Gzip``. + """gzip compressor registered as ``CompressType.GZIP``. Empty input is returned as-is so a zero-length body does not become a gzip header-only blob. @@ -83,9 +82,9 @@ def decompress(self, data: bytes) -> bytes: return gzip.decompress(data) -@register_plugin(PluginType.COMPRESS, CompressType.ZLib, init_pos=PluginInitPos.WORKER) +@register_plugin(PluginType.COMPRESS, CompressType.ZLIB, init_pos=PluginInitPos.WORKER) class CompressZlib(BaseCompress): - """zlib compressor registered as ``CompressType.ZLib``. + """zlib compressor registered as ``CompressType.ZLIB``. Empty input is returned as-is so a zero-length body does not become a zlib header-only blob. @@ -112,13 +111,13 @@ def decompress(self, data: bytes) -> bytes: return zlib.decompress(data) -@register_plugin(PluginType.COMPRESS, CompressType.Snappy, init_pos=PluginInitPos.WORKER) +@register_plugin(PluginType.COMPRESS, CompressType.SNAPPY, init_pos=PluginInitPos.WORKER) class CompressSnappy(BaseCompress): - """Block-mode snappy compressor registered as ``CompressType.Snappy``. + """Block-mode snappy compressor registered as ``CompressType.SNAPPY``. ``python-snappy`` is imported on first use so processes that never send or receive snappy frames do not need the optional dependency. - The same class is also registered as ``CompressType.SnappyBlock``. + The same class is also registered as ``CompressType.SNAPPY_BLOCK``. """ def __init__(self) -> None: @@ -165,12 +164,12 @@ def decompress(self, data: bytes) -> bytes: # SnappyBlock (5) uses the same block implementation as the deprecated # Snappy (2); both codes stay registered so either value decodes. -register_plugin(PluginType.COMPRESS, CompressType.SnappyBlock, init_pos=PluginInitPos.WORKER)(CompressSnappy) +register_plugin(PluginType.COMPRESS, CompressType.SNAPPY_BLOCK, init_pos=PluginInitPos.WORKER)(CompressSnappy) -@register_plugin(PluginType.COMPRESS, CompressType.SnappyStream, init_pos=PluginInitPos.WORKER) +@register_plugin(PluginType.COMPRESS, CompressType.SNAPPY_STREAM, init_pos=PluginInitPos.WORKER) class CompressStreamSnappy(CompressSnappy): - """Stream-mode snappy compressor registered as ``CompressType.SnappyStream``. + """Stream-mode snappy compressor registered as ``CompressType.SNAPPY_STREAM``. ``snappy.stream_compress`` / ``stream_decompress`` take file-like objects, so this subclass wraps the body in ``BytesIO`` rather than diff --git a/trpc_sdk/compressor/_constants.py b/trpc_sdk/compressor/_constants.py index 8a26fb6..b8b32ba 100644 --- a/trpc_sdk/compressor/_constants.py +++ b/trpc_sdk/compressor/_constants.py @@ -3,10 +3,9 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Shared constants for the compressor package. -:class:`CompressCode` (ContentEncoding) feeds +:class:`CompressType` (ContentEncoding) feeds :class:`~trpc_sdk.compressor._types.CompressType`. Values match ``TrpcCompressType`` in ``trpc.proto``. """ @@ -16,21 +15,23 @@ from enum import IntEnum from enum import unique +from trpc_sdk._inner.pb import trpc_pb2 + @unique -class CompressCode(IntEnum): +class CompressType(IntEnum): """ContentEncoding codes accepted by the compress plugin table. Members are the wire values, so they can be written into a frame head and compared against a decoded ``content_encoding`` without a cast. """ - NOOP = 0 - GZIP = 1 - SNAPPY = 2 - ZLIB = 3 - SNAPPY_STREAM = 4 - SNAPPY_BLOCK = 5 - LZ4_FRAME = 6 - LZ4_BLOCK = 7 - ZSTD = 8 + NOOP = trpc_pb2.TRPC_DEFAULT_COMPRESS + GZIP = trpc_pb2.TRPC_GZIP_COMPRESS + SNAPPY = trpc_pb2.TRPC_SNAPPY_COMPRESS + ZLIB = trpc_pb2.TRPC_ZLIB_COMPRESS + SNAPPY_STREAM = trpc_pb2.TRPC_SNAPPY_STREAM_COMPRESS + SNAPPY_BLOCK = trpc_pb2.TRPC_SNAPPY_BLOCK_COMPRESS + LZ4_FRAME = trpc_pb2.TRPC_LZ4_FRAME_COMPRESS + LZ4_BLOCK = trpc_pb2.TRPC_LZ4_BLOCK_COMPRESS + ZSTD = trpc_pb2.TRPC_ZSTD_COMPRESS diff --git a/trpc_sdk/compressor/_types.py b/trpc_sdk/compressor/_types.py deleted file mode 100644 index 8f9331a..0000000 --- a/trpc_sdk/compressor/_types.py +++ /dev/null @@ -1,25 +0,0 @@ -# Tencent is pleased to support the open source community by making tRPC-Python available. -# -# Copyright (C) 2026 Tencent. All rights reserved. -# -# tRPC-Python is licensed under Apache-2.0. - -"""Shared type definitions for the compressor package.""" - -from __future__ import annotations - -from ._constants import CompressCode - - -class CompressType: - """ContentEncoding codes, aligned with ``TrpcCompressType`` in ``trpc.proto``.""" - - Noop = CompressCode.NOOP - Gzip = CompressCode.GZIP - Snappy = CompressCode.SNAPPY - ZLib = CompressCode.ZLIB - SnappyStream = CompressCode.SNAPPY_STREAM - SnappyBlock = CompressCode.SNAPPY_BLOCK - Lz4Frame = CompressCode.LZ4_FRAME - Lz4Block = CompressCode.LZ4_BLOCK - Zstd = CompressCode.ZSTD diff --git a/trpc_sdk/compressor/_utils.py b/trpc_sdk/compressor/_utils.py index b4d004a..f7706a7 100644 --- a/trpc_sdk/compressor/_utils.py +++ b/trpc_sdk/compressor/_utils.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Plugin lookups and body compress helpers. ``get_compress`` is a thin plugin-table lookup. Built-in compressors diff --git a/trpc_sdk/config/__init__.py b/trpc_sdk/config/__init__.py index cb63bd2..e8e2331 100644 --- a/trpc_sdk/config/__init__.py +++ b/trpc_sdk/config/__init__.py @@ -45,8 +45,6 @@ from ._exceptions import GetConfigKeyError from ._loader import ConfigLoader from ._loader import ConfigLoaderFactory -from ._options import with_codec -from ._options import with_provider from ._parser import TrpcConfigParser from ._provider import FileConfigProvider from ._types import Admin @@ -90,8 +88,6 @@ # config loading "ConfigLoader", "ConfigLoaderFactory", - "with_codec", - "with_provider", # Exceptions "ConfigError", "GetConfigKeyError", diff --git a/trpc_sdk/config/_config.py b/trpc_sdk/config/_config.py index 4aa47f9..ccd130e 100644 --- a/trpc_sdk/config/_config.py +++ b/trpc_sdk/config/_config.py @@ -67,8 +67,7 @@ def load(cls, config_path: str, file_code: str = "utf-8") -> Config: Returns: The configuration that was just loaded. """ - cls._config_parser = TrpcConfigParser('file', 'yaml', {'file_path': config_path}, - {'code': file_code}) + cls._config_parser = TrpcConfigParser('file', 'yaml', {'file_path': config_path}, {'code': file_code}) # The parser retains the decoded dictionary for lookup and deserializing. cls._config_parser.load() if cls._config_parser.get('client') is not None: @@ -103,7 +102,7 @@ def parse_client_config(cls, config_parser: TrpcConfigParser) -> None: cls.set_client_service_configs(client_service_config) - if client_config.filters is not None: + if client_config.filters: cls._fallback_client_config.filters = client_config.filters if client_config.timeout > 0: diff --git a/trpc_sdk/config/_decoder.py b/trpc_sdk/config/_decoder.py index c3f2636..6de6c22 100644 --- a/trpc_sdk/config/_decoder.py +++ b/trpc_sdk/config/_decoder.py @@ -8,7 +8,7 @@ Decoders turn the raw bytes returned by a data provider into a Python object, usually a ``dict``. They are registered as ``CONFIG_DECODER`` plugins and are selected by name through :class:`~trpc_sdk.config._parser.TrpcConfigParser` or -:func:`~trpc_sdk.config._options.with_codec`. +:func:`~trpc_sdk.config.ConfigLoaderFactory.sync_load`. The ``code`` decoder option selects the text encoding of the raw bytes and defaults to ``utf8``. @@ -41,10 +41,10 @@ def set_options(self, options: Dict) -> None: def _resolve_encoding(self, options: Optional[dict]) -> str: """Read the text encoding from the decoder options. - + Args: options: Decoder options, may be ``None``. - + Returns: The configured encoding, or ``utf8`` when unset. """ diff --git a/trpc_sdk/config/_loader.py b/trpc_sdk/config/_loader.py index 443f114..7106115 100644 --- a/trpc_sdk/config/_loader.py +++ b/trpc_sdk/config/_loader.py @@ -42,13 +42,11 @@ :mod:`trpc_sdk.config._options`:: 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("YamlDecoder"), + provider="file", + decoder="YamlDecoder", ) server_config = loader.get("server", {}) @@ -67,9 +65,12 @@ from trpc_sdk.abc import BaseConfigProvider from trpc_sdk.abc import BaseConfigDecoder +from trpc_sdk.abc import PluginType from trpc_sdk.common import get_or_create_event_loop +from trpc_sdk.plugin import get_plugin -from ._exceptions import ConfigError +from ._exceptions import ConfigDecoderError +from ._exceptions import ProviderNotExist class ConfigLoader: @@ -185,15 +186,14 @@ class ConfigLoaderFactory: """Build configured loaders through composable option functions. The factory has no instance state. Use its class methods with options such - as :func:`~trpc_sdk.config.with_provider` and - :func:`~trpc_sdk.config.with_codec`. + as :func:`~trpc_sdk.config.ConfigLoaderFactory.sync_load`. """ def __init__(self) -> None: raise TypeError("ConfigLoaderFactory only exposes classmethod; call it on the class.") @classmethod - def create(cls, path: str, *options: Callable) -> ConfigLoader: + def create(cls, path: str, decoder: str = "", provider: str = "") -> ConfigLoader: """Create a configured loader without reading the resource. Options are applied in the order provided. A valid loader requires @@ -203,46 +203,51 @@ def create(cls, path: str, *options: Callable) -> ConfigLoader: Args: path: Path (or key) identifying the config within the provider. options: Options such as - :func:`~trpc_sdk.config._options.with_provider` / - :func:`~trpc_sdk.config._options.with_codec`. + :func:`~trpc_sdk.config.ConfigLoaderFactory.sync_load`. Returns: A ready-to-load config loader. - - Raises: - ConfigError: If no decoder or no provider was selected. """ config = ConfigLoader(path) - for option in options: - option(config) + decoder_instance = cls._get_decoder(decoder) + config.set_decoder(decoder_instance) + provider_instance = cls._get_provider(provider) + config.set_provider(provider_instance) - if config._decoder is None: - raise ConfigError(f'No decoder selected for config {path}') + return config - if config._provider is None: - raise ConfigError(f'No data provider selected for config {path}') + @classmethod + def _get_decoder(cls, decoder: str) -> BaseConfigDecoder: + decoder_instance = get_plugin(PluginType.CONFIG_DECODER, decoder) + if decoder_instance is None: + raise ConfigDecoderError(decoder) + return decoder_instance - return config + @classmethod + def _get_provider(cls, provider: str) -> BaseConfigProvider: + provider_instance = get_plugin(PluginType.CONFIG_PROVIDER, provider) + if provider_instance is None: + raise ProviderNotExist(provider) + return provider_instance @classmethod - async def load(cls, path: str, *options: Callable) -> ConfigLoader: + async def load(cls, path: str, decoder: str = "", provider: str = "") -> ConfigLoader: """Create a loader and asynchronously load its configuration. Args: path: Path (or key) identifying the config within the provider. - options: Options such as - :func:`~trpc_sdk.config._options.with_provider` / - :func:`~trpc_sdk.config._options.with_codec`. + decoder: Registered ``CONFIG_DECODER`` plugin name. + provider: Registered ``CONFIG_PROVIDER`` plugin name. Returns: The loaded config loader. """ - config_loader = cls.create(path, *options) + config_loader = cls.create(path, decoder, provider) await config_loader.load() return config_loader @classmethod - def sync_load(cls, path: str, *options: Callable) -> ConfigLoader: + def sync_load(cls, path: str, decoder: str = "", provider: str = "") -> ConfigLoader: """Create and load a configuration from synchronous application code. This method runs :meth:`load` on the current event loop and returns the @@ -251,11 +256,10 @@ def sync_load(cls, path: str, *options: Callable) -> ConfigLoader: Args: path: Path (or key) identifying the config within the provider. - options: Options such as - :func:`~trpc_sdk.config._options.with_provider` / - :func:`~trpc_sdk.config._options.with_codec`. + decoder: Registered ``CONFIG_DECODER`` plugin name. + provider: Registered ``CONFIG_PROVIDER`` plugin name. Returns: The loaded config loader. """ - return get_or_create_event_loop().run_until_complete(cls.load(path, *options)) + return get_or_create_event_loop().run_until_complete(cls.load(path, decoder, provider)) diff --git a/trpc_sdk/config/_options.py b/trpc_sdk/config/_options.py deleted file mode 100644 index fb8dc13..0000000 --- a/trpc_sdk/config/_options.py +++ /dev/null @@ -1,69 +0,0 @@ -# Tencent is pleased to support the open source community by making tRPC-Python available. -# -# Copyright (C) 2026 Tencent. All rights reserved. -# -# tRPC-Python is licensed under Apache-2.0. -"""Option builders for :class:`~trpc_sdk.config.ConfigLoader`. - -These ``with_*`` helpers are passed to -:meth:`~trpc_sdk.config.ConfigLoaderFactory.create` (and the load wrappers) -to select a decoder or data provider:: - - from trpc_sdk.config import ConfigLoaderFactory, with_codec, with_provider - - cfg = ConfigLoaderFactory.sync_load( - "my.yaml", with_provider("file"), with_codec("YamlDecoder") - ) -""" - -from __future__ import annotations - -from typing import Callable - -from trpc_sdk.abc import PluginType -from trpc_sdk.plugin import get_plugin - -from ._exceptions import ConfigDecoderError -from ._exceptions import ProviderNotExist -from ._loader import ConfigLoader - - -def with_codec(name: str) -> Callable: - """Build an option selecting the decoder plugin to use. - - Args: - name: Registered ``CONFIG_DECODER`` plugin name. - - Returns: - An option callable accepted by - :meth:`~trpc_sdk.config.ConfigLoaderFactory.create`. - """ - - def option(config: ConfigLoader) -> None: - decoder = get_plugin(PluginType.CONFIG_DECODER, name) - if decoder is None: - raise ConfigDecoderError(name) - config.set_decoder(decoder) - - return option - - -def with_provider(name: str) -> Callable: - """Build an option selecting the data provider to use. - - Args: - name: Data provider name registered via ``set_provider``. - - Returns: - An option callable accepted by - :meth:`~trpc_sdk.config.ConfigLoaderFactory.create`. - """ - - def option(config: ConfigLoader) -> None: - - provider = get_plugin(PluginType.CONFIG_PROVIDER, name) - if provider is None: - raise ProviderNotExist(name) - config.set_provider(provider) - - return option diff --git a/trpc_sdk/config/_provider.py b/trpc_sdk/config/_provider.py index 06d1b6b..4626d2d 100644 --- a/trpc_sdk/config/_provider.py +++ b/trpc_sdk/config/_provider.py @@ -8,9 +8,9 @@ Providers load raw config bytes from a data source. They are registered as ``CONFIG_PROVIDER`` plugins and are selected by name through :class:`~trpc_sdk.config._parser.TrpcConfigParser` or -:func:`~trpc_sdk.config._options.with_provider`. +:func:`~trpc_sdk.config.ConfigLoaderFactory.sync_load`. -Named providers used by :func:`~trpc_sdk.config._options.with_provider` are kept in +Named providers used by :func:`~trpc_sdk.config.ConfigLoaderFactory.sync_load` are kept in this module's registry via :func:`set_provider` / :func:`get_provider`. """ @@ -33,7 +33,7 @@ class FileConfigProvider(BaseConfigProvider): This provider is reachable under three different names: the class itself, the ``'FileConfigProvider'`` plugin name used by :class:`TrpcConfigParser`, and the - ``'file'`` key via ``set_provider`` used by ``with_provider('file')``. + ``'file'`` key via ``set_provider`` used by ``ConfigLoaderFactory.sync_load(provider='file')``. """ def __init__(self): diff --git a/trpc_sdk/config/_types.py b/trpc_sdk/config/_types.py index 74a54e9..9957fd8 100644 --- a/trpc_sdk/config/_types.py +++ b/trpc_sdk/config/_types.py @@ -336,14 +336,8 @@ class ClientConfig: discovery: str = '' load_balance: str = '' circuit_breaker: str = '' - filters: Optional[List[str]] = None - service: Optional[List[ClientServiceConfig]] = None - - def __post_init__(self) -> None: - if self.filters is None: - self.filters = [] - if self.service is None: - self.service = [] + filters: List[str] = field(default_factory=list) + service: List[ClientServiceConfig] = field(default_factory=list) @dataclass diff --git a/trpc_sdk/config/_utils.py b/trpc_sdk/config/_utils.py index 3e99d9a..481910b 100644 --- a/trpc_sdk/config/_utils.py +++ b/trpc_sdk/config/_utils.py @@ -3,13 +3,16 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. -"""Config utils""" +"""Configuration utilities.""" + +from __future__ import annotations import netifaces def join_host_port(host: str, port: int) -> str: """Build ip port. + Args: host: host of type str port: port of type int @@ -22,8 +25,8 @@ def join_host_port(host: str, port: int) -> str: def get_ip_with_nic(nic: str) -> str: - """ - Get ip with nic. + """Get ip with nic. + Args: nic: nic of type str Returns: diff --git a/trpc_sdk/exceptions/__init__.py b/trpc_sdk/exceptions/__init__.py index f056710..2e470aa 100644 --- a/trpc_sdk/exceptions/__init__.py +++ b/trpc_sdk/exceptions/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """tRPC-Python exception definitions.""" from ._trpc_exception import TrpcErrorCode @@ -49,5 +48,5 @@ "ClientInvokeError", "ClientPoolLimitError", "ClientPoolClosedError", - "ClientPoolConnClosedError" + "ClientPoolConnClosedError", ] diff --git a/trpc_sdk/exceptions/_client_exceptions.py b/trpc_sdk/exceptions/_client_exceptions.py index 47839b0..364bdd3 100644 --- a/trpc_sdk/exceptions/_client_exceptions.py +++ b/trpc_sdk/exceptions/_client_exceptions.py @@ -3,9 +3,7 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. -"""TRPC Framework Exception Definitions -This file contains all exception classes and error codes used in the TRPC framework -""" +"""TRPC Framework Exception Definitions.""" from __future__ import annotations @@ -14,16 +12,12 @@ from ._trpc_exception import TrpcException - - - class ClientTimeoutError(TrpcException): - """Exception raised when client request times out""" + """Exception raised when client request times out.""" def __init__(self, msg: str): - """ - Initialize the timeout error - + """Initialize the timeout error. + Args: msg: Description of the timeout """ @@ -31,9 +25,8 @@ def __init__(self, msg: str): super().__init__(TrpcErrorType.FRAMEWORK, TrpcErrorCode.TRPC_CLIENT_INVOKE_TIMEOUT_ERR, msg) def set_timeout_type(self, timeout_type: str): - """ - Set the specific type of timeout - + """Set the specific type of timeout. + Args: timeout_type: Detailed classification of timeout reason """ @@ -48,9 +41,8 @@ class ClientConnectionError(TrpcException): """Exception raised when client fails to establish connection""" def __init__(self, msg: str): - """ - Initialize the connection error - + """Initialize the connection error. + Args: msg: Description of the connection failure """ @@ -61,9 +53,8 @@ class ClientEncodeError(TrpcException): """Exception raised when client fails to encode request data""" def __init__(self, msg: str): - """ - Initialize the encode error - + """Initialize the encode error. + Args: msg: Description of the encode failure """ @@ -74,9 +65,8 @@ class ClientDecodeError(TrpcException): """Exception raised when client fails to decode response data""" def __init__(self, msg: str): - """ - Initialize the decode error - + """Initialize the decode error. + Args: msg: Description of the decode failure """ @@ -87,9 +77,8 @@ class ClientRouteError(TrpcException): """Exception raised when client encounters routing issues""" def __init__(self, msg: str): - """ - Initialize the routing error - + """Initialize the routing error. + Args: msg: Description of the routing failure """ @@ -100,9 +89,8 @@ class ClientInvokeError(TrpcException): """Exception raised for unknown invocation errors""" def __init__(self, msg: str): - """ - Initialize the invocation error - + """Initialize the invocation error. + Args: msg: Description of the invocation failure """ @@ -113,9 +101,8 @@ class ClientPoolLimitError(TrpcException): """Exception raised when connection pool exceeds its limit""" def __init__(self, msg: str): - """ - Initialize the pool limit error - + """Initialize the pool limit error. + Args: msg: Description of the pool limit exceeded """ @@ -126,9 +113,8 @@ class ClientPoolClosedError(TrpcException): """Exception raised when trying to use a closed connection pool""" def __init__(self, msg: str): - """ - Initialize the pool closed error - + """Initialize the pool closed error. + Args: msg: Description of the closed pool access attempt """ @@ -139,9 +125,8 @@ class ClientPoolConnClosedError(TrpcException): """Exception raised when trying to use a closed connection""" def __init__(self, msg): - """ - Initialize the connection closed error - + """Initialize the connection closed error. + Args: msg: Description of the closed connection access attempt """ diff --git a/trpc_sdk/exceptions/_exceptions.py b/trpc_sdk/exceptions/_exceptions.py index 4768fc8..62bf905 100644 --- a/trpc_sdk/exceptions/_exceptions.py +++ b/trpc_sdk/exceptions/_exceptions.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Exceptions raised by the task process feature. ``TrpcErrorType`` and ``TrpcErrorCode`` stay in :mod:`trpc_sdk.exceptions` diff --git a/trpc_sdk/exceptions/_server_exceptions.py b/trpc_sdk/exceptions/_server_exceptions.py index 3da51bb..840c242 100644 --- a/trpc_sdk/exceptions/_server_exceptions.py +++ b/trpc_sdk/exceptions/_server_exceptions.py @@ -3,9 +3,9 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. +"""TRPC Framework Exception Definitions. -"""TRPC Framework Exception Definitions -This file contains all exception classes and error codes used in the TRPC framework +This file contains all exception classes and error codes used in the TRPC framework. """ from __future__ import annotations @@ -19,9 +19,8 @@ class ServerEncodeError(TrpcException): """Exception raised when server fails to encode response data""" def __init__(self, msg: str): - """ - Initialize the encode error - + """Initialize the encode error. + Args: msg: Description of the encode failure """ @@ -32,9 +31,8 @@ class ServerDecodeError(TrpcException): """Exception raised when server fails to decode incoming request data""" def __init__(self, msg): - """ - Initialize the decode error - + """Initialize the decode error. + Args: msg: Description of the decode failure """ @@ -45,9 +43,8 @@ class ServerFuncNotFoundError(TrpcException): """Exception raised when requested function/method is not found in service""" def __init__(self, msg: str): - """ - Initialize the function not found error - + """Initialize the function not found error. + Args: msg: Description of the missing function, typically includes function name """ @@ -58,9 +55,8 @@ class ServerTimeoutError(TrpcException): """Exception raised when server processing exceeds time limit""" def __init__(self, msg: str): - """ - Initialize the server timeout error - + """Initialize the server timeout error. + Args: msg: Description of the timeout condition """ @@ -71,12 +67,9 @@ class ServerSystemError(TrpcException): """Exception raised for internal server system errors""" def __init__(self, msg: str): - """ - Initialize the system error - + """Initialize the system error. + Args: msg: Description of the system failure """ super().__init__(TrpcErrorType.FRAMEWORK, TrpcErrorCode.TRPC_SERVER_SYSTEM_ERR, msg) - - diff --git a/trpc_sdk/exceptions/_trpc_exception.py b/trpc_sdk/exceptions/_trpc_exception.py index 6611c6e..d6e2ff1 100644 --- a/trpc_sdk/exceptions/_trpc_exception.py +++ b/trpc_sdk/exceptions/_trpc_exception.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """tRPC exception types and error codes.""" from __future__ import annotations @@ -26,30 +25,24 @@ class TrpcErrorType(IntEnum): def _build_exception_code() -> type[IntEnum]: """Build ``TrpcErrorCode`` from ``TrpcRetCode`` plus Python extensions.""" - members = { - name: int(value) for name, value in trpc_pb2.TrpcRetCode.items() - } + members = {name: int(value) for name, value in trpc_pb2.TrpcRetCode.items()} # Python-only extensions. Values stay above the protocol reserved range so # they never collide with newly added TrpcRetCode members. - members.update( - { - "TRPC_CLIENT_POOL_CLOSED": 152, - "TRPC_CLIENT_POOL_CONN_CLOSED": 153, - "TRPC_TASK_HANDLE_ERR": 200, - "TRPC_PLUGIN_INIT_ERR": 202, - "TRPC_CONFIG_ERR": 203, - } - ) + members.update({ + "TRPC_CLIENT_POOL_CLOSED": 152, + "TRPC_CLIENT_POOL_CONN_CLOSED": 153, + "TRPC_TASK_HANDLE_ERR": 200, + "TRPC_PLUGIN_INIT_ERR": 202, + "TRPC_CONFIG_ERR": 203, + }) exception_code = IntEnum("TrpcErrorCode", members) - exception_code.__doc__ = ( - "Protocol and Python-framework error codes.\n\n" - "Protocol members are imported from ``trpc.TrpcRetCode`` at runtime, so " - "new protobuf retcodes become available without code changes. " - "Python-only extensions use values starting at 1001. Legacy name aliases " - "are intentionally omitted here and should be added by dependent packages." - ) + exception_code.__doc__ = ("Protocol and Python-framework error codes.\n\n" + "Protocol members are imported from ``trpc.TrpcRetCode`` at runtime, so " + "new protobuf retcodes become available without code changes. " + "Python-only extensions use values starting at 1001. Legacy name aliases " + "are intentionally omitted here and should be added by dependent packages.") return exception_code @@ -98,9 +91,8 @@ class UnknownError(TrpcException): """Exception raised for unclassified/unrecognized errors""" def __init__(self, msg: str): - """ - Initialize the unknown error - + """Initialize the unknown error. + Args: msg: Description of the unknown error condition """ diff --git a/trpc_sdk/filters/__init__.py b/trpc_sdk/filters/__init__.py index f544072..b283f3c 100644 --- a/trpc_sdk/filters/__init__.py +++ b/trpc_sdk/filters/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Unary filter chain helpers.""" from ._cython import FilterChain # pyright: ignore[reportMissingModuleSource] diff --git a/trpc_sdk/filters/_cython/__init__.py b/trpc_sdk/filters/_cython/__init__.py index 004c91b..3ae8076 100644 --- a/trpc_sdk/filters/_cython/__init__.py +++ b/trpc_sdk/filters/_cython/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Cython unary filter chain helpers.""" from ._filter import FilterChain # pyright: ignore[reportMissingModuleSource] diff --git a/trpc_sdk/filters/_cython/_filter.pyi b/trpc_sdk/filters/_cython/_filter.pyi index c117b71..1d9401f 100644 --- a/trpc_sdk/filters/_cython/_filter.pyi +++ b/trpc_sdk/filters/_cython/_filter.pyi @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Type declarations for the unary RPC filter chain.""" from typing import Any diff --git a/trpc_sdk/http/__init__.py b/trpc_sdk/http/__init__.py index b6f338f..17331c9 100644 --- a/trpc_sdk/http/__init__.py +++ b/trpc_sdk/http/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """tRPC-Python HTTP package: tRPC over aiohttp, plus a plain HTTP client. Public symbols are re-exported here. Callers should ``from trpc_sdk.http @@ -31,13 +30,13 @@ from __future__ import annotations -from ._client import Client +from ._client import HttpClient from ._client_transport import HttpClientTransport from ._client_transport import register_http_session_params -from ._codec import ClientHttpCodec -from ._codec import ClientHttpParser -from ._codec import ServerHttpCodec -from ._codec import ServerHttpParser +from ._codec import HttpClientCodec +from ._codec import HttpClientParser +from ._codec import HttpServerCodec +from ._codec import HttpServerParser from ._constants import DEFAULT_SESSION_NAME from ._constants import HTTP from ._constants import HTTP_ARG_JSON @@ -52,16 +51,6 @@ from ._constants import LOCAL_ADDR from ._constants import TRANS_INFO_BASE64_KEY from ._constants import USER_ROUTE_KEY -from ._context import get_http_header_in_client -from ._context import get_http_ok_codes -from ._context import get_http_request -from ._context import get_http_response -from ._context import get_http_rsp_header -from ._context import get_http_status_in_client -from ._context import pop_http_ok_codes -from ._context import pop_http_rsp_header -from ._context import set_http_ok_codes -from ._context import set_http_rsp_header from ._ctx_manager import BaseRequestContextManager from ._ctx_manager import RequestContextManager from ._exceptions import InvalidURL @@ -69,17 +58,27 @@ from ._http_response import HttpClientRspHeader from ._http_response import TrpcHttpResponse from ._http_response import create_rsp_object -from ._http_transport import HttpServerTransport -from ._http_transport import HttpServerTransportFactory from ._options import get_options +from ._utils import get_http_header_in_client +from ._utils import get_http_ok_codes +from ._utils import get_http_request +from ._utils import get_http_response +from ._utils import get_http_rsp_header +from ._utils import get_http_status_in_client +from ._utils import pop_http_ok_codes +from ._utils import pop_http_rsp_header +from ._utils import set_http_ok_codes +from ._utils import set_http_rsp_header from ._routes import HttpDecodeCallback from ._routes import HttpRoute -from ._routes import RegisteredRoutes -from ._routes import StaticFileRouters +from ._routes import get_registered_routes +from ._routes import get_static_file_routers from ._routes import register_static from ._routes import register_user_http_decode_func from ._routes import route from ._serialization_form import FormSerializer +from ._server_transport import HttpServerTransport +from ._server_transport import HttpServerTransportFactory from ._sse_client import SSEClient from ._sse_client import SSEEventSource from ._sse_event import SSEEvent @@ -93,17 +92,13 @@ from ._types import find_http_status from ._types import find_serialization_type from ._types import get_trpc_error_code -from ._utils import check_url -from ._utils import find_from_dict -from ._utils import get_host -from ._utils import reverse_dict __all__ = [ # Codec - "ServerHttpCodec", - "ServerHttpParser", - "ClientHttpCodec", - "ClientHttpParser", + "HttpServerCodec", + "HttpServerParser", + "HttpClientCodec", + "HttpClientParser", # Server transport "HttpServerTransport", "HttpServerTransportFactory", @@ -114,9 +109,7 @@ "register_http_session_params", "HttpSession", # HTTP client - "Client", - "check_url", - "get_host", + "HttpClient", "get_options", "BaseRequestContextManager", "RequestContextManager", @@ -125,8 +118,8 @@ "SSEEventSource", # Routes "HttpRoute", - "RegisteredRoutes", - "StaticFileRouters", + "get_registered_routes", + "get_static_file_routers", "route", "register_static", # Context helpers @@ -170,8 +163,6 @@ "find_compress_type", "find_content_encoding", "find_http_status", - "reverse_dict", - "find_from_dict", # Exceptions "InvalidURL", # Serialization diff --git a/trpc_sdk/http/_client.py b/trpc_sdk/http/_client.py index 344142f..5a67a15 100644 --- a/trpc_sdk/http/_client.py +++ b/trpc_sdk/http/_client.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """HTTP client with tRPC filters, naming and a plain HTTP API. :class:`Client` wraps :class:`trpc_sdk.client.Client` so ``get`` / ``post`` @@ -19,7 +18,8 @@ from aiohttp import hdrs from trpc_sdk.abc import clone_client_message -from trpc_sdk.client import Client as TrpcClient +from trpc_sdk.client import TrpcClient + from ._constants import HTTP_ARG_STREAM_KEY from ._constants import HTTP_ARGS_META_KEY from ._ctx_manager import RequestContextManager @@ -31,7 +31,7 @@ from ._types import UrlParser -class Client: +class HttpClient: """HTTP client that reuses tRPC filters, naming and invoke. ``get`` / ``post`` / ``request`` return an async context manager that @@ -67,14 +67,14 @@ def create_http_context(self, ctx, url: ParseResult, headers: HttpClientReqHeade return ctx, msg def post( - self, - ctx, - url: str, - options=None, - *, - data: Any = None, - headers: Any = None, - **kwargs: Any, + self, + ctx, + url: str, + options=None, + *, + data: Any = None, + headers: Any = None, + **kwargs: Any, ) -> RequestContextManager: """Send an HTTP POST. @@ -108,15 +108,15 @@ def get(self, ctx, url: str, options=None, *, headers: Any = None, **kwargs: Any return RequestContextManager(self._request(ctx, hdrs.METH_GET, url, options, headers=headers, **kwargs)) def request( - self, - ctx, - method, - url, - options=None, - *, - data: Any = None, - headers: Any = None, - **kwargs: Any, + self, + ctx, + method, + url, + options=None, + *, + data: Any = None, + headers: Any = None, + **kwargs: Any, ) -> RequestContextManager: """Send an HTTP request with an arbitrary method. @@ -132,19 +132,18 @@ def request( Returns: Async context manager yielding a :class:`TrpcHttpResponse`. """ - return RequestContextManager( - self._request(ctx, method, url, options, data=data, headers=headers, **kwargs)) + return RequestContextManager(self._request(ctx, method, url, options, data=data, headers=headers, **kwargs)) async def _request( - self, - ctx, - method, - url, - options=None, - *, - data: Any = None, - headers: Any = None, - **kwargs: Any, + self, + ctx, + method, + url, + options=None, + *, + data: Any = None, + headers: Any = None, + **kwargs: Any, ) -> TrpcHttpResponse: """Parse the URL, invoke, and wrap ``client_rsp_head`` as :class:`TrpcHttpResponse`. diff --git a/trpc_sdk/http/_client_transport.py b/trpc_sdk/http/_client_transport.py index 1b535b4..1d65551 100644 --- a/trpc_sdk/http/_client_transport.py +++ b/trpc_sdk/http/_client_transport.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """HTTP client transport: turn a TrpcMessage into an aiohttp round trip. :class:`HttpClientTransport.round_trip` is the plugin behind protocol @@ -35,6 +34,7 @@ from trpc_sdk.serialization import SerializationType from trpc_sdk.transport import RoundTripOptions from trpc_sdk.utils import now_ms + from ._constants import DEFAULT_SESSION_NAME from ._constants import HTTP from ._constants import HTTP_ARG_JSON @@ -50,7 +50,6 @@ from ._types import find_content_encoding from ._types import find_content_type - _http_session_params: Dict[str, Dict[str, Any]] = {} @@ -61,7 +60,7 @@ def register_http_session_params(params: dict, name: str = DEFAULT_SESSION_NAME) params: Keyword arguments forwarded to ``ClientSession``. name: Session name; ``DEFAULT_SESSION_NAME`` is the shared one. """ - global _http_session_params + global _http_session_params # noqa: F824 _http_session_params[name] = params @@ -139,7 +138,7 @@ def _get_headers(msg: TrpcMessage, req_header: HttpClientReqHeader): headers[HTTP_TRPC_HEADER.trpc_callee] = msg.callee_service_name headers[HTTP_TRPC_HEADER.trpc_timeout] = str(msg.timeout) - if msg.serialization_type != SerializationType.Noop: + if msg.serialization_type != SerializationType.NOOP: headers[hdrs.CONTENT_TYPE] = find_content_type(msg.serialization_type, "") if msg.compress_type: headers[hdrs.CONTENT_ENCODING] = find_content_encoding(msg.compress_type, "") diff --git a/trpc_sdk/http/_codec.py b/trpc_sdk/http/_codec.py index aed6aa2..8eba456 100644 --- a/trpc_sdk/http/_codec.py +++ b/trpc_sdk/http/_codec.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """tRPC-over-HTTP codec: encode and decode between TrpcMessage and HTTP. The codec never talks to a socket. On the server it reads the aiohttp @@ -22,6 +21,7 @@ import os import sys from typing import Any +from typing import List from aiohttp import hdrs from aiohttp.web_request import CIMultiDictProxy @@ -43,11 +43,12 @@ from trpc_sdk.exceptions import TrpcException from trpc_sdk.plugin import register_plugin from trpc_sdk.serialization import SerializationType + from ._constants import HTTP from ._constants import TRANS_INFO_BASE64_KEY -from ._context import pop_http_ok_codes from ._http_request import HttpClientReqHeader from ._http_response import HttpClientRspHeader +from ._utils import pop_http_ok_codes from ._types import HTTP_TRPC_HEADER from ._types import find_compress_type from ._types import find_http_status @@ -56,16 +57,28 @@ @register_plugin(PluginType.SERVER_PARSER, HTTP, init_pos=PluginInitPos.WORKER) -class ServerHttpParser(BaseServerProtocolParser): +class HttpServerParser(BaseServerProtocolParser): """HTTP server frame parser. HTTP framing is handled by aiohttp, so this parser is a no-op plugin registration that occupies the ``http`` parser slot. """ + def feed_data(self, data: bytes) -> None: + """Feed data to the parser.""" + raise NotImplementedError("HTTP frames are read by aiohttp, not by HttpServerParser") + + def read(self) -> List[bytes]: + """Return every complete frame currently buffered.""" + raise NotImplementedError("HTTP frames are read by aiohttp, not by HttpServerParser") + + def reset(self) -> None: + """Reset the parser.""" + raise NotImplementedError("HTTP frames are read by aiohttp, not by HttpServerParser") + @register_plugin(PluginType.SERVER_CODEC, HTTP, init_pos=PluginInitPos.WORKER) -class ServerHttpCodec(BaseCodec): +class HttpServerCodec(BaseCodec): """Server codec: pack RPC results into an aiohttp response. ``encode_data`` / ``decode_data`` read the aiohttp request / response @@ -184,8 +197,8 @@ async def decode_data(self, context: TrpcContext, _: bytes) -> bytes: if request.method == hdrs.METH_GET: req_body = request.query_string.encode("utf-8") - message.set_serialization_type(SerializationType.Form) - trpc_req.content_type = SerializationType.Form + message.set_serialization_type(SerializationType.FORM) + trpc_req.content_type = SerializationType.FORM return req_body req_body = await request.read() @@ -275,7 +288,7 @@ def decode_trpc_req_header( @register_plugin(PluginType.CLIENT_PARSER, HTTP, init_pos=PluginInitPos.WORKER) -class ClientHttpParser(BaseClientProtocolParser): +class HttpClientParser(BaseClientProtocolParser): """HTTP client frame parser. HTTP framing is handled by aiohttp, so this parser is a no-op @@ -292,11 +305,11 @@ async def read_frame(self, connection: Any) -> bytes: NotImplementedError: Always; the HTTP client transport reads the response through aiohttp instead of framing bytes. """ - raise NotImplementedError("HTTP frames are read by aiohttp, not by ClientHttpParser") + raise NotImplementedError("HTTP frames are read by aiohttp, not by HttpClientParser") @register_plugin(PluginType.CLIENT_CODEC, HTTP, init_pos=PluginInitPos.WORKER) -class ClientHttpCodec(BaseCodec): +class HttpClientCodec(BaseCodec): """Client codec: fill method/caller defaults and decode HTTP errors. ``encode_data`` does not build an HTTP packet: it only creates a @@ -375,8 +388,7 @@ def decode_data(self, context: TrpcContext, _: bytes) -> bytes: codec_ok = pop_http_ok_codes(context) codec_ok.add(http.HTTPStatus.OK) if rsp_header.status_code not in codec_ok: - message.set_client_rsp_err( - ClientInvokeError(f"http client codec StatusCode: {rsp_header.status_code}")) + message.set_client_rsp_err(ClientInvokeError(f"http client codec StatusCode: {rsp_header.status_code}")) body = b"" if not rsp_header.stream: diff --git a/trpc_sdk/http/_constants.py b/trpc_sdk/http/_constants.py index ca4f1b6..3086711 100644 --- a/trpc_sdk/http/_constants.py +++ b/trpc_sdk/http/_constants.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """HTTP protocol constants shared across the package. Scheme names, aiohttp kwargs keys, and context-meta keys live here so diff --git a/trpc_sdk/http/_context.py b/trpc_sdk/http/_context.py deleted file mode 100644 index ae111e5..0000000 --- a/trpc_sdk/http/_context.py +++ /dev/null @@ -1,162 +0,0 @@ -# Tencent is pleased to support the open source community by making tRPC-Python available. -# -# Copyright (C) 2026 Tencent. All rights reserved. -# -# tRPC-Python is licensed under Apache-2.0. - -"""HTTP request/response accessors on :class:`~trpc_sdk.abc.TrpcContext`. - -Handlers use these functions to reach the aiohttp ``Request`` / -``Response`` held on a context's message, and the HTTP client uses them to -pull status and headers off a :class:`~trpc_sdk.http.TrpcHttpResponse`. -Extra response headers and accepted status codes travel through -dedicated meta keys so codec encode can merge them after the user -handler returns. -""" - -from __future__ import annotations - -from typing import Dict -from typing import Set - -from aiohttp.web_request import CIMultiDictProxy -from aiohttp.web_request import Request -from aiohttp.web_response import Response - -from trpc_sdk.abc import TrpcContext -from trpc_sdk.abc import get_message -from ._constants import HTTP_RSP_HEADER_KEY -from ._constants import HTTP_RSP_OK_CODE_KEY -from ._http_response import TrpcHttpResponse - - -def get_http_request(ctx: TrpcContext) -> Request: - """Return the aiohttp request stored on ``ctx``'s message. - - Args: - ctx: Server-side tRPC context of an HTTP call. - - Returns: - The aiohttp ``Request`` held as ``message.server_raw_req``, or - None outside an HTTP server call. - """ - return get_message(ctx).server_raw_req - - -def get_http_response(ctx: TrpcContext) -> Response: - """Return the aiohttp response stored on ``ctx``'s message. - - Args: - ctx: Server-side tRPC context of an HTTP call. - - Returns: - The aiohttp ``Response`` held as ``message.server_raw_rsp``, or - None outside an HTTP server call. - """ - return get_message(ctx).server_raw_rsp - - -def get_http_header_in_client(rsp: TrpcHttpResponse) -> CIMultiDictProxy: - """Return HTTP headers from a client response. - - Args: - rsp: Client response wrapper. - - Returns: - Case-insensitive multi-dict of response headers. - """ - return rsp.header - - -def get_http_status_in_client(rsp: TrpcHttpResponse) -> int: - """Return the HTTP status code from a client response. - - Args: - rsp: Client response wrapper. - - Returns: - HTTP status code. - """ - return rsp.status - - -def set_http_rsp_header(ctx: TrpcContext, header: Dict) -> None: - """Store extra response headers on ``ctx`` for later merge. - - Args: - ctx: tRPC context. - header: Headers the handler wants on the HTTP response. - """ - ctx.with_meta_data(HTTP_RSP_HEADER_KEY, header) - - -def get_http_rsp_header(ctx: TrpcContext) -> Dict: - """Return extra response headers previously stored on ``ctx``. - - Args: - ctx: tRPC context. - - Returns: - Header dict, or ``{}`` if none was set. - """ - return ctx.get_meta_data(HTTP_RSP_HEADER_KEY, {}) - - -def pop_http_rsp_header(ctx: TrpcContext) -> Dict: - """Pop extra response headers off ``ctx``. - - :class:`~trpc_sdk.http.HttpServerTransport` calls this after the handler - returns so the extra headers can be merged into the aiohttp - response exactly once. - - Args: - ctx: tRPC context. - - Returns: - Header dict, or ``{}`` if none was set. - """ - header = {} - if HTTP_RSP_HEADER_KEY in ctx.meta_data: - header = ctx.pop_meta_data(HTTP_RSP_HEADER_KEY) - return header - - -def set_http_ok_codes(ctx: TrpcContext, ok_codes: Set) -> None: - """Store the set of HTTP status codes the client treats as success. - - Args: - ctx: tRPC context. - ok_codes: Status codes that should not become a client error. - """ - ctx.with_meta_data(HTTP_RSP_OK_CODE_KEY, ok_codes) - - -def get_http_ok_codes(ctx: TrpcContext) -> Set: - """Return the accepted HTTP status codes stored on ``ctx``. - - Args: - ctx: tRPC context. - - Returns: - Set of status codes, or ``set()`` if none was set. - """ - return ctx.get_meta_data(HTTP_RSP_OK_CODE_KEY, set()) - - -def pop_http_ok_codes(ctx: TrpcContext) -> Set: - """Pop the accepted HTTP status codes off ``ctx``. - - :class:`~trpc_sdk.http.ClientHttpCodec` calls this during decode so a - non-OK HTTP status can be turned into a client-side error unless the - caller listed it as acceptable. - - Args: - ctx: tRPC context. - - Returns: - Set of status codes, or ``set()`` if none was set. - """ - err_code = set() - if HTTP_RSP_OK_CODE_KEY in ctx.meta_data: - err_code = ctx.pop_meta_data(HTTP_RSP_OK_CODE_KEY) - return err_code diff --git a/trpc_sdk/http/_ctx_manager.py b/trpc_sdk/http/_ctx_manager.py index 2c4f8e8..a46bdf0 100644 --- a/trpc_sdk/http/_ctx_manager.py +++ b/trpc_sdk/http/_ctx_manager.py @@ -3,10 +3,9 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Async context managers wrapping an HTTP request coroutine. -:class:`RequestContextManager` is what :class:`~trpc_sdk.http.Client` +:class:`RequestContextManager` is what :class:`~trpc_sdk.http.HttpClient` returns from ``get`` / ``post`` / ``request``. ``async with`` awaits the request and :meth:`TrpcHttpResponse.release` on exit so the aiohttp response is closed. diff --git a/trpc_sdk/http/_exceptions.py b/trpc_sdk/http/_exceptions.py index 8764c23..162ad92 100644 --- a/trpc_sdk/http/_exceptions.py +++ b/trpc_sdk/http/_exceptions.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """HTTP-specific exceptions. Framework-wide errors live in :mod:`trpc_sdk.exceptions`. This module only diff --git a/trpc_sdk/http/_http_request.py b/trpc_sdk/http/_http_request.py index 7d7e211..89a1dbe 100644 --- a/trpc_sdk/http/_http_request.py +++ b/trpc_sdk/http/_http_request.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """HTTP client request-header record. :class:`HttpClientReqHeader` is the object stored on @@ -32,14 +31,14 @@ class HttpClientReqHeader: """ def __init__( - self, - method: str = hdrs.METH_GET, - host: str = "", - headers: Optional[dict] = None, - stream: bool = False, - scheme: str = HTTP, - parsed_url: Optional[ParseResult] = None, - url_parser: Optional[UrlParser] = None, + self, + method: str = hdrs.METH_GET, + host: str = "", + headers: Optional[dict] = None, + stream: bool = False, + scheme: str = HTTP, + parsed_url: Optional[ParseResult] = None, + url_parser: Optional[UrlParser] = None, ) -> None: self.method = method self.host = host # not read by transport; Host is filled from parsed_url / selector addr diff --git a/trpc_sdk/http/_http_response.py b/trpc_sdk/http/_http_response.py index 6df661f..ca10ef6 100644 --- a/trpc_sdk/http/_http_response.py +++ b/trpc_sdk/http/_http_response.py @@ -3,12 +3,11 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """HTTP client response wrappers. :class:`HttpClientRspHeader` is the raw status/headers/body the transport stores on ``TrpcMessage.client_rsp_head``. :class:`TrpcHttpResponse` -is the user-facing wrapper returned by :class:`~trpc_sdk.http.Client`. +is the user-facing wrapper returned by :class:`~trpc_sdk.http.HttpClient`. """ from __future__ import annotations @@ -31,11 +30,11 @@ class HttpClientRspHeader: """ def __init__( - self, - code: int, - headers: CIMultiDictProxy, - body: Union[ClientResponse, bytes], - stream: bool = False, + self, + code: int, + headers: CIMultiDictProxy, + body: Union[ClientResponse, bytes], + stream: bool = False, ) -> None: self.status_code = code self.headers = headers # aiohttp CIMultiDictProxy; lookups are case-insensitive @@ -52,7 +51,7 @@ def __str__(self) -> str: class TrpcHttpResponse: - """User-facing HTTP response returned by :class:`~trpc_sdk.http.Client`. + """User-facing HTTP response returned by :class:`~trpc_sdk.http.HttpClient`. Parsing helpers (``json`` / ``pb`` / ``text`` / ``stream_data``) delegate to the wrapped :class:`HttpClientRspHeader`. :meth:`release` diff --git a/trpc_sdk/http/_options.py b/trpc_sdk/http/_options.py index 8f6ebb4..87f90c6 100644 --- a/trpc_sdk/http/_options.py +++ b/trpc_sdk/http/_options.py @@ -3,8 +3,7 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - -"""HTTP-client option assembly for ``Client.invoke``. +"""HTTP-client option assembly for ``TrpcClient.invoke``. :func:`get_options` turns a parsed URL plus extra :class:`~trpc_sdk.client.Options` into the list the HTTP client passes to @@ -33,16 +32,12 @@ def get_options(url: ParseResult, opts: Optional[List]) -> List: Args: url: Already-parsed URL. - opts: Extra :class:`~trpc_sdk.client.Options` to append. + opts: Extra :class:`~trpc_sdk.client.TrpcOptions` to append. Returns: - A list of options to pass to ``Client.invoke``. + A list of options to pass to ``TrpcClient.invoke``. """ - base = ( - Options() - .set_protocol("http") - .set_serialization_type(SerializationType.Noop) - ) + base = (Options().set_protocol("http").set_serialization_type(SerializationType.NOOP)) trpc_selector = TrpcSelector() if url.scheme == trpc_selector.get_selector_name(): diff --git a/trpc_sdk/http/_routes.py b/trpc_sdk/http/_routes.py index 2f08172..3bc6d81 100644 --- a/trpc_sdk/http/_routes.py +++ b/trpc_sdk/http/_routes.py @@ -3,11 +3,10 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """User-registered HTTP routes, static-file prefixes and the ``@route`` decode callback. -``@route`` writes into :data:`RegisteredRoutes`; :func:`register_static` -fills :data:`StaticFileRouters`. :class:`~trpc_sdk.http.HttpServerTransport` +``@route`` writes into :data:`get_registered_routes`; :func:`register_static` +fills :data:`get_static_file_routers`. :class:`~trpc_sdk.http.HttpServerTransport` reads both when it builds the aiohttp app, after fork: precise user routes first, then static prefixes, then the RPC catch-all. :func:`register_user_http_decode_func` replaces how a ``@route`` request is @@ -29,17 +28,17 @@ class HttpRoute: """One user-registered HTTP callback. - Stored in :data:`RegisteredRoutes` and later bound onto aiohttp by + Stored in :data:`get_registered_routes` and later bound onto aiohttp by :class:`~trpc_sdk.http.HttpServerTransport`. ``service_name`` limits the route to one HTTP service when set. """ def __init__( - self, - handler: Callable[[TrpcContext, Request], bytes], - method: str, - path: str, - service_name: Optional[str] = None, + self, + handler: Callable[[TrpcContext, Request], bytes], + method: str, + path: str, + service_name: Optional[str] = None, ) -> None: self.handler = handler self.method = method @@ -47,8 +46,8 @@ def __init__( self.service_name = service_name -RegisteredRoutes: Dict[str, HttpRoute] = {} -StaticFileRouters = {} +_registered_routes: Dict[str, HttpRoute] = {} +_static_file_routers: Dict[str, str] = {} HttpDecodeCallback = Callable[[TrpcContext], None] _user_http_decode_cb: Optional[HttpDecodeCallback] = None @@ -75,7 +74,7 @@ def get_user_http_decode_func() -> Optional[HttpDecodeCallback]: def route(path: str, method: str = hdrs.METH_ANY, service_name: Optional[str] = None): """Register a custom HTTP handler on ``path``. - The decorator records the function into :data:`RegisteredRoutes` + The decorator records the function into :data:`get_registered_routes` keyed by ``path_method`` (plus ``_service_name`` when given). It does not wrap the function; the worker looks the record up later. @@ -89,12 +88,12 @@ def route(path: str, method: str = hdrs.METH_ANY, service_name: Optional[str] = """ def decorator(f): - global RegisteredRoutes + global _registered_routes # noqa: F824 handler = HttpRoute(f, method, path, service_name) prefix = f"{path}_{method}" if service_name: prefix = f"{prefix}_{service_name}" - RegisteredRoutes[prefix] = handler + _registered_routes[prefix] = handler return decorator @@ -106,5 +105,13 @@ def register_static(prefix: str, path_to_folder: str) -> None: prefix: HTTP path prefix, for example ``/static``. path_to_folder: Local directory that aiohttp should serve. """ - global StaticFileRouters - StaticFileRouters[prefix] = path_to_folder + global _static_file_routers # noqa: F824 + _static_file_routers[prefix] = path_to_folder + + +def get_registered_routes() -> Dict[str, HttpRoute]: + return _registered_routes + + +def get_static_file_routers() -> Dict[str, str]: + return _static_file_routers diff --git a/trpc_sdk/http/_serialization_form.py b/trpc_sdk/http/_serialization_form.py index 6a303b7..6eb58d8 100644 --- a/trpc_sdk/http/_serialization_form.py +++ b/trpc_sdk/http/_serialization_form.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """``application/x-www-form-urlencoded`` serializer. GET query strings and form bodies are parsed with ``parse_qs`` and @@ -28,7 +27,7 @@ from trpc_sdk.utils import dict_to_protobuf -@register_plugin(PluginType.SERIALIZATION, SerializationType.Form, init_pos=PluginInitPos.WORKER) +@register_plugin(PluginType.SERIALIZATION, SerializationType.FORM, init_pos=PluginInitPos.WORKER) class FormSerializer(BaseSerializer): """Serializer for HTTP form / query-string payloads.""" diff --git a/trpc_sdk/http/_http_transport.py b/trpc_sdk/http/_server_transport.py similarity index 94% rename from trpc_sdk/http/_http_transport.py rename to trpc_sdk/http/_server_transport.py index 5c23ea5..36a37ec 100644 --- a/trpc_sdk/http/_http_transport.py +++ b/trpc_sdk/http/_server_transport.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """HTTP server transport: serve an aiohttp application on the endpoint. :class:`HttpServerTransport` records the options before fork and serves the @@ -36,16 +35,16 @@ from trpc_sdk.transport import ssl_context_from_opts from trpc_sdk.utils import now_ms from trpc_sdk.utils import set_addr_to_ctx_from_transport -from ._codec import ServerHttpCodec +from ._codec import HttpServerCodec from ._constants import HTTP from ._constants import LOCAL_ADDR from ._constants import TRANS_INFO_BASE64_KEY from ._constants import USER_ROUTE_KEY -from ._context import pop_http_rsp_header from ._routes import HttpRoute -from ._routes import RegisteredRoutes -from ._routes import StaticFileRouters +from ._routes import get_registered_routes +from ._routes import get_static_file_routers from ._routes import get_user_http_decode_func +from ._utils import pop_http_rsp_header class HttpServerTransport(TrpcServerTransport): @@ -86,8 +85,7 @@ def listen(self) -> None: runner = reactor.submit(self._setup_runner, timeout=model.ready_timeout) model.keep_resource(reactor, runner, ResourceKind.RUNNER) runners[id(reactor)] = runner - self._serve_stream(model, group, lambda reactor: runners[id(reactor)].server, - ssl_context_from_opts(self.opts)) + self._serve_stream(model, group, lambda reactor: runners[id(reactor)].server, ssl_context_from_opts(self.opts)) async def _setup_runner(self) -> web.AppRunner: """Build and start an aiohttp runner on the loop that will serve it. @@ -116,14 +114,14 @@ def _build_app(self) -> web.Application: app = web.Application(client_max_size=TrpcConfig.server_config().max_rbuf_size) service_name = self.opts.service_adapter.opt.service_name - for user_route in RegisteredRoutes.values(): + for user_route in get_registered_routes().values(): if user_route.service_name and user_route.service_name != service_name: continue resource = app.router.add_resource(user_route.path) method = user_route.method if user_route.method else hdrs.METH_ANY resource.add_route(method, partial(self._handle_route, user_route)) - for prefix, path_to_file in StaticFileRouters.items(): + for prefix, path_to_file in get_static_file_routers().items(): app.router.add_static(prefix, path_to_file) resource = app.router.add_resource(r'/{name:.*}') @@ -160,7 +158,7 @@ def _create_context(self, request: Request) -> Tuple[TrpcContext, web.Response]: async def _handle_rpc(self, request: Request) -> Response: """RPC catch-all: run the tRPC handler and fill the HTTP response. - Body is not passed as bytes; :class:`ServerHttpCodec` reads it + Body is not passed as bytes; :class:`HttpServerCodec` reads it from the request on ``ctx``. The handler return value becomes ``response.body``. @@ -222,7 +220,7 @@ def _default_route_decode(self, ctx: TrpcContext, request: Request) -> None: """ message = get_message(ctx) message.set_server_rpc_name(request.path) - ServerHttpCodec.decode_trpc_req_header(ctx, message, request) + HttpServerCodec.decode_trpc_req_header(ctx, message, request) @register_plugin(PluginType.SERVER_TRANSPORT, HTTP, init_pos=PluginInitPos.WORKER) diff --git a/trpc_sdk/http/_sse_client.py b/trpc_sdk/http/_sse_client.py index ff11a39..877d5b1 100644 --- a/trpc_sdk/http/_sse_client.py +++ b/trpc_sdk/http/_sse_client.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Server-Sent Events client.""" from __future__ import annotations @@ -11,7 +10,7 @@ from typing import Any from typing import AsyncIterator -from ._client import Client +from ._client import HttpClient from ._constants import HTTP_ARG_STREAM_KEY from ._http_response import TrpcHttpResponse from ._sse_event import SSEEvent @@ -115,10 +114,10 @@ def __init__(self, name: str = "", encoding: str = "utf-8") -> None: """Create the underlying HTTP client. Args: - name: Name passed to :class:`Client` for config lookup. + name: Name passed to :class:`HttpClient` for config lookup. encoding: Text encoding of event stream bodies. """ - self.http_client = Client(name) + self.http_client = HttpClient(name) self._encoding = encoding async def sse_iter_events(self, diff --git a/trpc_sdk/http/_sse_event.py b/trpc_sdk/http/_sse_event.py index 685fa77..fa232d4 100644 --- a/trpc_sdk/http/_sse_event.py +++ b/trpc_sdk/http/_sse_event.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Server-Sent Events event model.""" from __future__ import annotations diff --git a/trpc_sdk/http/_sse_parser.py b/trpc_sdk/http/_sse_parser.py index d640f6f..4c43761 100644 --- a/trpc_sdk/http/_sse_parser.py +++ b/trpc_sdk/http/_sse_parser.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Incremental ``text/event-stream`` decoder.""" from __future__ import annotations diff --git a/trpc_sdk/http/_types.py b/trpc_sdk/http/_types.py index e3964f0..92460cc 100644 --- a/trpc_sdk/http/_types.py +++ b/trpc_sdk/http/_types.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Shared HTTP records: header names, URL parsing, session and lookups. This module holds the data types that codec, client transport and @@ -26,6 +25,8 @@ from functools import partial from typing import Dict from typing import Optional +from typing import TypeVar +from typing import Mapping from urllib.parse import ParseResult from urllib.parse import urlparse from urllib.parse import urlunparse @@ -39,8 +40,51 @@ from trpc_sdk.serialization import SerializationType from ._exceptions import InvalidURL -from ._utils import find_from_dict -from ._utils import reverse_dict + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + + +def _reverse_dict(origin: Mapping[_KT, _VT]) -> Mapping[_VT, _KT]: + """Return a new mapping with keys and values swapped. + + Duplicate values keep the last key that mapped to them, matching + the historical ``defines._reverse_dict`` behaviour. That is why + ``application/protobuf`` (and not ``application/x-protobuf``) is + the content type returned for :attr:`~trpc_sdk.serialization.SerializationType.PB`. + + Args: + origin: Mapping to invert. + + Returns: + A new mapping from values to keys. + """ + reversed_map: dict[_VT, _KT] = {} + for key, value in origin.items(): + reversed_map[value] = key + return reversed_map + + +def _find_from_dict( + origin: Mapping[_KT, _VT], + key: _KT, + default: Optional[_VT] = None, +) -> Optional[_VT]: + """Look ``key`` up in ``origin``, returning ``default`` if missing. + + The HTTP lookup helpers in :mod:`trpc_sdk.http._types` bind ``origin`` + with :func:`functools.partial`, so callers pass only ``key`` and + an optional ``default``. + + Args: + origin: Mapping to search. + key: Key to look up. + default: Value returned when ``key`` is absent. + + Returns: + The mapped value, or ``default``. + """ + return origin.get(key, default) class HttpSession(threading.local): @@ -92,7 +136,7 @@ class HttpTrpcHeader: TrpcErrorType.BUSINESS: HTTP_TRPC_HEADER.trpc_user_func_error_code, } -get_trpc_error_code = partial(find_from_dict, _trpc_err_type_to_http_header) +get_trpc_error_code = partial(_find_from_dict, _trpc_err_type_to_http_header) _content_type_to_serialization_type: Dict[str, SerializationType] = { "application/json": SerializationType.JSON, @@ -100,21 +144,20 @@ class HttpTrpcHeader: "application/x-protobuf": SerializationType.PB, "application/pb": SerializationType.PB, "application/proto": SerializationType.PB, - "application/jce": SerializationType.JCE, - "application/flatbuffer": SerializationType.FlatBuffer, - "application/octet-stream": SerializationType.Noop, - "application/x-www-form-urlencoded": SerializationType.Form, + "application/flatbuffer": SerializationType.FLATBUFFER, + "application/octet-stream": SerializationType.NOOP, + "application/x-www-form-urlencoded": SerializationType.FORM, } -_serialization_type_to_content_type = reverse_dict(_content_type_to_serialization_type) +_serialization_type_to_content_type = _reverse_dict(_content_type_to_serialization_type) -find_serialization_type = partial(find_from_dict, _content_type_to_serialization_type) -find_content_type = partial(find_from_dict, _serialization_type_to_content_type) +find_serialization_type = partial(_find_from_dict, _content_type_to_serialization_type) +find_content_type = partial(_find_from_dict, _serialization_type_to_content_type) -_content_encoding_to_compress_type: Dict[str, int] = {"gzip": CompressType.Gzip} -_compress_type_to_content_encoding = reverse_dict(_content_encoding_to_compress_type) +_content_encoding_to_compress_type: Dict[str, int] = {"gzip": CompressType.GZIP} +_compress_type_to_content_encoding = _reverse_dict(_content_encoding_to_compress_type) -find_compress_type = partial(find_from_dict, _content_encoding_to_compress_type) -find_content_encoding = partial(find_from_dict, _compress_type_to_content_encoding) +find_compress_type = partial(_find_from_dict, _content_encoding_to_compress_type) +find_content_encoding = partial(_find_from_dict, _compress_type_to_content_encoding) _trpc_err_code_to_http_status: Dict[int, http.HTTPStatus] = { TrpcErrorCode.TRPC_INVOKE_SUCCESS: http.HTTPStatus.OK, @@ -130,7 +173,7 @@ class HttpTrpcHeader: TrpcErrorCode.TRPC_INVOKE_UNKNOWN_ERR: http.HTTPStatus.INTERNAL_SERVER_ERROR, } -find_http_status = partial(find_from_dict, _trpc_err_code_to_http_status) +find_http_status = partial(_find_from_dict, _trpc_err_code_to_http_status) class UrlParser: diff --git a/trpc_sdk/http/_utils.py b/trpc_sdk/http/_utils.py index 586835d..c171141 100644 --- a/trpc_sdk/http/_utils.py +++ b/trpc_sdk/http/_utils.py @@ -3,95 +3,159 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - -"""Dict lookup helpers and URL small tools used by the HTTP package. - -:func:`reverse_dict` and :func:`find_from_dict` exist so the content-type, -content-encoding and HTTP-status tables in :mod:`trpc_sdk.http._types` can -be inverted and queried without repeating the same two functions. -:func:`check_url` and :func:`get_host` operate on an already-parsed -:class:`~urllib.parse.ParseResult`. +"""HTTP request/response accessors on :class:`~trpc_sdk.abc.TrpcContext`. + +Handlers use these functions to reach the aiohttp ``Request`` / +``Response`` held on a context's message, and the HTTP client uses them to +pull status and headers off a :class:`~trpc_sdk.http.TrpcHttpResponse`. +Extra response headers and accepted status codes travel through +dedicated meta keys so codec encode can merge them after the user +handler returns. """ from __future__ import annotations -from typing import Mapping -from typing import Optional -from typing import TypeVar -from urllib.parse import ParseResult +from typing import Dict +from typing import Set + +from aiohttp.web_request import CIMultiDictProxy +from aiohttp.web_request import Request +from aiohttp.web_response import Response + +from trpc_sdk.abc import TrpcContext +from trpc_sdk.abc import get_message +from ._constants import HTTP_RSP_HEADER_KEY +from ._constants import HTTP_RSP_OK_CODE_KEY +from ._http_response import TrpcHttpResponse + + +def get_http_request(ctx: TrpcContext) -> Request: + """Return the aiohttp request stored on ``ctx``'s message. + + Args: + ctx: Server-side tRPC context of an HTTP call. + + Returns: + The aiohttp ``Request`` held as ``message.server_raw_req``, or + None outside an HTTP server call. + """ + return get_message(ctx).server_raw_req + + +def get_http_response(ctx: TrpcContext) -> Response: + """Return the aiohttp response stored on ``ctx``'s message. + + Args: + ctx: Server-side tRPC context of an HTTP call. + + Returns: + The aiohttp ``Response`` held as ``message.server_raw_rsp``, or + None outside an HTTP server call. + """ + return get_message(ctx).server_raw_rsp + +def get_http_header_in_client(rsp: TrpcHttpResponse) -> CIMultiDictProxy: + """Return HTTP headers from a client response. -_KT = TypeVar("_KT") -_VT = TypeVar("_VT") + Args: + rsp: Client response wrapper. + Returns: + Case-insensitive multi-dict of response headers. + """ + return rsp.header -def reverse_dict(origin: Mapping[_KT, _VT]) -> Mapping[_VT, _KT]: - """Return a new mapping with keys and values swapped. - Duplicate values keep the last key that mapped to them, matching - the historical ``defines._reverse_dict`` behaviour. That is why - ``application/protobuf`` (and not ``application/x-protobuf``) is - the content type returned for :attr:`~trpc_sdk.serialization.SerializationType.PB`. +def get_http_status_in_client(rsp: TrpcHttpResponse) -> int: + """Return the HTTP status code from a client response. Args: - origin: Mapping to invert. + rsp: Client response wrapper. Returns: - A new mapping from values to keys. + HTTP status code. """ - reversed_map: dict[_VT, _KT] = {} - for key, value in origin.items(): - reversed_map[value] = key - return reversed_map + return rsp.status + + +def set_http_rsp_header(ctx: TrpcContext, header: Dict) -> None: + """Store extra response headers on ``ctx`` for later merge. + Args: + ctx: tRPC context. + header: Headers the handler wants on the HTTP response. + """ + ctx.with_meta_data(HTTP_RSP_HEADER_KEY, header) -def find_from_dict( - origin: Mapping[_KT, _VT], - key: _KT, - default: Optional[_VT] = None, -) -> Optional[_VT]: - """Look ``key`` up in ``origin``, returning ``default`` if missing. - The HTTP lookup helpers in :mod:`trpc_sdk.http._types` bind ``origin`` - with :func:`functools.partial`, so callers pass only ``key`` and - an optional ``default``. +def get_http_rsp_header(ctx: TrpcContext) -> Dict: + """Return extra response headers previously stored on ``ctx``. Args: - origin: Mapping to search. - key: Key to look up. - default: Value returned when ``key`` is absent. + ctx: tRPC context. Returns: - The mapped value, or ``default``. + Header dict, or ``{}`` if none was set. """ - return origin.get(key, default) + return ctx.get_meta_data(HTTP_RSP_HEADER_KEY, {}) + + +def pop_http_rsp_header(ctx: TrpcContext) -> Dict: + """Pop extra response headers off ``ctx``. + + :class:`~trpc_sdk.http.HttpServerTransport` calls this after the handler + returns so the extra headers can be merged into the aiohttp + response exactly once. + Args: + ctx: tRPC context. + + Returns: + Header dict, or ``{}`` if none was set. + """ + header = {} + if HTTP_RSP_HEADER_KEY in ctx.meta_data: + header = ctx.pop_meta_data(HTTP_RSP_HEADER_KEY) + return header + + +def set_http_ok_codes(ctx: TrpcContext, ok_codes: Set) -> None: + """Store the set of HTTP status codes the client treats as success. + + Args: + ctx: tRPC context. + ok_codes: Status codes that should not become a client error. + """ + ctx.with_meta_data(HTTP_RSP_OK_CODE_KEY, ok_codes) -def check_url(url: ParseResult) -> bool: - """Return whether ``url`` has both scheme and netloc. - Kept so existing subclasses that imported this helper keep working. +def get_http_ok_codes(ctx: TrpcContext) -> Set: + """Return the accepted HTTP status codes stored on ``ctx``. Args: - url: Already-parsed URL. + ctx: tRPC context. Returns: - ``True`` when both fields are non-empty. + Set of status codes, or ``set()`` if none was set. """ - return url.scheme != "" and url.netloc != "" + return ctx.get_meta_data(HTTP_RSP_OK_CODE_KEY, set()) -def get_host(url: ParseResult) -> str: - """Return ``hostname:port`` when a port is set, else ``hostname``. +def pop_http_ok_codes(ctx: TrpcContext) -> Set: + """Pop the accepted HTTP status codes off ``ctx``. - Kept so existing subclasses that imported this helper keep working. + :class:`~trpc_sdk.http.HttpClientCodec` calls this during decode so a + non-OK HTTP status can be turned into a client-side error unless the + caller listed it as acceptable. Args: - url: Already-parsed URL. + ctx: tRPC context. Returns: - Host string suitable for a ``Host`` header. + Set of status codes, or ``set()`` if none was set. """ - if url.port: - return f"{url.hostname}:{url.port}" - return url.hostname + err_code = set() + if HTTP_RSP_OK_CODE_KEY in ctx.meta_data: + err_code = ctx.pop_meta_data(HTTP_RSP_OK_CODE_KEY) + return err_code diff --git a/trpc_sdk/naming/__init__.py b/trpc_sdk/naming/__init__.py index 011aa17..5582d26 100644 --- a/trpc_sdk/naming/__init__.py +++ b/trpc_sdk/naming/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """tRPC-Python naming package: discovery, routing, load balancing, selectors. Public symbols are re-exported here. Callers should ``from trpc_sdk.naming @@ -32,22 +31,22 @@ from __future__ import annotations from ._circuit_breaker import NoopCircuitBreaker -from ._constants import DEFAULT_CIRCUITBREAKER_NAME +from ._constants import DEFAULT_CIRCUIT_BREAKER_NAME from ._constants import DEFAULT_DISCOVERY_NAME from ._constants import DEFAULT_LOADBALANCE_NAME from ._constants import DEFAULT_SELECTOR_NAME -from ._constants import DEFAULT_SERVICEROUTER_NAME +from ._constants import DEFAULT_SERVICE_ROUTER_NAME from ._constants import DNS_SELECTOR_NAME from ._constants import IP_SELECTOR_NAMES from ._constants import TRPC_SELECTOR_NAME -from ._defaults import get_default_circuitbreaker +from ._defaults import get_default_circuit_breaker from ._defaults import get_default_discovery from ._defaults import get_default_loadbalance -from ._defaults import get_default_servicerouter -from ._defaults import set_default_circuitbreaker +from ._defaults import get_default_service_router +from ._defaults import set_default_circuit_breaker from ._defaults import set_default_discovery from ._defaults import set_default_loadbalance -from ._defaults import set_default_servicerouter +from ._defaults import set_default_service_router from ._discovery import IpDiscovery from ._discovery import resolve_host from ._dsn_selector import DSNSelector @@ -63,13 +62,12 @@ from ._service_router import NoopServiceRouter from ._trpc_selector import TrpcSelector - __all__ = [ # Constants "DEFAULT_DISCOVERY_NAME", "DEFAULT_LOADBALANCE_NAME", - "DEFAULT_CIRCUITBREAKER_NAME", - "DEFAULT_SERVICEROUTER_NAME", + "DEFAULT_CIRCUIT_BREAKER_NAME", + "DEFAULT_SERVICE_ROUTER_NAME", "DEFAULT_SELECTOR_NAME", "TRPC_SELECTOR_NAME", "DNS_SELECTOR_NAME", @@ -79,10 +77,10 @@ "set_default_discovery", "get_default_loadbalance", "set_default_loadbalance", - "get_default_circuitbreaker", - "set_default_circuitbreaker", - "get_default_servicerouter", - "set_default_servicerouter", + "get_default_circuit_breaker", + "set_default_circuit_breaker", + "get_default_service_router", + "set_default_service_router", # Discovery "IpDiscovery", "resolve_host", diff --git a/trpc_sdk/naming/_circuit_breaker.py b/trpc_sdk/naming/_circuit_breaker.py index 5e69df7..b2dcab0 100644 --- a/trpc_sdk/naming/_circuit_breaker.py +++ b/trpc_sdk/naming/_circuit_breaker.py @@ -3,14 +3,13 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Built-in no-op circuit breaker. :class:`NoopCircuitBreaker` is registered as -:data:`~trpc_sdk.naming._constants.DEFAULT_CIRCUITBREAKER_NAME`. It reports +:data:`~trpc_sdk.naming._constants.DEFAULT_CIRCUIT_BREAKER_NAME`. It reports every node as available and ignores :meth:`report`. Real breakers (Polar, and so on) replace it through -:func:`~trpc_sdk.naming.set_default_circuitbreaker` or +:func:`~trpc_sdk.naming.set_default_circuit_breaker` or :meth:`~trpc_sdk.abc.SelectorOption.set_circuit_breaker`. """ @@ -22,10 +21,11 @@ from trpc_sdk.abc import Node from trpc_sdk.abc import PluginType from trpc_sdk.plugin import register_plugin -from ._constants import DEFAULT_CIRCUITBREAKER_NAME + +from ._constants import DEFAULT_CIRCUIT_BREAKER_NAME -@register_plugin(PluginType.NAMING_CIRCUIT_BREAKER, DEFAULT_CIRCUITBREAKER_NAME) +@register_plugin(PluginType.NAMING_CIRCUIT_BREAKER, DEFAULT_CIRCUIT_BREAKER_NAME) class NoopCircuitBreaker(BaseCircuitBreaker): """Circuit breaker that never trips. diff --git a/trpc_sdk/naming/_constants.py b/trpc_sdk/naming/_constants.py index b3141c3..80cf5ef 100644 --- a/trpc_sdk/naming/_constants.py +++ b/trpc_sdk/naming/_constants.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Immutable plugin-name literals for the naming package. These strings are the names passed to ``@register_plugin``. Mutable @@ -25,10 +24,10 @@ DEFAULT_LOADBALANCE_NAME = "RandomLB" # Built-in circuit-breaker plugin registered by :class:`NoopCircuitBreaker`. -DEFAULT_CIRCUITBREAKER_NAME = "NoopCB" +DEFAULT_CIRCUIT_BREAKER_NAME = "NoopCB" # Built-in service-router plugin registered by :class:`NoopServiceRouter`. -DEFAULT_SERVICEROUTER_NAME = "NoopSR" +DEFAULT_SERVICE_ROUTER_NAME = "NoopSR" # Built-in DSN selector plugin; also the framework-wide default selector. DEFAULT_SELECTOR_NAME = "dsn" diff --git a/trpc_sdk/naming/_defaults.py b/trpc_sdk/naming/_defaults.py index ba1f7bd..4cf6c97 100644 --- a/trpc_sdk/naming/_defaults.py +++ b/trpc_sdk/naming/_defaults.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Process-wide default plugin names used by :class:`TrpcSelector`. Each value starts as the matching literal in @@ -20,15 +19,15 @@ from __future__ import annotations -from ._constants import DEFAULT_CIRCUITBREAKER_NAME +from ._constants import DEFAULT_CIRCUIT_BREAKER_NAME from ._constants import DEFAULT_DISCOVERY_NAME from ._constants import DEFAULT_LOADBALANCE_NAME -from ._constants import DEFAULT_SERVICEROUTER_NAME +from ._constants import DEFAULT_SERVICE_ROUTER_NAME _default_discovery: str = DEFAULT_DISCOVERY_NAME _default_loadbalance: str = DEFAULT_LOADBALANCE_NAME -_default_circuitbreaker: str = DEFAULT_CIRCUITBREAKER_NAME -_default_servicerouter: str = DEFAULT_SERVICEROUTER_NAME +_default_circuit_breaker: str = DEFAULT_CIRCUIT_BREAKER_NAME +_default_service_router: str = DEFAULT_SERVICE_ROUTER_NAME def get_default_discovery() -> str: @@ -61,31 +60,31 @@ def set_default_loadbalance(lb: str) -> None: _default_loadbalance = lb -def get_default_circuitbreaker() -> str: +def get_default_circuit_breaker() -> str: """Return the circuit-breaker plugin name :class:`TrpcSelector` uses by default.""" - return _default_circuitbreaker + return _default_circuit_breaker -def set_default_circuitbreaker(cb: str) -> None: +def set_default_circuit_breaker(cb: str) -> None: """Replace the process-wide default circuit-breaker plugin name. Args: cb: Registered name under ``PluginType.NAMING_CIRCUIT_BREAKER``. """ - global _default_circuitbreaker - _default_circuitbreaker = cb + global _default_circuit_breaker + _default_circuit_breaker = cb -def get_default_servicerouter() -> str: +def get_default_service_router() -> str: """Return the service-router plugin name :class:`TrpcSelector` uses by default.""" - return _default_servicerouter + return _default_service_router -def set_default_servicerouter(sr: str) -> None: +def set_default_service_router(sr: str) -> None: """Replace the process-wide default service-router plugin name. Args: sr: Registered name under ``PluginType.NAMING_SERVICE_ROUTER``. """ - global _default_servicerouter - _default_servicerouter = sr + global _default_service_router + _default_service_router = sr diff --git a/trpc_sdk/naming/_discovery.py b/trpc_sdk/naming/_discovery.py index 8bc5ae5..9a3bdaa 100644 --- a/trpc_sdk/naming/_discovery.py +++ b/trpc_sdk/naming/_discovery.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Built-in IP / DNS discovery. :class:`IpDiscovery` treats ``service_name`` as a ``host:port`` (or @@ -34,7 +33,6 @@ from trpc_sdk.plugin import register_plugin from ._constants import DEFAULT_DISCOVERY_NAME -from ._defaults import set_default_discovery @register_plugin(PluginType.NAMING_DISCOVERY, DEFAULT_DISCOVERY_NAME) @@ -126,10 +124,8 @@ def resolve_host(host: str, resolve_dns: bool = True) -> Tuple[Optional[str], in port = host[host.index(']'):] port_arr = port.split(':') if len(port_arr) != 2: - raise Exception( - f"IPv6 address {host!r} is missing ':port' after the closing " - f"bracket (expected '[ip]:port')" - ) + raise Exception(f"IPv6 address {host!r} is missing ':port' after the closing " + f"bracket (expected '[ip]:port')") return ip, int(port_arr[1]) else: if host.find("?") != -1: diff --git a/trpc_sdk/naming/_dsn_selector.py b/trpc_sdk/naming/_dsn_selector.py index be4df3d..cbcff82 100644 --- a/trpc_sdk/naming/_dsn_selector.py +++ b/trpc_sdk/naming/_dsn_selector.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Data-source-name selectors. :class:`DSNSelector` is registered as @@ -55,11 +54,9 @@ async def select(self, service_name: str, opt: SelectorOption) -> Node: ValueError: ``service_name`` is empty. """ if service_name == "": - raise ValueError( - "DSNSelector.select received an empty service_name; " - "pass a data-source name such as " - "'dsn://user:passwd@tcp(ip:port)/db'" - ) + raise ValueError("DSNSelector.select received an empty service_name; " + "pass a data-source name such as " + "'dsn://user:passwd@tcp(ip:port)/db'") return Node(service_name=service_name, address=service_name) @@ -108,15 +105,11 @@ async def select(self, service_name: str, opt: SelectorOption) -> Node: ``None``, or the inner selector is not instantiated. """ if service_name == "": - raise ValueError( - "ResolveSelector.select received an empty service_name; " - "pass a DSN that contains an extractable service name" - ) + raise ValueError("ResolveSelector.select received an empty service_name; " + "pass a DSN that contains an extractable service name") if self.extractor is None: - raise ValueError( - "ResolveSelector.select cannot extract a service name " - "because extractor is None" - ) + raise ValueError("ResolveSelector.select cannot extract a service name " + "because extractor is None") pos, length = self.extractor.extract(service_name) extracted_service_name = service_name[pos:pos + length] resolved_node = await self.resolve_address(extracted_service_name, opt) @@ -142,15 +135,12 @@ def resolve_address(self, service_name: str, opt: SelectorOption) -> str: ValueError: No instance is stored for ``resolver_selector_name``. """ - resolver = DEFAULT_PLUGIN_MANAGER.get_instance( - PluginType.NAMING_SELECTOR, self.resolver_selector_name) + resolver = DEFAULT_PLUGIN_MANAGER.get_instance(PluginType.NAMING_SELECTOR, self.resolver_selector_name) if resolver is None: - raise ValueError( - f"ResolveSelector.resolve_address cannot load naming selector " - f"{self.resolver_selector_name!r} under PluginType.NAMING_SELECTOR; " - f"the plugin is not instantiated. Register it and call " - f"plugin.setup() first" - ) + raise ValueError(f"ResolveSelector.resolve_address cannot load naming selector " + f"{self.resolver_selector_name!r} under PluginType.NAMING_SELECTOR; " + f"the plugin is not instantiated. Register it and call " + f"plugin.setup() first") return resolver.select(service_name, opt) async def report(self, node: Node, cost: int, success: int) -> NoReturn: diff --git a/trpc_sdk/naming/_ip_selector.py b/trpc_sdk/naming/_ip_selector.py index 99e6845..b6f9617 100644 --- a/trpc_sdk/naming/_ip_selector.py +++ b/trpc_sdk/naming/_ip_selector.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """IP and DNS selectors that parse the target as host:port. :class:`IpSelector` is registered as ``ip``, ``http``, and ``https`` so @@ -31,7 +30,6 @@ from ._constants import DNS_SELECTOR_NAME from ._discovery import resolve_host -from ._selector_lookup import get_selector @register_plugin(PluginType.NAMING_SELECTOR, DNS_SELECTOR_NAME) @@ -56,10 +54,8 @@ async def select(self, service_name: str, opt: SelectorOption) -> Node: Exception: ``service_name`` is empty. """ if service_name == "": - raise Exception( - "DNSSelector.select received an empty service_name; " - "pass a host:port target" - ) + raise Exception("DNSSelector.select received an empty service_name; " + "pass a host:port target") addr = get_random_addr(service_name) ip, port = resolve_host(addr) @@ -101,10 +97,8 @@ async def select(self, service_name: str, opt: SelectorOption) -> Node: Exception: ``service_name`` is empty. """ if service_name == "": - raise Exception( - "IpSelector.select received an empty service_name; " - "pass a host:port target" - ) + raise Exception("IpSelector.select received an empty service_name; " + "pass a host:port target") addr = get_random_addr(service_name) ip, port = resolve_host(addr, False) diff --git a/trpc_sdk/naming/_load_balance.py b/trpc_sdk/naming/_load_balance.py index ea50cb3..4c55e6d 100644 --- a/trpc_sdk/naming/_load_balance.py +++ b/trpc_sdk/naming/_load_balance.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Built-in random load balancer. :class:`RandomLoadBalance` is registered as @@ -23,7 +22,6 @@ from trpc_sdk.plugin import register_plugin from ._constants import DEFAULT_LOADBALANCE_NAME -from ._defaults import set_default_loadbalance @register_plugin(PluginType.NAMING_LOADBALANCE, DEFAULT_LOADBALANCE_NAME) @@ -35,11 +33,7 @@ class RandomLoadBalance(BaseLoadBalance): retry inside this plugin. """ - async def select( - self, - service_name: str, - node_list: List[Node], - namespace: str) -> Node: + async def select(self, service_name: str, node_list: List[Node], namespace: str) -> Node: """Return one uniformly chosen node. Args: @@ -54,9 +48,7 @@ async def select( Exception: ``node_list`` is empty. """ if len(node_list) == 0: - raise Exception( - f"RandomLoadBalance.select has no nodes for service " - f"{service_name!r} in namespace {namespace!r}" - ) + raise Exception(f"RandomLoadBalance.select has no nodes for service " + f"{service_name!r} in namespace {namespace!r}") n = randint(0, len(node_list) - 1) return node_list[n] diff --git a/trpc_sdk/naming/_registry.py b/trpc_sdk/naming/_registry.py index b4436fc..ac2f16c 100644 --- a/trpc_sdk/naming/_registry.py +++ b/trpc_sdk/naming/_registry.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Service-registry lookup. :func:`get_registry` is the naming counterpart of :func:`get_selector`: diff --git a/trpc_sdk/naming/_selector_lookup.py b/trpc_sdk/naming/_selector_lookup.py index 8a224a5..9d0ea14 100644 --- a/trpc_sdk/naming/_selector_lookup.py +++ b/trpc_sdk/naming/_selector_lookup.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Shared lookup helpers for naming selector plugins. :func:`get_selector` used to be copied in ``ip_selector``, diff --git a/trpc_sdk/naming/_service_router.py b/trpc_sdk/naming/_service_router.py index 2ff42c0..a85adf7 100644 --- a/trpc_sdk/naming/_service_router.py +++ b/trpc_sdk/naming/_service_router.py @@ -3,13 +3,12 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Built-in no-op service router. :class:`NoopServiceRouter` is registered as -:data:`~trpc_sdk.naming._constants.DEFAULT_SERVICEROUTER_NAME`. It returns +:data:`~trpc_sdk.naming._constants.DEFAULT_SERVICE_ROUTER_NAME`. It returns the discovered node list unchanged. Polar plugins replace it through -:func:`set_default_servicerouter` or +:func:`set_default_service_router` or :meth:`~trpc_sdk.abc.SelectorOption.set_service_router`. :class:`~trpc_sdk.abc.BaseServiceRouter` is the abstract contract this @@ -26,11 +25,10 @@ from trpc_sdk.abc import ServerRouterOption from trpc_sdk.plugin import register_plugin -from ._constants import DEFAULT_SERVICEROUTER_NAME -from ._defaults import set_default_servicerouter +from ._constants import DEFAULT_SERVICE_ROUTER_NAME -@register_plugin(PluginType.NAMING_SERVICE_ROUTER, DEFAULT_SERVICEROUTER_NAME) +@register_plugin(PluginType.NAMING_SERVICE_ROUTER, DEFAULT_SERVICE_ROUTER_NAME) class NoopServiceRouter(BaseServiceRouter): """Service router that keeps every discovered node. @@ -38,11 +36,7 @@ class NoopServiceRouter(BaseServiceRouter): the same list discovery produced. """ - async def filter( - self, - service_name: str, - nodes: List[Node], - opt: ServerRouterOption) -> List[Node]: + async def filter(self, service_name: str, nodes: List[Node], opt: ServerRouterOption) -> List[Node]: """Return ``nodes`` without filtering. Args: diff --git a/trpc_sdk/naming/_trpc_selector.py b/trpc_sdk/naming/_trpc_selector.py index 245d986..745698c 100644 --- a/trpc_sdk/naming/_trpc_selector.py +++ b/trpc_sdk/naming/_trpc_selector.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Composite selector that chains discovery, routing, load balancing, and breaking. :class:`TrpcSelector` is the default client selector constructed in @@ -45,11 +44,10 @@ from trpc_sdk.plugin import get_plugin from ._constants import TRPC_SELECTOR_NAME -from ._defaults import get_default_circuitbreaker +from ._defaults import get_default_circuit_breaker from ._defaults import get_default_discovery from ._defaults import get_default_loadbalance -from ._defaults import get_default_servicerouter -from ._selector_lookup import get_selector +from ._defaults import get_default_service_router class TrpcSelector(BaseSelector): @@ -64,8 +62,8 @@ def __init__(self): self.selector_plugin_name = TRPC_SELECTOR_NAME self.discovery = "" self.loadbalance = "" - self.circuitbreaker = "" - self.servicerouter = "" + self.circuit_breaker = "" + self.service_router = "" async def select(self, service_name: str, opt: SelectorOption) -> Node: """Resolve one node for ``service_name`` through the naming plugins. @@ -84,63 +82,51 @@ async def select(self, service_name: str, opt: SelectorOption) -> Node: registered; or no node remains after discovery/routing. """ if service_name == "": - raise Exception( - "TrpcSelector.select received an empty service_name; " - "pass a non-empty target or callee service name" - ) + raise Exception("TrpcSelector.select received an empty service_name; " + "pass a non-empty target or callee service name") namespace = opt.namespace self.discovery = get_default_discovery() self.loadbalance = get_default_loadbalance() - self.circuitbreaker = get_default_circuitbreaker() - self.servicerouter = get_default_servicerouter() + self.circuit_breaker = get_default_circuit_breaker() + self.service_router = get_default_service_router() if opt.discovery != "": self.discovery = opt.discovery if opt.loadbalance != "": self.loadbalance = opt.loadbalance if opt.circuit_breaker != "": - self.circuitbreaker = opt.circuit_breaker + self.circuit_breaker = opt.circuit_breaker if opt.service_router != "": - self.servicerouter = opt.service_router + self.service_router = opt.service_router - discovery_instance: Optional[BaseDiscovery] = get_plugin( - PluginType.NAMING_DISCOVERY, self.discovery) - loadbalance_instance: Optional[BaseLoadBalance] = get_plugin( - PluginType.NAMING_LOADBALANCE, self.loadbalance) - circuitbreaker_instance: Optional[BaseCircuitBreaker] = get_plugin( - PluginType.NAMING_CIRCUIT_BREAKER, self.circuitbreaker) - servicerouter_instance: Optional[BaseServiceRouter] = get_plugin( - PluginType.NAMING_SERVICE_ROUTER, self.servicerouter) + discovery_instance: Optional[BaseDiscovery] = get_plugin(PluginType.NAMING_DISCOVERY, self.discovery) + loadbalance_instance: Optional[BaseLoadBalance] = get_plugin(PluginType.NAMING_LOADBALANCE, self.loadbalance) + circuit_breaker_instance: Optional[BaseCircuitBreaker] = get_plugin(PluginType.NAMING_CIRCUIT_BREAKER, + self.circuit_breaker) + service_router_instance: Optional[BaseServiceRouter] = get_plugin(PluginType.NAMING_SERVICE_ROUTER, + self.service_router) if discovery_instance is None: - raise Exception( - f"TrpcSelector.select cannot resolve service {service_name!r}: " - f"discovery plugin {self.discovery!r} is not registered under " - f"PluginType.NAMING_DISCOVERY; register the plugin before calling " - f"select()" - ) + raise Exception(f"TrpcSelector.select cannot resolve service {service_name!r}: " + f"discovery plugin {self.discovery!r} is not registered under " + f"PluginType.NAMING_DISCOVERY; register the plugin before calling " + f"select()") if loadbalance_instance is None: - raise Exception( - f"TrpcSelector.select cannot resolve service {service_name!r}: " - f"load-balance plugin {self.loadbalance!r} is not registered under " - f"PluginType.NAMING_LOADBALANCE; register the plugin before calling " - f"select()" - ) - if circuitbreaker_instance is None: - raise Exception( - f"TrpcSelector.select cannot resolve service {service_name!r}: " - f"circuit-breaker plugin {self.circuitbreaker!r} is not registered " - f"under PluginType.NAMING_CIRCUIT_BREAKER; register the plugin " - f"before calling select()" - ) - if servicerouter_instance is None: - raise Exception( - f"TrpcSelector.select cannot resolve service {service_name!r}: " - f"service-router plugin {self.servicerouter!r} is not registered " - f"under PluginType.NAMING_SERVICE_ROUTER; register the plugin " - f"before calling select()" - ) + raise Exception(f"TrpcSelector.select cannot resolve service {service_name!r}: " + f"load-balance plugin {self.loadbalance!r} is not registered under " + f"PluginType.NAMING_LOADBALANCE; register the plugin before calling " + f"select()") + if circuit_breaker_instance is None: + raise Exception(f"TrpcSelector.select cannot resolve service {service_name!r}: " + f"circuit-breaker plugin {self.circuit_breaker!r} is not registered " + f"under PluginType.NAMING_CIRCUIT_BREAKER; register the plugin " + f"before calling select()") + if service_router_instance is None: + raise Exception(f"TrpcSelector.select cannot resolve service {service_name!r}: " + f"service-router plugin {self.service_router!r} is not registered " + f"under PluginType.NAMING_SERVICE_ROUTER; register the plugin " + f"before calling select()") node = await discovery_instance.select_node(service_name, opt) discovered_count: Optional[int] = None @@ -150,8 +136,7 @@ async def select(self, service_name: str, opt: SelectorOption) -> Node: if node is None: node_list: List[Node] = await discovery_instance.list(service_name, namespace) discovered_count = len(node_list) - node_list = await servicerouter_instance.filter( - service_name, node_list, opt.service_router_opt) + node_list = await service_router_instance.filter(service_name, node_list, opt.service_router_opt) filtered_count = len(node_list) node = await loadbalance_instance.select(service_name, node_list, namespace) @@ -163,20 +148,16 @@ async def select(self, service_name: str, opt: SelectorOption) -> Node: elif filtered_count == 0: reason = "service router filtered out every discovered node" else: - reason = ( - f"load balancer returned no node " - f"(discovery returned {discovered_count} node(s), " - f"service router kept {filtered_count})" - ) - raise Exception( - f"TrpcSelector.select found no usable node for service " - f"{service_name!r} in namespace {namespace!r}: {reason}" - ) + reason = (f"load balancer returned no node " + f"(discovery returned {discovered_count} node(s), " + f"service router kept {filtered_count})") + raise Exception(f"TrpcSelector.select found no usable node for service " + f"{service_name!r} in namespace {namespace!r}: {reason}") if node.metadata is None: node.metadata = {} - node.metadata["circuitbreaker"] = circuitbreaker_instance + node.metadata["circuit_breaker"] = circuit_breaker_instance return node async def report(self, node: Node, cost: int, success: int) -> NoReturn: @@ -184,7 +165,7 @@ async def report(self, node: Node, cost: int, success: int) -> NoReturn: Args: node: The node :meth:`select` returned. Must carry - ``metadata['circuitbreaker']``. + ``metadata['circuit_breaker']``. cost: Call duration passed to the breaker. success: Call result passed to the breaker. @@ -193,16 +174,12 @@ async def report(self, node: Node, cost: int, success: int) -> NoReturn: missing (the node did not come from :meth:`select`). """ if node is None: - raise Exception( - "TrpcSelector.report requires the Node returned by select(); " - "got None" - ) + raise Exception("TrpcSelector.report requires the Node returned by select(); " + "got None") if node.metadata is None: - raise Exception( - "TrpcSelector.report requires node.metadata populated by " - "select() with a 'circuitbreaker' entry; got None" - ) - breaker: BaseCircuitBreaker = node.metadata["circuitbreaker"] + raise Exception("TrpcSelector.report requires node.metadata populated by " + "select() with a 'circuit_breaker' entry; got None") + breaker: BaseCircuitBreaker = node.metadata["circuit_breaker"] await breaker.report(node, cost, success) def get_selector_name(self) -> str: diff --git a/trpc_sdk/plugin/__init__.py b/trpc_sdk/plugin/__init__.py index c4962aa..b5bdcbe 100644 --- a/trpc_sdk/plugin/__init__.py +++ b/trpc_sdk/plugin/__init__.py @@ -1,9 +1,9 @@ -# Tencent is pleased to support the open source community by making tRPC-Agent-Python available. +# Tencent is pleased to support the open source community by making tRPC-Python available. # # Copyright (C) 2026 Tencent. All rights reserved. # -# tRPC-Agent-Python is licensed under Apache-2.0. -"""tRPC-Agent-Python plugin module""" +# tRPC-Python is licensed under Apache-2.0. +"""tRPC-Python plugin module.""" from __future__ import annotations diff --git a/trpc_sdk/plugin/_exceptions.py b/trpc_sdk/plugin/_exceptions.py index d8a22b7..6b7ebf1 100644 --- a/trpc_sdk/plugin/_exceptions.py +++ b/trpc_sdk/plugin/_exceptions.py @@ -3,8 +3,9 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. -"""TRPC Framework Exception Definitions -This file contains all exception classes and error codes used in the TRPC framework +"""TRPC Framework Exception Definitions. + +This file contains all exception classes and error codes used in the TRPC framework. """ from __future__ import annotations @@ -16,14 +17,13 @@ class PluginInitError(TrpcException): """Exception raised when plugin initialization fails - + This is a critical error that will cause the service to exit """ def __init__(self, msg: str): - """ - Initialize the plugin initialization error - + """Initialize the plugin initialization error. + Args: msg: Description of the initialization failure """ diff --git a/trpc_sdk/plugin/_plugin.py b/trpc_sdk/plugin/_plugin.py index 54922b9..2c6ec5b 100644 --- a/trpc_sdk/plugin/_plugin.py +++ b/trpc_sdk/plugin/_plugin.py @@ -72,8 +72,7 @@ def adjust_plugin_order(self, plugin_type: PluginType): self._plugin_specs[plugin_type] = ordered_dict def register(self, plugin_spec: PluginSpec): - """ - Register plugin + """Register plugin. Args: plugin_spec: plugin specification @@ -81,8 +80,7 @@ def register(self, plugin_spec: PluginSpec): self._plugin_specs[plugin_spec.plugin_type][plugin_spec.plugin_name] = plugin_spec def get_plugin_spec(self, plugin_type: PluginType, plugin_name: str) -> Optional[PluginSpec]: - """ - Get plugin specification by plugin type and plugin name + """Get plugin specification by plugin type and plugin name. Args: plugin_type: plugin type @@ -93,8 +91,7 @@ def get_plugin_spec(self, plugin_type: PluginType, plugin_name: str) -> Optional return self._plugin_specs[plugin_type].get(plugin_name, None) def find_instance(self, plugin_type: PluginType, plugin_name: str) -> bool: - """ - Check if plugin instance exists by plugin type and plugin name + """Check if plugin instance exists by plugin type and plugin name. Args: plugin_type: plugin type @@ -105,8 +102,7 @@ def find_instance(self, plugin_type: PluginType, plugin_name: str) -> bool: return plugin_type in self._plugin_instances and plugin_name in self._plugin_instances[plugin_type] def get_instance(self, plugin_type: PluginType, plugin_name: str) -> Optional[object]: - """ - Get plugin instance by plugin type and plugin name + """Get plugin instance by plugin type and plugin name. Args: plugin_type: plugin type @@ -117,8 +113,7 @@ def get_instance(self, plugin_type: PluginType, plugin_name: str) -> Optional[ob return self._plugin_instances[plugin_type].get(plugin_name, None) def set_instance(self, plugin_type: PluginType, plugin_name: str, instance: object) -> None: - """ - Set plugin instance + """Set plugin instance. The slot is keyed by the registered type and name rather than by the instance, because not every registered object is a @@ -133,8 +128,7 @@ def set_instance(self, plugin_type: PluginType, plugin_name: str, instance: obje self._plugin_instances[plugin_type][plugin_name] = instance def remove_plugin_spec(self, plugin_spec: PluginSpec) -> None: - """ - Remove plugin specification + """Remove plugin specification. Args: plugin_spec: plugin specification diff --git a/trpc_sdk/plugin/_registry.py b/trpc_sdk/plugin/_registry.py index 76ff013..cb6add3 100644 --- a/trpc_sdk/plugin/_registry.py +++ b/trpc_sdk/plugin/_registry.py @@ -16,10 +16,10 @@ from trpc_sdk.abc import PluginInitPos from trpc_sdk.abc import PluginType from trpc_sdk.abc import TaskInfo + from ._plugin import DEFAULT_PLUGIN_MANAGER from ._plugin import PluginSpec - PluginFactoryType = TypeVar("PluginFactoryType", bound=Callable[[], object]) """Anything ``register_plugin`` accepts: a plugin class or a factory.""" @@ -31,8 +31,7 @@ def register_plugin( version: str = "", report: bool = False, ) -> Callable[[PluginFactoryType], PluginFactoryType]: - """ - Register plugin decorator + """Register plugin decorator. The decorated object only has to be callable with no arguments. A :class:`~trpc_sdk.abc.BasePlugin` subclass is the common case and is @@ -84,8 +83,7 @@ def register_task(task_name: str, task_info: TaskInfo): def get_plugin(plugin_type: PluginType, plugin_name: str) -> Optional[object]: - """ - Get plugin, building it on first use if no eager pass covered it + """Get plugin, building it on first use if no eager pass covered it. Args: plugin_type: plugin type @@ -116,8 +114,8 @@ def get_plugin(plugin_type: PluginType, plugin_name: str) -> Optional[object]: def get_plugin_class(plugin_type: PluginType, plugin_name: str) -> Optional[Callable[[], object]]: - """ - Get plugin class + """Get plugin class. + Args: plugin_type: plugin type plugin_name: plugin name diff --git a/trpc_sdk/rpcz/__init__.py b/trpc_sdk/rpcz/__init__.py index 7521ffc..d7aebed 100644 --- a/trpc_sdk/rpcz/__init__.py +++ b/trpc_sdk/rpcz/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """tRPC-Python rpcz module: per-request timing and size spans. The package is split by responsibility: diff --git a/trpc_sdk/rpcz/_span.py b/trpc_sdk/rpcz/_span.py index e8e0a37..3649a25 100644 --- a/trpc_sdk/rpcz/_span.py +++ b/trpc_sdk/rpcz/_span.py @@ -1,4 +1,8 @@ -# -*- coding: utf-8 -*- +# Tencent is pleased to support the open source community by making tRPC-Python available. +# +# Copyright (C) 2026 Tencent. All rights reserved. +# +# tRPC-Python is licensed under Apache-2.0. """Core span model for rpcz.""" import json diff --git a/trpc_sdk/rpcz/_storage.py b/trpc_sdk/rpcz/_storage.py index d2be7db..0a1c573 100644 --- a/trpc_sdk/rpcz/_storage.py +++ b/trpc_sdk/rpcz/_storage.py @@ -1,4 +1,8 @@ -# -*- coding: utf-8 -*- +# Tencent is pleased to support the open source community by making tRPC-Python available. +# +# Copyright (C) 2026 Tencent. All rights reserved. +# +# tRPC-Python is licensed under Apache-2.0. """Global in-process rpcz span storage. Both containers are plain module globals, so they are per-process: a diff --git a/trpc_sdk/rpcz/filter/__init__.py b/trpc_sdk/rpcz/filter/__init__.py index 42da848..4efec45 100644 --- a/trpc_sdk/rpcz/filter/__init__.py +++ b/trpc_sdk/rpcz/filter/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Filter-chain half of rpcz: sampling and span creation. Importing this package registers ``RpczServerFilter`` and diff --git a/trpc_sdk/rpcz/filter/_client_filter.py b/trpc_sdk/rpcz/filter/_client_filter.py index c852df5..302a847 100644 --- a/trpc_sdk/rpcz/filter/_client_filter.py +++ b/trpc_sdk/rpcz/filter/_client_filter.py @@ -1,4 +1,8 @@ -# -*- coding: utf-8 -*- +# Tencent is pleased to support the open source community by making tRPC-Python available. +# +# Copyright (C) 2026 Tencent. All rights reserved. +# +# tRPC-Python is licensed under Apache-2.0. """Rpcz client filter.""" from __future__ import annotations diff --git a/trpc_sdk/rpcz/filter/_sampler.py b/trpc_sdk/rpcz/filter/_sampler.py index a9a7a36..0218ce6 100644 --- a/trpc_sdk/rpcz/filter/_sampler.py +++ b/trpc_sdk/rpcz/filter/_sampler.py @@ -1,4 +1,8 @@ -# -*- coding: utf-8 -*- +# Tencent is pleased to support the open source community by making tRPC-Python available. +# +# Copyright (C) 2026 Tencent. All rights reserved. +# +# tRPC-Python is licensed under Apache-2.0. """Span id allocation and sampling decisions shared by both rpcz filters. Every object here is per-process and deliberately unsynchronized: span diff --git a/trpc_sdk/rpcz/filter/_server_filter.py b/trpc_sdk/rpcz/filter/_server_filter.py index 6e9516d..acf473c 100644 --- a/trpc_sdk/rpcz/filter/_server_filter.py +++ b/trpc_sdk/rpcz/filter/_server_filter.py @@ -1,4 +1,8 @@ -# -*- coding: utf-8 -*- +# Tencent is pleased to support the open source community by making tRPC-Python available. +# +# Copyright (C) 2026 Tencent. All rights reserved. +# +# tRPC-Python is licensed under Apache-2.0. """Rpcz server filter.""" from __future__ import annotations diff --git a/trpc_sdk/runtime/__init__.py b/trpc_sdk/runtime/__init__.py index 01a27cf..aaea698 100644 --- a/trpc_sdk/runtime/__init__.py +++ b/trpc_sdk/runtime/__init__.py @@ -99,7 +99,6 @@ from ._process import RpcTaskProcess from ._process import SeparateWorker from ._process import TaskProcess -from ._switches import use_c_task from ._threadmodel import BaseReactor from ._threadmodel import HandlerThreadInfo from ._threadmodel import InlineReactor @@ -161,5 +160,7 @@ "register_protocol_handle", "set_signal_handle", # Runtime feature switches - "use_c_task", + "run_server_signal_handle", + "create_worker", + "freeze_handler_thread_hooks", ] diff --git a/trpc_sdk/runtime/_common/__init__.py b/trpc_sdk/runtime/_common/__init__.py index c980063..ece69f0 100644 --- a/trpc_sdk/runtime/_common/__init__.py +++ b/trpc_sdk/runtime/_common/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Services every serving process shares, after trpc-cpp ``runtime/common``. SIGTERM callbacks, process metadata and the exit template do not depend on diff --git a/trpc_sdk/runtime/_common/_process_info.py b/trpc_sdk/runtime/_common/_process_info.py index 6997739..247cc5b 100644 --- a/trpc_sdk/runtime/_common/_process_info.py +++ b/trpc_sdk/runtime/_common/_process_info.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Listen addresses, handlers, and IPC metadata shared by server processes.""" from __future__ import annotations diff --git a/trpc_sdk/runtime/_common/_readiness.py b/trpc_sdk/runtime/_common/_readiness.py index 5e35ba2..ca0717e 100644 --- a/trpc_sdk/runtime/_common/_readiness.py +++ b/trpc_sdk/runtime/_common/_readiness.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Startup wait shared by the modes that fork serving children (separate, peer). Before forking, the parent creates one shared-memory byte per child @@ -31,6 +30,7 @@ from trpc_sdk.log import logger from trpc_sdk.utils import TimerScope from trpc_sdk.utils import registered_timer_tasks + from .._constants import CHILD_EXIT_POLL_INTERVAL from .._types import ChildProcessInfo @@ -56,13 +56,12 @@ def warn_unnamed_timers(owner: str, copies: int, unit: str) -> None: unit: What those processes are called ("rpc tasks", "peer workers"). """ unnamed = [ - info.cls.__name__ - for info in registered_timer_tasks() - if not info.name and info.scope is TimerScope.PROCESS + info.cls.__name__ for info in registered_timer_tasks() if not info.name and info.scope is TimerScope.PROCESS ] if unnamed and copies > 1: - logger.warning("[%s] timers %s have no name, so each of the %s %s runs them; " - "name one 'worker:' to run it once", owner, unnamed, copies, unit) + logger.warning( + "[%s] timers %s have no name, so each of the %s %s runs them; " + "name one 'worker:' to run it once", owner, unnamed, copies, unit) class ChildReadiness: diff --git a/trpc_sdk/runtime/_common/_shutdown.py b/trpc_sdk/runtime/_common/_shutdown.py index faa9ca1..4d3c145 100644 --- a/trpc_sdk/runtime/_common/_shutdown.py +++ b/trpc_sdk/runtime/_common/_shutdown.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """The exit template every serving process shares. Every role — the merge worker, the separate-mode I/O process, its rpc tasks, @@ -59,6 +58,7 @@ from typing import Optional from trpc_sdk.log import logger + from ._signals import run_worker_signal_handle from .._constants import CHILD_EXIT_GRACE_SECONDS from .._constants import CHILD_EXIT_POLL_INTERVAL @@ -300,7 +300,7 @@ def _arm_exit_killer(self) -> None: """ if self._exit_killer is not None: return - killer = threading.Timer(PARENT_EXIT_GRACE_SECONDS, os._exit, args=(1,)) + killer = threading.Timer(PARENT_EXIT_GRACE_SECONDS, os._exit, args=(1, )) killer.daemon = True killer.start() self._exit_killer = killer diff --git a/trpc_sdk/runtime/_common/_signals.py b/trpc_sdk/runtime/_common/_signals.py index 5525af9..25abf11 100644 --- a/trpc_sdk/runtime/_common/_signals.py +++ b/trpc_sdk/runtime/_common/_signals.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Business callbacks run when a server process receives SIGTERM. Master and worker processes keep separate callback lists because they shut down diff --git a/trpc_sdk/runtime/_constants.py b/trpc_sdk/runtime/_constants.py index c073d9d..b7f973e 100644 --- a/trpc_sdk/runtime/_constants.py +++ b/trpc_sdk/runtime/_constants.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Constants for the tRPC-Python runtime (process and thread model).""" from __future__ import annotations diff --git a/trpc_sdk/runtime/_merge_worker.py b/trpc_sdk/runtime/_merge_worker.py index fe4de54..adce6cf 100644 --- a/trpc_sdk/runtime/_merge_worker.py +++ b/trpc_sdk/runtime/_merge_worker.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Worker of ``merge`` mode: one process accepts, decodes and runs handlers. There is no dispatcher and no worker child process here. This worker *is* the @@ -66,6 +65,7 @@ from trpc_sdk.abc import ProcessType from trpc_sdk.log import logger from trpc_sdk.transport import UserProtocolTransport + from ._constants import LOOP_THREAD_STOP_TIMEOUT from ._threadmodel import HandlerThreadInfo from ._threadmodel import LoopThread @@ -232,8 +232,7 @@ def start_worker_process(self) -> None: that fails to listen aborts startup with status 1 rather than leaving the process half-listening. """ - logger.info("[merge worker] %s start_worker_process(), serving loops: %s", type(self).__name__, - self.thread_num) + logger.info("[merge worker] %s start_worker_process(), serving loops: %s", type(self).__name__, self.thread_num) for transport in self.transports: try: if isinstance(transport, UserProtocolTransport): diff --git a/trpc_sdk/runtime/_modes.py b/trpc_sdk/runtime/_modes.py index 0ff9708..2aea34c 100644 --- a/trpc_sdk/runtime/_modes.py +++ b/trpc_sdk/runtime/_modes.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Internal ``server.mode`` name -> worker class lookup. Three modes ship with the framework: ``merge``, where one process accepts and diff --git a/trpc_sdk/runtime/_process/__init__.py b/trpc_sdk/runtime/_process/__init__.py index 6879c00..419b09a 100644 --- a/trpc_sdk/runtime/_process/__init__.py +++ b/trpc_sdk/runtime/_process/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Processes the worker forks: task children, and ``separate`` / ``peer`` mode. Task children are the batch and inference processes a worker forks before it diff --git a/trpc_sdk/runtime/_process/_peer_worker.py b/trpc_sdk/runtime/_process/_peer_worker.py index 42aaa5f..7b5d300 100644 --- a/trpc_sdk/runtime/_process/_peer_worker.py +++ b/trpc_sdk/runtime/_process/_peer_worker.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Worker of ``peer`` mode: N equal processes, each a complete single-loop server. The process the application started is worker-0. Before its event loop exists @@ -53,6 +52,7 @@ from trpc_sdk.plugin import get_registered_tasks from trpc_sdk.telemetry import report_attr from trpc_sdk.transport import has_custom_scheduler + from .._common import ChildReadiness from .._common import warn_unnamed_timers from .._constants import CHILD_EXIT_GRACE_SECONDS diff --git a/trpc_sdk/runtime/_process/_rpc_task.py b/trpc_sdk/runtime/_process/_rpc_task.py index 0f2934c..175d5c7 100644 --- a/trpc_sdk/runtime/_process/_rpc_task.py +++ b/trpc_sdk/runtime/_process/_rpc_task.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Handler process forked by the separate-mode I/O worker.""" from __future__ import annotations @@ -24,6 +23,7 @@ from trpc_sdk.transport import RpcTaskConnection from trpc_sdk.transport import UserProtocolTransport from trpc_sdk.utils import PipeEnd + from .._constants import RPC_TASK_SENDER_PREFIX from .._threadmodel import HandlerThreadInfo from .._threadmodel import ThreadModel diff --git a/trpc_sdk/runtime/_process/_separate_worker.py b/trpc_sdk/runtime/_process/_separate_worker.py index 77b3d87..8ff6f3b 100644 --- a/trpc_sdk/runtime/_process/_separate_worker.py +++ b/trpc_sdk/runtime/_process/_separate_worker.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Worker of ``separate`` mode: this process does I/O, its children do the work. The split is the one thing this mode exists for. :class:`SeparateWorker` owns @@ -100,6 +99,7 @@ from trpc_sdk.utils import PipeEnd from trpc_sdk.utils import PipeKind from trpc_sdk.utils import create_pipe + from .._common import ChildReadiness from .._common import warn_unnamed_timers from .._constants import CHILD_EXIT_GRACE_SECONDS diff --git a/trpc_sdk/runtime/_process/_task_process.py b/trpc_sdk/runtime/_process/_task_process.py index 82b65fc..d6ae26a 100644 --- a/trpc_sdk/runtime/_process/_task_process.py +++ b/trpc_sdk/runtime/_process/_task_process.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Task child processes: background work moved off the worker processes. A task is registered with ``@trpc.task`` and runs in its own process, so slow @@ -97,8 +96,6 @@ def build_task_infos(default_task_num: int = 1) -> List[TaskInfo]: task.batch_size = task_handler.batch_size task.thread_num = task_handler.thread_num task.model_info = task_handler.model_info - task.use_c_task = task_handler.use_c_task - task.c_task_driver_params = task_handler.c_task_driver_params task.on_fork = task_handler.on_fork task.pause_heartbeat = task_handler.pause_heartbeat if task.pause_heartbeat: @@ -138,7 +135,8 @@ def __init__(self, task_infos: List[TaskInfo], senders: List[str]) -> None: # Sender name -> its end toward each task, index-aligned with # ``task_infos``. self._sender_pipes: Dict[str, List[Optional[PipeConnection]]] = { - name: [None] * len(task_infos) for name in self.sender_names + name: [None] * len(task_infos) + for name in self.sender_names } self._build() diff --git a/trpc_sdk/runtime/_switches.py b/trpc_sdk/runtime/_switches.py deleted file mode 100644 index 3ae3458..0000000 --- a/trpc_sdk/runtime/_switches.py +++ /dev/null @@ -1,73 +0,0 @@ -# Tencent is pleased to support the open source community by making tRPC-Python available. -# -# Copyright (C) 2026 Tencent. All rights reserved. -# -# tRPC-Python is licensed under Apache-2.0. - -"""Runtime switches, read from ``TRPC_*`` environment variables, that select a -server implementation path. - -Each switch picks between a pure-Python implementation and a native one. They -are read from the environment once, when this module is first imported, because -the choice must be stable for the whole lifetime of the process: the worker -decides which children to fork and how to wire the IPC pipes, and every child -must agree with that decision. - -Read a switch through its accessor at the point of use rather than binding the -value at import time. A module-level ``FLAG = use_c_task()`` snapshot taken -while the package is still loading can be captured before tests or embedding -code have had a chance to change it. - -The ``set_use_*`` functions exist for tests and for embedders that configure the -framework in code instead of through the environment; they must be called before -:meth:`~trpc_sdk.server.Server.serve` forks any child process. - -Only the task path is switchable now. The C dispatcher and trpcio switches went -away with the process topology that read them: there is no dispatcher child to -choose an implementation for, since the server process accepts for itself. The -native data plane those switches selected is archived under ``trpc_sdk/old_server``. -""" - -from __future__ import annotations - -import os -from dataclasses import dataclass - -from ._constants import ENV_C_TASK -from ._constants import ENV_ENABLED - - -@dataclass -class ServerFeatures: - """The set of implementation paths chosen for this process.""" - - # Run task handlers in the native task driver instead of the Python one. - c_task: bool = False - - @classmethod - def from_env(cls) -> ServerFeatures: - """Build the switch set from the ``TRPC_*`` environment variables.""" - return cls(c_task=os.environ.get(ENV_C_TASK) == ENV_ENABLED) - - -_FEATURES = ServerFeatures.from_env() - - -def use_c_task() -> bool: - """Return whether task processes run the native task driver.""" - return _FEATURES.c_task - - -def set_use_c_task(enabled: bool) -> None: - """Enable or disable the native task driver. - - Args: - enabled: True to run task handlers in the native driver. - """ - _FEATURES.c_task = enabled - - -def reload_from_env() -> None: - """Re-read every switch from the environment, discarding code overrides.""" - global _FEATURES # pylint: disable=global-statement - _FEATURES = ServerFeatures.from_env() diff --git a/trpc_sdk/runtime/_threadmodel/__init__.py b/trpc_sdk/runtime/_threadmodel/__init__.py index 4bfb7bd..f0ee673 100644 --- a/trpc_sdk/runtime/_threadmodel/__init__.py +++ b/trpc_sdk/runtime/_threadmodel/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Thread model of one serving process, after trpc-cpp ``runtime/threadmodel``. The threads of a ``merge`` worker are built from the pieces below. Which of diff --git a/trpc_sdk/runtime/_threadmodel/_handler_pool.py b/trpc_sdk/runtime/_threadmodel/_handler_pool.py index a7dfc80..7871230 100644 --- a/trpc_sdk/runtime/_threadmodel/_handler_pool.py +++ b/trpc_sdk/runtime/_threadmodel/_handler_pool.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Hand requests from I/O loops to handle threads under ``io_handle_type: separate``. The loop that reads a request is not the one that runs it. One @@ -184,8 +183,10 @@ def submit(self, run: CoroutineFactory) -> None: """ slots = self.slots count = len(slots) - start = get_next_worker(SchedulerParams(worker_conn_num=count, remote_ip="", session_id=0, stream_id=0, - target=SCHEDULE_TARGET_HANDLE_REQ)) % count + start = get_next_worker( + SchedulerParams( + worker_conn_num=count, remote_ip="", session_id=0, stream_id=0, + target=SCHEDULE_TARGET_HANDLE_REQ)) % count if self.max_concurrency <= 0: self._post(slots[start], self._start, run) return diff --git a/trpc_sdk/runtime/_threadmodel/_thread_hooks.py b/trpc_sdk/runtime/_threadmodel/_thread_hooks.py index 621a54f..0e12163 100644 --- a/trpc_sdk/runtime/_threadmodel/_thread_hooks.py +++ b/trpc_sdk/runtime/_threadmodel/_thread_hooks.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Per-serving-loop start/stop hooks, and which serving loop this thread runs. A *serving loop* is an event loop that runs user code (handlers, filters, diff --git a/trpc_sdk/runtime/_threadmodel/_thread_model.py b/trpc_sdk/runtime/_threadmodel/_thread_model.py index 391f77e..1666b6b 100644 --- a/trpc_sdk/runtime/_threadmodel/_thread_model.py +++ b/trpc_sdk/runtime/_threadmodel/_thread_model.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Thread model of one serving process: which loops a server transport serves on. A server transport is created before fork, but the loops it serves on only @@ -56,6 +55,7 @@ from trpc_sdk.log import logger + class BaseReactor(Protocol): """One event loop a server transport can serve on; owned by the runtime. @@ -87,11 +87,13 @@ def attach_socket(self, """Serve an accepted socket on the reactor's loop, without blocking.""" +# yapf: disable def connect_accepted(loop: asyncio.AbstractEventLoop, sock: socket.socket, protocol_factory: Callable[[], asyncio.BaseProtocol], ssl_context: Optional[Any], label: str) -> None: + # yapf: enable """Wrap an accepted socket in a transport on ``loop``; runs on ``loop``'s thread. ``connect_accepted_socket`` is a coroutine (it may have to perform a TLS @@ -121,13 +123,9 @@ def _on_attached(task: asyncio.Task) -> None: task.add_done_callback(_on_attached) -def attach_on_loop(loop: Optional[asyncio.AbstractEventLoop], - sock: socket.socket, - protocol_factory: Callable[[], asyncio.BaseProtocol], - ssl_context: Optional[Any], - *, - in_loop_thread: bool, - label: str) -> None: +def attach_on_loop(loop: Optional[asyncio.AbstractEventLoop], sock: socket.socket, + protocol_factory: Callable[[], asyncio.BaseProtocol], ssl_context: Optional[Any], *, + in_loop_thread: bool, label: str) -> None: """Serve an accepted socket on ``loop``, directly or by posting it there; never blocks. A loop that does not exist or is closed (the worker is shutting down) @@ -182,12 +180,8 @@ async def _call() -> Any: return asyncio.run_coroutine_threadsafe(_call(), loop) -def call_on_loop(loop: Optional[asyncio.AbstractEventLoop], - func: Callable[[], Any], - timeout: Optional[float], - *, - in_loop_thread: bool, - label: str) -> Any: +def call_on_loop(loop: Optional[asyncio.AbstractEventLoop], func: Callable[[], Any], timeout: Optional[float], *, + in_loop_thread: bool, label: str) -> Any: """Run ``func`` on ``loop`` and return its result, awaiting an awaitable one. On the loop's own thread there is nothing to post to: posting would wait @@ -368,11 +362,7 @@ class ThreadModel: _resources: Dict[int, List[Tuple[ResourceKind, Any]]] = field(default_factory=dict, repr=False) @classmethod - def single(cls, - loop: asyncio.AbstractEventLoop, - *, - worker: Any = None, - reuse_port: bool = False) -> ThreadModel: + def single(cls, loop: asyncio.AbstractEventLoop, *, worker: Any = None, reuse_port: bool = False) -> ThreadModel: """Serve everything on ``loop``, owned by the calling thread. Args: diff --git a/trpc_sdk/runtime/_threadmodel/_worker_view.py b/trpc_sdk/runtime/_threadmodel/_worker_view.py index d92c228..254ce43 100644 --- a/trpc_sdk/runtime/_threadmodel/_worker_view.py +++ b/trpc_sdk/runtime/_threadmodel/_worker_view.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """The worker as seen from a serving loop other than its own.""" from __future__ import annotations diff --git a/trpc_sdk/runtime/_types.py b/trpc_sdk/runtime/_types.py index 236c02d..c3d63b2 100644 --- a/trpc_sdk/runtime/_types.py +++ b/trpc_sdk/runtime/_types.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Shared types for runtime components. Holds the pre-fork records the worker / server adapter fill before any child exists. @@ -18,7 +17,6 @@ from multiprocessing import Process from typing import Any from typing import Callable -from typing import Dict from typing import List from typing import Optional from typing import Tuple @@ -27,6 +25,7 @@ from trpc_sdk.transport import encode_worker_msg_req from trpc_sdk.utils import PipeConnection + @dataclass class ChildProcessInfo: """One child this worker forked, plus how to build a replacement. diff --git a/trpc_sdk/runtime/_worker.py b/trpc_sdk/runtime/_worker.py index c18163f..cd5023c 100644 --- a/trpc_sdk/runtime/_worker.py +++ b/trpc_sdk/runtime/_worker.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """The worker role: the process that runs user handlers. In ``merge`` mode the worker binds the public addresses and runs handlers @@ -49,7 +48,6 @@ from trpc_sdk.abc import ProcessType from trpc_sdk.common import bind_lifetime_to_parent from trpc_sdk.common import execute_after_in_child -from trpc_sdk.common import execute_before_loop_run_in_child from trpc_sdk.common import set_current_process_var from trpc_sdk.config import TrpcConfig from trpc_sdk.log import logger @@ -248,7 +246,7 @@ def _task_senders(self) -> List[str]: """ from ._process import worker_sender_name # baseworker only have one sender to create pipe - # subclass will override this method and + # subclass will override this method and return [worker_sender_name(0)] def _task_pipe_owners(self) -> List[str]: @@ -308,9 +306,9 @@ def _warn_unsupported_reboot_child(self) -> None: fork, so the warning would repeat once per child. """ if TrpcConfig.server_config().reboot_child: - logger.warning("[%s] server.reboot_child is not supported in this version and is treated as false: " - "a child that dies takes the whole worker down, for the supervisor to restart", - self.name) + logger.warning( + "[%s] server.reboot_child is not supported in this version and is treated as false: " + "a child that dies takes the whole worker down, for the supervisor to restart", self.name) def _warn_threads_before_fork(self) -> None: """Warn when other threads are running before fork. @@ -511,8 +509,9 @@ def _wait_until_tasks_ready(self) -> None: previous = signal.signal(signal.SIGTERM, _raise_system_exit) if in_main_thread else None try: while not io_ready_reached(self.io_wait_count): - dead = [child.name for child in self.children - if child.process is not None and not child.process.is_alive()] + dead = [ + child.name for child in self.children if child.process is not None and not child.process.is_alive() + ] if dead: logger.error("[%s] child %s exited before the tasks were ready", self.name, dead) self._exit_code = 1 @@ -789,7 +788,8 @@ def _register_signal_handlers(self) -> None: self.loop.add_signal_handler(signal.SIGUSR2, self.memory_inspector.dump_to_file) self._watch_children() - def _listen_on(self, transport: BaseServerTransport, + def _listen_on(self, + transport: BaseServerTransport, loop: Optional[asyncio.AbstractEventLoop] = None) -> BaseServerTransport: """Call ``listen`` on ``transport`` and remember it. diff --git a/trpc_sdk/serialization/__init__.py b/trpc_sdk/serialization/__init__.py index d7b10ae..43a3769 100644 --- a/trpc_sdk/serialization/__init__.py +++ b/trpc_sdk/serialization/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """tRPC-Python serialization package: ContentType plugins and lookups. Public symbols are re-exported here. Implementation lives in ``_``-prefixed @@ -12,25 +11,23 @@ The package is split by responsibility: - :mod:`~trpc_sdk.serialization._types` — ``SerializationType``, ``JsonData``, ``Body`` -- :mod:`~trpc_sdk.serialization._serialization` — JSON / protobuf / noop / JCE / WUP plugins +- :mod:`~trpc_sdk.serialization._serialization` — JSON / protobuf / noop plugins - :mod:`~trpc_sdk.serialization._utils` — ``serialize`` / ``deserialize`` / ``get_serializer`` -- :mod:`~trpc_sdk.serialization._constants` — ``SerializationCode`` wire values +- :mod:`~trpc_sdk.serialization._constants` — ``SerializationType`` wire values Importing this package registers every built-in serializer. """ from __future__ import annotations -from ._serialization import JceSerializer from ._serialization import JsonSerializer from ._serialization import NoopSerializer from ._serialization import ProtoSerializer -from ._serialization import WupSerializer from ._serialization import json_to_pb_kwargs from ._serialization import pb_to_json_kwargs from ._types import Body from ._types import JsonData -from ._types import SerializationType +from ._constants import SerializationType from ._utils import deserialize from ._utils import get_serializer from ._utils import serialize @@ -47,6 +44,4 @@ "json_to_pb_kwargs", "ProtoSerializer", "NoopSerializer", - "JceSerializer", - "WupSerializer", ] diff --git a/trpc_sdk/serialization/_constants.py b/trpc_sdk/serialization/_constants.py index 4c3bf53..e567965 100644 --- a/trpc_sdk/serialization/_constants.py +++ b/trpc_sdk/serialization/_constants.py @@ -3,12 +3,11 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Shared constants for the serialization package. -:class:`SerializationCode` (ContentType) feeds +:class:`SerializationType` (ContentType) feeds :class:`~trpc_sdk.serialization._types.SerializationType`. 0-4 match -``TrpcContentEncodeType``. ``NOOP_ENCODE`` is 4 so it does not collide +``TrpcContentEncodeType``. ``NOOP`` is 4 so it does not collide with compress ``NOOP`` (0). 129 / 200 are local codes; ``UNSUPPORTED`` (-1) is a skip sentinel. """ @@ -18,9 +17,11 @@ from enum import IntEnum from enum import unique +from trpc_sdk._inner.pb import trpc_pb2 + @unique -class SerializationCode(IntEnum): +class SerializationType(IntEnum): """ContentType codes accepted by the serialization plugin table. Members are the wire values, so they can be written into a frame head @@ -31,13 +32,11 @@ class SerializationCode(IntEnum): UNSUPPORTED = -1 # Built-in serializers; 0-4 align with TrpcContentEncodeType. - PROTO = 0 - JCE = 1 - JSON = 2 - FLATBUFFER = 3 + PB = trpc_pb2.TRPC_PROTO_ENCODE + JSON = trpc_pb2.TRPC_JSON_ENCODE + FLATBUFFER = trpc_pb2.TRPC_FLATBUFFER_ENCODE # Distinct from compress NOOP = 0; this is TrpcContentEncodeType 4. - NOOP_ENCODE = 4 + NOOP = trpc_pb2.TRPC_NOOP_ENCODE # Local codes. Not present on TrpcContentEncodeType. FORM = 129 - WUP = 200 diff --git a/trpc_sdk/serialization/_serialization.py b/trpc_sdk/serialization/_serialization.py index 7cfd067..c4fbae3 100644 --- a/trpc_sdk/serialization/_serialization.py +++ b/trpc_sdk/serialization/_serialization.py @@ -3,17 +3,12 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Built-in ContentType serializer plugins. This is the merged copy of the historical ``serialization_json`` / ``serialization_proto`` / ``serialization_noop`` / ``serialization_jce`` / ``serialization_wup`` modules. Importing it (which :mod:`trpc_sdk.serialization` does) registers every built-in serializer, -JCE (1) and WUP (200) included. - -``jcepy`` is imported on first JCE / WUP use so processes that never -send those encodings do not need the optional dependency. """ from __future__ import annotations @@ -31,9 +26,10 @@ from trpc_sdk.abc import PluginInitPos from trpc_sdk.abc import PluginType from trpc_sdk.plugin import register_plugin + +from ._constants import SerializationType from ._types import Body from ._types import JsonData -from ._types import SerializationType # protobuf >= 5.26 renamed including_default_value_fields. _PROTOBUF_VERSION = tuple(int(x) for x in google.protobuf.__version__.split(".")[:2]) @@ -183,9 +179,9 @@ def deserialize(self, data: bytes, body: Any) -> None: body.ParseFromString(data) -@register_plugin(PluginType.SERIALIZATION, SerializationType.Noop, init_pos=PluginInitPos.WORKER) +@register_plugin(PluginType.SERIALIZATION, SerializationType.NOOP, init_pos=PluginInitPos.WORKER) class NoopSerializer(BaseSerializer): - """Identity serializer registered as ``SerializationType.Noop``. + """Identity serializer registered as ``SerializationType.NOOP``. Used when the frame already carries raw bytes (e.g. HTTP octet-stream). ``Body`` is the typed wrapper; a plain @@ -211,76 +207,3 @@ def deserialize(self, data: bytes, body: Any) -> None: """ if isinstance(body, Body): body.data = data - - -@register_plugin(PluginType.SERIALIZATION, SerializationType.JCE, init_pos=PluginInitPos.WORKER) -class JceSerializer(BaseSerializer): - """JCE serializer registered as ``SerializationType.JCE``. - - ``jcepy.core.tafcore`` is imported on first use. Output uses - ``JceOutputStream.bodySerilization`` (the jcepy spelling). Input - skips the leading int32 tag and copies deserialized fields onto - ``body``. - """ - - def serialize(self, body: Any) -> bytes: - """Serialize ``body`` with a JCE output stream. - - Args: - body: JCE-capable application object. - """ - from jcepy.core import tafcore - - oos = tafcore.JceOutputStream() - oos.bodySerilization(body) - return oos.getBuffer() - - def deserialize(self, data: bytes, body: Any) -> None: - """Populate ``body`` from JCE bytes. - - Args: - data: JCE-encoded body bytes. - body: Object whose attributes are overwritten from the - deserialized result. - """ - from jcepy.core import tafcore - - ios = tafcore.JceInputStream(data) - ios.read(tafcore.int32, 0, True) - res = ios.bodydeserialize(body) - for item in res.__dict__.items(): - setattr(body, str(item[0]), item[1]) - - -@register_plugin(PluginType.SERIALIZATION, SerializationType.Wup, init_pos=PluginInitPos.WORKER) -class WupSerializer(BaseSerializer): - """Taf WUP serializer registered as ``SerializationType.Wup``. - - ``jcepy.core.tafcore`` is imported on first use. WUP is the Taf - dictionary packet (``TafUniPacket``), not the raw JCE stream used - by :class:`JceSerializer`. - """ - - def serialize(self, body: Any) -> bytes: - """Serialize ``body`` with ``TafUniPacket.WUPserialize``. - - Args: - body: WUP-capable application object. - """ - from jcepy.core import tafcore - - up = tafcore.TafUniPacket() - return up.WUPserialize(body) - - def deserialize(self, data: bytes, body: Any) -> None: - """Populate ``body`` from a WUP packet. - - Args: - data: WUP-encoded body bytes. - body: Object to populate via ``WUPdeserialize``. - """ - from jcepy.core import tafcore - - up = tafcore.TafUniPacket() - up.deserialize(data) - up.WUPdeserialize(body) diff --git a/trpc_sdk/serialization/_types.py b/trpc_sdk/serialization/_types.py index 27d9f18..111a540 100644 --- a/trpc_sdk/serialization/_types.py +++ b/trpc_sdk/serialization/_types.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Shared type definitions for the serialization package.""" from __future__ import annotations @@ -14,24 +13,6 @@ from typing import Dict from typing import Optional -from ._constants import SerializationCode - - -class SerializationType: - """ContentType codes, aligned with ``TrpcContentEncodeType`` in ``trpc.proto``. - - ``Form`` / ``Wup`` are local codes; ``Unsupported`` is a skip sentinel. - """ - - PB = SerializationCode.PROTO - JCE = SerializationCode.JCE - JSON = SerializationCode.JSON - FlatBuffer = SerializationCode.FLATBUFFER - Noop = SerializationCode.NOOP_ENCODE - Unsupported = SerializationCode.UNSUPPORTED - Form = SerializationCode.FORM - Wup = SerializationCode.WUP - @dataclass class JsonData: diff --git a/trpc_sdk/serialization/_utils.py b/trpc_sdk/serialization/_utils.py index b88f7fd..1261cd4 100644 --- a/trpc_sdk/serialization/_utils.py +++ b/trpc_sdk/serialization/_utils.py @@ -3,13 +3,12 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Plugin lookups and body serialize helpers. ``get_serializer`` is a thin plugin-table lookup. Built-in serializers register from :mod:`trpc_sdk.serialization._serialization`, which the package ``__init__`` imports. ``serialize`` / ``deserialize`` then treat -``SerializationType.Unsupported`` as a no-op without looking up a plugin. +``SerializationType.UNSUPPORTED`` as a no-op without looking up a plugin. """ from __future__ import annotations @@ -20,7 +19,8 @@ from trpc_sdk.abc import BaseSerializer from trpc_sdk.abc import PluginType from trpc_sdk.plugin import get_plugin -from ._types import SerializationType + +from ._constants import SerializationType def get_serializer(serialization_type: int) -> Optional[BaseSerializer]: @@ -36,7 +36,7 @@ def get_serializer(serialization_type: int) -> Optional[BaseSerializer]: def serialize(serialization_type: int, body: Any) -> bytes: """Serialize ``body`` with the plugin registered for ``serialization_type``. - ``None`` and ``SerializationType.Unsupported`` return empty bytes + ``None`` and ``SerializationType.UNSUPPORTED`` return empty bytes without touching the plugin table. Any other code looks up the plugin and calls ``serialize``; an unregistered type fails there. @@ -48,7 +48,7 @@ def serialize(serialization_type: int, body: Any) -> bytes: if body is None: return empty_buffer - if serialization_type == SerializationType.Unsupported: + if serialization_type == SerializationType.UNSUPPORTED: return empty_buffer serializer = get_serializer(serialization_type) @@ -59,7 +59,7 @@ def deserialize(serialization_type: int, data: Optional[bytes], body: Any) -> An """Populate ``body`` from ``data`` using the registered serializer. ``None`` body, ``None`` / empty ``data``, and - ``SerializationType.Unsupported`` return ``None`` without a plugin + ``SerializationType.UNSUPPORTED`` return ``None`` without a plugin lookup. Otherwise the plugin's ``deserialize`` mutates ``body`` in place and this helper returns ``None``. @@ -71,7 +71,7 @@ def deserialize(serialization_type: int, data: Optional[bytes], body: Any) -> An if body is None or not data: return None - if serialization_type == SerializationType.Unsupported: + if serialization_type == SerializationType.UNSUPPORTED: return None serializer = get_serializer(serialization_type) diff --git a/trpc_sdk/server/__init__.py b/trpc_sdk/server/__init__.py index 00efc53..13adde9 100644 --- a/trpc_sdk/server/__init__.py +++ b/trpc_sdk/server/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """tRPC-Python server module: the service layer. The application parses the YAML config into a :class:`Server`, which builds diff --git a/trpc_sdk/server/_adapter.py b/trpc_sdk/server/_adapter.py index 0d92aa7..8a79812 100644 --- a/trpc_sdk/server/_adapter.py +++ b/trpc_sdk/server/_adapter.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Options and listen-endpoint tables the worker reads at startup. :class:`TrpcServerAdapter` lives in the same process as the worker. It does @@ -28,7 +27,6 @@ import sys import threading -from typing import TYPE_CHECKING from typing import Callable from typing import List from typing import Optional @@ -41,8 +39,7 @@ from trpc_sdk.runtime import ProcessInfo from trpc_sdk.runtime import WorkerInfo -if TYPE_CHECKING: - from trpc_sdk.server import ServerOption +from ._option import ServerOption class TrpcServerAdapter(BaseTrpcServerAdapter): diff --git a/trpc_sdk/server/_constants.py b/trpc_sdk/server/_constants.py index db5c5eb..72b1ff4 100644 --- a/trpc_sdk/server/_constants.py +++ b/trpc_sdk/server/_constants.py @@ -3,14 +3,12 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Constants for tRPC-Python Server Module.""" from __future__ import annotations from trpc_sdk.runtime import MODE_MERGE - # ServerOption defaults (YAML ``server:``, one per Server process). # Process model. merge keeps a request in one process; separate forks rpc diff --git a/trpc_sdk/server/_cython/__init__.py b/trpc_sdk/server/_cython/__init__.py index 012b79c..acf25ae 100644 --- a/trpc_sdk/server/_cython/__init__.py +++ b/trpc_sdk/server/_cython/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Cython per-service handler path and service factory.""" from ._service import ServiceAdapter # pyright: ignore[reportMissingModuleSource] diff --git a/trpc_sdk/server/_option.py b/trpc_sdk/server/_option.py index 9fd8a9f..f9f2542 100644 --- a/trpc_sdk/server/_option.py +++ b/trpc_sdk/server/_option.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Process-model and per-service options consumed by Server / TrpcServerAdapter. ``create_server(yaml)`` copies YAML ``server:`` fields onto :class:`ServerOption` @@ -35,6 +34,7 @@ from trpc_sdk.stream import StreamDispatcher from trpc_sdk.transport import DefaultServerTransport from trpc_sdk.transport import DefaultServerTransportOption + from ._constants import DEFAULT_ADDRESS from ._constants import DEFAULT_CLOSE_WAIT_TIME from ._constants import DEFAULT_COMPRESS_TYPE diff --git a/trpc_sdk/server/_option_resolver.py b/trpc_sdk/server/_option_resolver.py index 92268e1..19a49c2 100644 --- a/trpc_sdk/server/_option_resolver.py +++ b/trpc_sdk/server/_option_resolver.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Resolution of the thread-model and process-model fields of :class:`ServerOption`. :func:`~trpc_sdk.server.create_server` first calls :func:`apply_process_model`, @@ -41,7 +40,6 @@ import os import sys -from typing import TYPE_CHECKING from typing import Dict from typing import List from typing import Optional @@ -59,6 +57,7 @@ from trpc_sdk.runtime import MODE_SPELLINGS from trpc_sdk.runtime import PROCESS_MODEL_MULTI from trpc_sdk.runtime import PROCESS_MODEL_SINGLE + from ._constants import DEFAULT_HANDLE_THREAD_NUM from ._constants import DEFAULT_HANDLER_MAX_CONCURRENCY from ._constants import DEFAULT_HANDLER_QUEUE_SIZE @@ -69,9 +68,7 @@ from ._constants import DEFAULT_WORKER_NUM from ._constants import THREADS_PER_CPU_WARN from ._constants import WORKERS_PER_CPU_WARN - -if TYPE_CHECKING: - from ._option import ServerOption +from ._option import ServerOption # ``global.processmodel.io_handle_type`` spellings accepted under # ``multi_process`` only: there, merging I/O and handlers means peer mode. @@ -173,8 +170,9 @@ def _apply_single_process(option: ServerOption, model: ProcessModel) -> None: if io_handle_type == IO_HANDLE_TYPE_MERGE: thread_num = model.handle_num or model.io_num if model.io_num and model.handle_num and model.io_num != model.handle_num: - logger.warning("global.processmodel: io_num=%s and handle_num=%s must be equal when io_handle_type is " - "merge; using handle_num=%s", model.io_num, model.handle_num, model.handle_num) + logger.warning( + "global.processmodel: io_num=%s and handle_num=%s must be equal when io_handle_type is " + "merge; using handle_num=%s", model.io_num, model.handle_num, model.handle_num) option.io_thread_num = thread_num option.handle_thread_num = DEFAULT_HANDLE_THREAD_NUM return @@ -206,8 +204,9 @@ def _apply_multi_process(option: ServerOption, model: ProcessModel) -> None: if io_handle_type == IO_HANDLE_TYPE_SEPARATE: option.mode = MODE_SEPARATE if model.io_num not in (0, 1): - logger.warning("global.processmodel: io_num=%s, but multi_process separate runs a single I/O process; " - "using 1", model.io_num) + logger.warning( + "global.processmodel: io_num=%s, but multi_process separate runs a single I/O process; " + "using 1", model.io_num) else: option.mode = MODE_PEER if model.io_num: @@ -242,8 +241,7 @@ def resolve_server_option(option: ServerOption, services: List[ServerService]) - elif option.mode == MODE_PEER: _resolve_peer_options(option) elif option.worker_num != DEFAULT_WORKER_NUM: - logger.warning("ServerOption.worker_num=%s is only read in separate and peer mode; ignored", - option.worker_num) + logger.warning("ServerOption.worker_num=%s is only read in separate and peer mode; ignored", option.worker_num) def _canonical_name(value: str) -> str: @@ -370,8 +368,9 @@ def _warn_if_oversized(field_name: str, value: int) -> None: """ limit = THREADS_PER_CPU_WARN * (os.cpu_count() or 1) if value > limit: - logger.warning("global.processmodel.%s=%s is more than %s times the CPU count (%s); keeping it, but it is likely too many", - field_name, value, THREADS_PER_CPU_WARN, os.cpu_count()) + logger.warning( + "global.processmodel.%s=%s is more than %s times the CPU count (%s); keeping it, but it is likely too many", + field_name, value, THREADS_PER_CPU_WARN, os.cpu_count()) def _resolve_ready_timeout(value: int, waits_for_startup: bool) -> int: @@ -441,8 +440,9 @@ def _resolve_separate_options(option: ServerOption, services: List[ServerService _warn_single_rpc_task_on_macos(option.worker_num, services) if (option.handler_max_concurrency != DEFAULT_HANDLER_MAX_CONCURRENCY or option.handler_queue_size != DEFAULT_HANDLER_QUEUE_SIZE): - logger.warning("server.handler_max_concurrency / handler_queue_size are not supported in separate mode yet " - "and are ignored (got %s / %s)", option.handler_max_concurrency, option.handler_queue_size) + logger.warning( + "server.handler_max_concurrency / handler_queue_size are not supported in separate mode yet " + "and are ignored (got %s / %s)", option.handler_max_concurrency, option.handler_queue_size) if option.tcp_reuse_port: logger.info("server.tcp_reuse_port is on: several processes may bind the same TCP port at once") @@ -464,8 +464,9 @@ def _resolve_worker_num(value: int) -> int: logger.warning("global.processmodel.handle_num=%s is negative; using %s", value, default) return default if value > WORKERS_PER_CPU_WARN * default: - logger.warning("global.processmodel.handle_num=%s is more than %s times the CPU count (%s); keeping it, " - "but that many processes is likely too many", value, WORKERS_PER_CPU_WARN, default) + logger.warning( + "global.processmodel.handle_num=%s is more than %s times the CPU count (%s); keeping it, " + "but that many processes is likely too many", value, WORKERS_PER_CPU_WARN, default) return value @@ -483,11 +484,14 @@ def _warn_single_rpc_task_on_macos(rpc_task_num: int, services: List[ServerServi """ if sys.platform != "darwin" or rpc_task_num <= 1: return - self_bound = [service.name for service in services - if "tcp" not in service.network or "http" in service.protocol or "sse" in service.protocol] + self_bound = [ + service.name for service in services + if "tcp" not in service.network or "http" in service.protocol or "sse" in service.protocol + ] if self_bound: - logger.warning("global.processmodel.handle_num=%s on macOS: services %s are bound by each rpc task with SO_REUSEPORT, " - "which macOS does not balance, so one rpc task will handle them", rpc_task_num, self_bound) + logger.warning( + "global.processmodel.handle_num=%s on macOS: services %s are bound by each rpc task with SO_REUSEPORT, " + "which macOS does not balance, so one rpc task will handle them", rpc_task_num, self_bound) def _resolve_peer_options(option: ServerOption) -> None: @@ -506,5 +510,6 @@ def _resolve_peer_options(option: ServerOption) -> None: logger.warning("global.processmodel.handle_num=1 in peer mode: a single worker, i.e. merge mode with a " "supervisor around it") if sys.platform == "darwin" and value > 1: - logger.warning("global.processmodel.handle_num=%s on macOS: SO_REUSEPORT does not balance load there, " - "so in practice one peer worker handles every request", value) + logger.warning( + "global.processmodel.handle_num=%s on macOS: SO_REUSEPORT does not balance load there, " + "so in practice one peer worker handles every request", value) diff --git a/trpc_sdk/server/_registry.py b/trpc_sdk/server/_registry.py index 0bb9b5c..5665490 100644 --- a/trpc_sdk/server/_registry.py +++ b/trpc_sdk/server/_registry.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Background naming-service registration for one :class:`~trpc_sdk.server._cython._service.ServiceAdapter`. :func:`start_service_registry` gives every service with a configured @@ -81,8 +80,7 @@ def __init__( self._running: bool = True self.deregister_done: threading.Semaphore = deregister_done self.daemon = daemon - self._loop: asyncio.AbstractEventLoop = get_async_lib( - TrpcConfig.global_config().enable_uvloop).new_event_loop() + self._loop: asyncio.AbstractEventLoop = get_async_lib(TrpcConfig.global_config().enable_uvloop).new_event_loop() def terminate(self) -> None: """Ask the retry loop to stop and cancel the in-flight register task. @@ -144,9 +142,7 @@ def start(self) -> None: """ if self.opt.registry_option == 1: warm_up() - self.thread = RegistryThread(self._register, - self._deregister, - self.opt.app.server_adapter.registry_semaphore) + self.thread = RegistryThread(self._register, self._deregister, self.opt.app.server_adapter.registry_semaphore) self.thread.start() def stop(self) -> None: diff --git a/trpc_sdk/server/_server.py b/trpc_sdk/server/_server.py index 3f50cac..3310f6c 100644 --- a/trpc_sdk/server/_server.py +++ b/trpc_sdk/server/_server.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Service table and the startup order that turns this process into a worker. :class:`Server` is the object application code holds after :func:`create_server`. @@ -58,6 +57,7 @@ from trpc_sdk.transport import get_server_transport from trpc_sdk.utils import find_free_port from trpc_sdk.utils import get_async_lib + from ._adapter import TrpcServerAdapter from ._option import ServerOption from ._option import ServiceOption @@ -136,8 +136,9 @@ def register(self, service_desc: ServiceDesc, fix_rpc_name: bool = False) -> Non """ for desc in list(service_desc.methods or ()) + list(service_desc.streams or ()): if not _is_coroutine_handler(desc.impl_func): - logger.warning("handler %s is not 'async def'; it runs as a task on a serving loop " - "and the framework keeps no thread pool for blocking handlers", desc.name) + logger.warning( + "handler %s is not 'async def'; it runs as a task on a serving loop " + "and the framework keeps no thread pool for blocking handlers", desc.name) for service_adapter in self.service_adapters.values(): service_adapter.register(service_desc, fix_rpc_name) diff --git a/trpc_sdk/server/_types.py b/trpc_sdk/server/_types.py index 012fdc1..c8516aa 100644 --- a/trpc_sdk/server/_types.py +++ b/trpc_sdk/server/_types.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Shared types for the server service layer. Holds the queue-wait policy and sliding window used by ``ServiceAdapter``. The diff --git a/trpc_sdk/server/_utils.py b/trpc_sdk/server/_utils.py index 8afbd0c..8dfc9b9 100644 --- a/trpc_sdk/server/_utils.py +++ b/trpc_sdk/server/_utils.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Bind-info file writer used by :func:`~trpc_sdk.server.create_server`.""" from __future__ import annotations diff --git a/trpc_sdk/stream/__init__.py b/trpc_sdk/stream/__init__.py index 4b852da..89ce8b1 100644 --- a/trpc_sdk/stream/__init__.py +++ b/trpc_sdk/stream/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """tRPC-Python stream package: public streaming RPC. Public symbols are re-exported here. Callers should ``from trpc_sdk.stream @@ -23,10 +22,10 @@ from __future__ import annotations -from ._client import Client +from ._client import ClientStreamFactory from ._client import ClientStream -from ._client import create_stream_client -from ._client import default_stream_client +from ._client import create_client_stream_factory +from ._client import get_default_client_stream_factory from ._constants import DEFAULT_INIT_WINDOW_SIZE from ._constants import MAX_INIT_WINDOW_SIZE from ._constants import MIN_INIT_WINDOW_SIZE @@ -38,9 +37,6 @@ from ._server import StreamDispatcher from ._server import create_server_stream from ._server import create_stream_dispatcher -from ._stream import Stream -from ._stream_factory import create_stream -from ._types import ClientStreamDesc __all__ = [ # Constants @@ -54,12 +50,9 @@ "ReceiveControl", # Client "ClientStream", - "ClientStreamDesc", - "Client", - "Stream", - "create_stream", - "create_stream_client", - "default_stream_client", + "ClientStreamFactory", + "create_client_stream_factory", + "get_default_client_stream_factory", # Server "ServerStream", "ServerStreamHandle", diff --git a/trpc_sdk/stream/_client.py b/trpc_sdk/stream/_client.py index 4b14d46..a8ea929 100644 --- a/trpc_sdk/stream/_client.py +++ b/trpc_sdk/stream/_client.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Client half of the tRPC streaming protocol. A :class:`ClientStream` is one RPC call. ``send_msg`` encodes a DATA @@ -11,7 +10,7 @@ the socket; it pops a queue filled by the background :meth:`ClientStream.dispatch` task that is the only reader of the client transport. -Stream ids ``0..99`` are reserved; :func:`create_stream_client` starts at +Stream ids ``0..99`` are reserved; :func:`create_client_stream` starts at :data:`STREAM_ID` so the first call is ``100``. """ @@ -30,6 +29,7 @@ from trpc_sdk.client import Options from trpc_sdk.client import get_options from trpc_sdk.client import update_message +from trpc_sdk.abc import ClientStreamDesc from trpc_sdk.common import get_or_create_event_loop from trpc_sdk.compressor import decompress from trpc_sdk.exceptions import ClientDecodeError @@ -41,11 +41,10 @@ from trpc_sdk._inner import trpc_pb2 from ._constants import DEFAULT_INIT_WINDOW_SIZE from ._constants import STREAM_ID +from ._client_stream_conn import create_client_stream_connection from ._flow_control import ReceiveControl from ._flow_control import SendControl from ._options import get_window_size -from ._stream_factory import create_stream -from ._types import ClientStreamDesc # pylint: disable=too-many-instance-attributes @@ -57,13 +56,12 @@ class ClientStream(BaseClientStream): peer's CLOSE (or a recv failure treated as CLOSE). """ - def __init__(self, ctx: TrpcContext, desc: ClientStreamDesc, stream_id: int, method: str) -> None: + def __init__(self, ctx: TrpcContext, desc: ClientStreamDesc, stream_id: int) -> None: self.ctx = ctx # Call context bound at construction; not replaced later. self.opts: Optional[Options] = None # Resolved in init_stream; None before the INIT handshake. self.desc = desc # Method descriptor (RPC name plus client-streams flag). - self.method = method # RPC name stamped on INIT / DATA / FEEDBACK frames. self.stream_id = stream_id # Allocated by Client; 0..99 are reserved. - self.stream = create_stream() # Transport-level stream used for send / recv / close. + self.stream = create_client_stream_connection() # Transport-level stream used for send / recv / close. self.recv_queue = Queue() # Filled only by dispatch(); recv_msg never touches the socket. self.client_closed = False # We sent CLOSE. self.server_closed = False # Peer sent CLOSE, or a recv failure was treated as one. @@ -156,7 +154,7 @@ async def send_msg(self, msg: Any) -> None: frame_head = create_frame_head(trpc_pb2.TRPC_STREAM_FRAME, trpc_pb2.TRPC_STREAM_FRAME_DATA, self.stream_id) client_msg.set_frame_head(frame_head) client_msg.set_stream_id(self.stream_id) - client_msg.set_client_rpc_name(self.method) + client_msg.set_client_rpc_name(self.desc.name) await self.stream.send(ctx, msg) @@ -176,7 +174,7 @@ def handle_frame(self, ctx: TrpcContext, rsp_data: bytes) -> None: if frame_state == trpc_pb2.TRPC_STREAM_FRAME_DATA: self.recv_queue.push((rsp_data, None)) return - + if frame_state == trpc_pb2.TRPC_STREAM_FRAME_CLOSE: err = msg.client_rsp_err or EOFError self.recv_queue.push((b"", err), True) @@ -186,7 +184,7 @@ def handle_frame(self, ctx: TrpcContext, rsp_data: bytes) -> None: self.opts.s_control.close_control() self.server_closed = True return - + if frame_state == trpc_pb2.TRPC_STREAM_FRAME_FEEDBACK: self.handle_feedback(msg) @@ -201,8 +199,7 @@ def handle_feedback(self, msg: TrpcMessage) -> None: ClientDecodeError: ``stream_frame`` is the wrong type. """ if not isinstance(msg.stream_frame, trpc_pb2.TrpcStreamFeedBackMeta): - raise ClientDecodeError( - "msg.stream_frame feedback fields must be type of TrpcStreamFeedBackMeta") + raise ClientDecodeError("msg.stream_frame feedback fields must be type of TrpcStreamFeedBackMeta") if self.opts.s_control: self.opts.s_control.update_window(msg.stream_frame.window_size_increment) @@ -243,7 +240,7 @@ async def feedback(self, increment: int) -> None: frame_head = create_frame_head(trpc_pb2.TRPC_STREAM_FRAME, trpc_pb2.TRPC_STREAM_FRAME_FEEDBACK, self.stream_id) msg.set_frame_head(frame_head) msg.set_stream_id(self.stream_id) - msg.set_client_rpc_name(self.method) + msg.set_client_rpc_name(self.desc.name) feedback_meta = trpc_pb2.TrpcStreamFeedBackMeta() feedback_meta.window_size_increment = increment @@ -282,7 +279,7 @@ async def init_stream(self, options: List[Callable]) -> None: frame_head = create_frame_head(trpc_pb2.TRPC_STREAM_FRAME, trpc_pb2.TRPC_STREAM_FRAME_INIT, self.stream_id) msg.set_frame_head(frame_head) msg.set_stream_id(self.stream_id) - msg.set_client_rpc_name(self.method) + msg.set_client_rpc_name(self.desc.name) await self._rpc_stream(ctx, msg, options) @@ -340,43 +337,46 @@ async def invoke(self, ctx, msg, client_options: Options) -> None: # pylint: disable=too-few-public-methods -class Client: - """Allocates monotonically increasing stream ids and opens streams.""" +class ClientStreamFactory: + """Factory for creating client streams.""" def __init__(self, stream_id: int) -> None: self.stream_id = stream_id async def create_client_stream( - self, - ctx: TrpcContext, - desc: ClientStreamDesc, - method: str, - options: List[Callable], + self, + ctx: TrpcContext, + desc: ClientStreamDesc, + options: List[Callable], ) -> ClientStream: """Allocate a stream id, construct the stream, and run INIT. Args: ctx: Call context. - desc: Method descriptor (name plus client-streams flag). - method: RPC name stamped on INIT / DATA frames. + desc: Method descriptor. options: Client option callables. Returns: An initialized :class:`ClientStream`. """ self.stream_id += 1 - client_stream = ClientStream(ctx, desc, self.stream_id, method) + client_stream = ClientStream(ctx, desc, self.stream_id) await client_stream.init_stream(options) return client_stream -def create_stream_client() -> Client: +def create_client_stream_factory() -> ClientStreamFactory: """Build a public-protocol stream client starting at :data:`STREAM_ID`. Returns: - A :class:`Client` whose first allocated id is ``100``. + A :class:`ClientStreamFactory` whose first allocated id is ``100``. """ - return Client(STREAM_ID) + return ClientStreamFactory(STREAM_ID) + + +_client_stream_factory = create_client_stream_factory() -default_stream_client = create_stream_client() +def get_default_client_stream_factory() -> ClientStreamFactory: + """Get the default client stream factory.""" + return _client_stream_factory diff --git a/trpc_sdk/stream/_stream.py b/trpc_sdk/stream/_client_stream_conn.py similarity index 91% rename from trpc_sdk/stream/_stream.py rename to trpc_sdk/stream/_client_stream_conn.py index 5e72c68..27b90f0 100644 --- a/trpc_sdk/stream/_stream.py +++ b/trpc_sdk/stream/_client_stream_conn.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Client-side stream implementations. ``Stream`` is the public ``trpc_sdk.stream`` protocol transport. @@ -27,7 +26,7 @@ from trpc_sdk.utils import now_ms -class Stream(BaseClientStreamConnection): +class ClientStreamConnection(BaseClientStreamConnection): """Client stream for the public ``trpc_sdk.stream`` protocol. ``opts`` is filled by :meth:`start` and reused by send / recv / close @@ -131,3 +130,13 @@ async def start(self, ctx: TrpcContext, client_options: Options) -> Options: client_options.node.cost_time = cost return client_options + + +def create_client_stream_connection() -> ClientStreamConnection: + """Build a client stream for the public ``trpc_sdk.stream`` protocol. + + Every call needs its own object: ``ClientStreamConnection.opts`` stays ``None`` until + ``start()`` fills in the per-call transport, codec and deadline, so a + shared instance would leak one call's options into the next. + """ + return ClientStreamConnection() diff --git a/trpc_sdk/stream/_constants.py b/trpc_sdk/stream/_constants.py index cf5403e..1fdb95e 100644 --- a/trpc_sdk/stream/_constants.py +++ b/trpc_sdk/stream/_constants.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Constants for the tRPC streaming protocol. Window bounds are the legal range of ``trpc_pb2.TrpcStreamInitMeta.init_window_size``. diff --git a/trpc_sdk/stream/_flow_control.py b/trpc_sdk/stream/_flow_control.py index 4186a74..db21fa8 100644 --- a/trpc_sdk/stream/_flow_control.py +++ b/trpc_sdk/stream/_flow_control.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Credit-based flow control for one stream. :class:`SendControl` gates outgoing DATA until the peer's window has diff --git a/trpc_sdk/stream/_options.py b/trpc_sdk/stream/_options.py index f3560fe..52f07fc 100644 --- a/trpc_sdk/stream/_options.py +++ b/trpc_sdk/stream/_options.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Option helpers for the streaming protocol. Window size is the one stream-level option that needs clamping before it diff --git a/trpc_sdk/stream/_server.py b/trpc_sdk/stream/_server.py index 178e7e2..e235ae1 100644 --- a/trpc_sdk/stream/_server.py +++ b/trpc_sdk/stream/_server.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Server half of the tRPC streaming protocol. :class:`ServerStream` is one accepted call. ``send_msg`` encodes a DATA @@ -383,7 +382,8 @@ def abort_session(self, session_id: int) -> None: server_stream.s_control.close_control() except Exception as err: # pylint: disable=broad-except logger.error(self._error_msg(f"[server stream] abort failed: {err!r}", session_id, - server_stream.stream_id), exc_info=True) + server_stream.stream_id), + exc_info=True) self.opts.codec.drop_session(session_id) def get_server_stream(self, ctx: TrpcContext) -> ServerStream: @@ -418,10 +418,10 @@ def handle_error(self, ctx: TrpcContext, req_buf: bytes) -> None: pass async def start_stream_handler( - self, - ctx: TrpcContext, - server_stream: ServerStream, - stream_handle: ServerStreamHandle, + self, + ctx: TrpcContext, + server_stream: ServerStream, + stream_handle: ServerStreamHandle, ) -> None: """Run the business handler, then CLOSE or RESET the stream. @@ -561,10 +561,10 @@ def handle_feedback(self, ctx: TrpcContext) -> None: server_stream.s_control.update_window(msg.stream_frame.window_size_increment) async def handle_by_stream_frame_type( - self, - ctx: TrpcContext, - stream_handle: ServerStreamHandle, - body: bytes, + self, + ctx: TrpcContext, + stream_handle: ServerStreamHandle, + body: bytes, ) -> bytes: """Switch on ``frame_state`` and handle INIT / DATA / CLOSE / FEEDBACK. diff --git a/trpc_sdk/stream/_stream_factory.py b/trpc_sdk/stream/_stream_factory.py deleted file mode 100644 index 5075b51..0000000 --- a/trpc_sdk/stream/_stream_factory.py +++ /dev/null @@ -1,27 +0,0 @@ -# Tencent is pleased to support the open source community by making tRPC-Python available. -# -# Copyright (C) 2026 Tencent. All rights reserved. -# -# tRPC-Python is licensed under Apache-2.0. - -"""Client stream factories. - -Each outbound stream call needs a fresh object: :attr:`Stream.opts` stays -``None`` until :meth:`~trpc_sdk.stream.Stream.start` fills in the per-call -transport, codec and deadline. A shared instance would leak one call's -options into the next. -""" - -from __future__ import annotations - -from ._stream import Stream - - -def create_stream() -> Stream: - """Build a client stream for the public ``trpc_sdk.stream`` protocol. - - Every call needs its own object: ``Stream.opts`` stays ``None`` until - ``start()`` fills in the per-call transport, codec and deadline, so a - shared instance would leak one call's options into the next. - """ - return Stream() diff --git a/trpc_sdk/stream/_types.py b/trpc_sdk/stream/_types.py deleted file mode 100644 index 37ef6d8..0000000 --- a/trpc_sdk/stream/_types.py +++ /dev/null @@ -1,27 +0,0 @@ -# Tencent is pleased to support the open source community by making tRPC-Python available. -# -# Copyright (C) 2026 Tencent. All rights reserved. -# -# tRPC-Python is licensed under Apache-2.0. - -"""Shared type definitions for the stream package. - -:class:`ClientStreamDesc` describes one client-side streaming method. -""" - -from __future__ import annotations - -from dataclasses import dataclass - - -@dataclass -class ClientStreamDesc: - """Describes one client-side streaming method. - - Attributes: - stream_name: RPC name written onto the INIT / DATA frames. - client_streams: Unused by this package; kept for stub generators. - """ - - stream_name: str = "" - client_streams: bool = False diff --git a/trpc_sdk/task/__init__.py b/trpc_sdk/task/__init__.py index d6d2ed1..62f5e5e 100644 --- a/trpc_sdk/task/__init__.py +++ b/trpc_sdk/task/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """tRPC-Python task process module. A task is a child process the server forks before its event loop starts, so a diff --git a/trpc_sdk/task/_connection.py b/trpc_sdk/task/_connection.py index a8a62f2..7384320 100644 --- a/trpc_sdk/task/_connection.py +++ b/trpc_sdk/task/_connection.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """asyncio protocols for both ends of the worker <-> task IPC pipe. The worker forks each task child before its event loop starts; the socketpair @@ -26,6 +25,7 @@ from trpc_sdk.log import logger from trpc_sdk.telemetry import report_attr from trpc_sdk.transport import InnerStreamParser + from ._cython import inner_decode_task_rsp from ._cython import receive_pkg_from_worker from ._utils import receive_from_task diff --git a/trpc_sdk/task/_consumer.py b/trpc_sdk/task/_consumer.py index e74c6be..461cda3 100644 --- a/trpc_sdk/task/_consumer.py +++ b/trpc_sdk/task/_consumer.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Batch consumers running inside a task child process. Requests and responses cross the worker/task boundary through two C queues. diff --git a/trpc_sdk/task/_cython/__init__.py b/trpc_sdk/task/_cython/__init__.py index ea306ba..7650331 100644 --- a/trpc_sdk/task/_cython/__init__.py +++ b/trpc_sdk/task/_cython/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Cython framing and queues of the worker/task IPC protocol.""" from ._task_frame import inner_decode_task_req # pyright: ignore[reportMissingModuleSource] diff --git a/trpc_sdk/task/_cython/_task_frame.pyi b/trpc_sdk/task/_cython/_task_frame.pyi index 2a52780..943c714 100644 --- a/trpc_sdk/task/_cython/_task_frame.pyi +++ b/trpc_sdk/task/_cython/_task_frame.pyi @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Type hints for the task IPC framing. One protocol lives here: a worker and its task child exchange a fixed 26-byte diff --git a/trpc_sdk/task/_cython/_task_queue.pyi b/trpc_sdk/task/_cython/_task_queue.pyi index 4ad1807..67daac4 100644 --- a/trpc_sdk/task/_cython/_task_queue.pyi +++ b/trpc_sdk/task/_cython/_task_queue.pyi @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Type hints for the request / response queues of a task process. These functions are only meaningful inside a task child: ``task_init``, diff --git a/trpc_sdk/task/_default_codec.py b/trpc_sdk/task/_default_codec.py index 98e4c13..b5ea913 100644 --- a/trpc_sdk/task/_default_codec.py +++ b/trpc_sdk/task/_default_codec.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Process-wide default task body codec. The framing between a worker and a task child is fixed, but the body is @@ -22,7 +21,6 @@ from trpc_sdk.abc import TaskCodec - DEFAULT_TASK_CODEC: Optional[TaskCodec] = None diff --git a/trpc_sdk/task/_task.py b/trpc_sdk/task/_task.py index 3926b58..22f8f8e 100644 --- a/trpc_sdk/task/_task.py +++ b/trpc_sdk/task/_task.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Business-facing entry point for sending a request to a task process. This wrapper resolves a task name to a connection; the encoding and the diff --git a/trpc_sdk/task/_types.py b/trpc_sdk/task/_types.py index 422be0c..4cf2c5b 100644 --- a/trpc_sdk/task/_types.py +++ b/trpc_sdk/task/_types.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Shared types and process-wide registries for the task feature. A task is a child process forked by the server before its event loop starts. diff --git a/trpc_sdk/task/_utils.py b/trpc_sdk/task/_utils.py index 237623c..2ab11a3 100644 --- a/trpc_sdk/task/_utils.py +++ b/trpc_sdk/task/_utils.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Worker-side helpers for talking to task child processes. The worker never runs a task handler inline: it encodes the request, writes @@ -18,6 +17,7 @@ from trpc_sdk.abc import TrpcContext from trpc_sdk.exceptions import TaskHandleError + from ._cython import inner_encode_task_req from ._types import TaskRegistry from ._types import TaskStatusCode diff --git a/trpc_sdk/telemetry/__init__.py b/trpc_sdk/telemetry/__init__.py index c95a057..22af7eb 100644 --- a/trpc_sdk/telemetry/__init__.py +++ b/trpc_sdk/telemetry/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Telemetry API for tRPC-Python.""" from ._metrics import set_default_metrics @@ -15,7 +14,7 @@ __all__ = [ "set_default_metrics", - "report_active", + "report_active", "report_passive", "report_attr", "report_custom", diff --git a/trpc_sdk/telemetry/_metrics.py b/trpc_sdk/telemetry/_metrics.py index 3468d78..7aecbdf 100644 --- a/trpc_sdk/telemetry/_metrics.py +++ b/trpc_sdk/telemetry/_metrics.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Telemetry metrics API for tRPC-Python.""" from __future__ import annotations diff --git a/trpc_sdk/transport/__init__.py b/trpc_sdk/transport/__init__.py index 33789a8..976e3d4 100644 --- a/trpc_sdk/transport/__init__.py +++ b/trpc_sdk/transport/__init__.py @@ -9,7 +9,7 @@ The **client half** turns an encoded request into a round trip over a pooled connection: :class:`ClientTransport` picks TCP or UDP from -:class:`RoundTripOptions`, and :class:`ClientConn` keeps the frame +:class:`RoundTripOptions`, and :class:`ClientStreamConn` keeps the frame queue for streaming calls. The **server half** never accepts connections itself. It tells @@ -31,9 +31,9 @@ and the plugin lookups, the TCP / UDP / stream round trips, the datagram endpoint helpers the UDP round trip uses, and the ``RoundTripOptions`` the client fills per call -- :mod:`~trpc_sdk.transport._pool` — client connection pools the TCP round - trip dials through; a tRPC-Python extension with no cross-language - counterpart, so it is scoped to the client transport half +- :mod:`~trpc_sdk.transport._client._pool` — client connection pools the + TCP round trip dials through; a tRPC-Python extension with no + cross-language counterpart, so it is scoped to the client transport half - :mod:`~trpc_sdk.transport._server` — the server half's listen transports: ``TrpcServerTransport`` (bind before fork, listen after it; its private acceptor picks ``create_server`` or a main-thread accept loop from the @@ -76,11 +76,6 @@ from ._constants import FRAME_HEAD_LEN from ._constants import INNER_MAGIC_VALUE from ._constants import RequestType -from ._pool import ConnAddress -from ._pool import ConnPoolOptions -from ._pool import ConnectionPoolManager -from ._pool import PooledConnection -from ._pool import get_pool_connection from ._scheduler import get_next_worker from ._scheduler import has_custom_scheduler from ._scheduler import register_dispatcher_worker_func @@ -91,7 +86,7 @@ from ._separate import SeparateRpczConnection from ._types import ClientConnectionInfo from ._types import SchedulerParams -from ._client import ClientConn +from ._client import ClientStreamConn from ._client import ClientTransport from ._client import PacketConnection from ._client import PacketReader @@ -101,6 +96,11 @@ from ._client import get_client_transport from ._client import get_default_client_transport from ._client import open_datagram_endpoint +from ._client._pool import ConnAddress +from ._client._pool import Connection +from ._client._pool import KeepLiveConnPoolManager +from ._client._pool import KeepLiveConnPoolOptions +from ._client._pool import get_pool_connection from ._server import ConnWriter from ._server import ConnectionCloseHandler from ._server import ConnectionIdleCleanHandler @@ -131,15 +131,15 @@ "ClientTransport", "get_client_transport", "get_default_client_transport", - "ClientConn", + "ClientStreamConn", "RequestType", "ClientTimeoutReason", "RoundTripOptions", # Client connection pool "ConnAddress", - "ConnPoolOptions", - "ConnectionPoolManager", - "PooledConnection", + "Connection", + "KeepLiveConnPoolManager", + "KeepLiveConnPoolOptions", "get_pool_connection", # Datagram endpoint helpers "open_datagram_endpoint", diff --git a/trpc_sdk/transport/_client/__init__.py b/trpc_sdk/transport/_client/__init__.py index 81e09ee..0359193 100644 --- a/trpc_sdk/transport/_client/__init__.py +++ b/trpc_sdk/transport/_client/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Client half of the transport package. Turns an encoded request into a round trip over a pooled connection. @@ -15,19 +14,19 @@ - :mod:`~trpc_sdk.transport._client._client_transport` — ``ClientTransport`` and the plugin lookups -- :mod:`~trpc_sdk.transport._client._client_transport_tcp`, - :mod:`~trpc_sdk.transport._client._client_transport_udp` — unary TCP / UDP +- :mod:`~trpc_sdk.transport._client._tcp_round_trip`, + :mod:`~trpc_sdk.transport._client._udp_round_trip` — unary TCP / UDP round trips -- :mod:`~trpc_sdk.transport._client._client_transport_stream` — - :class:`ClientConn`, the per-stream frame queue +- :mod:`~trpc_sdk.transport._client._client_stream_conn` — + :class:`ClientStreamConn`, the per-stream frame queue - :mod:`~trpc_sdk.transport._client._options` — :class:`RoundTripOptions` the client fills per call - :mod:`~trpc_sdk.transport._client._udp_connection` — datagram endpoint helpers used by the UDP round trip +- :mod:`~trpc_sdk.transport._client._pool` — the client connection pools + the TCP round trip dials through -Connection pools stay in the parent package -(:mod:`trpc_sdk.transport._pool`). Callers should import these -symbols from :mod:`trpc_sdk.transport`. +Callers should import these symbols from :mod:`trpc_sdk.transport`. """ from __future__ import annotations @@ -35,7 +34,7 @@ from ._client_transport import ClientTransport from ._client_transport import get_client_transport from ._client_transport import get_default_client_transport -from ._client_transport_stream import ClientConn +from ._client_stream_conn import ClientStreamConn from ._options import RoundTripOptions from ._udp_connection import PacketConnection from ._udp_connection import PacketReader @@ -44,7 +43,7 @@ from ._udp_connection import open_datagram_endpoint __all__ = [ - "ClientConn", + "ClientStreamConn", "ClientTransport", "RoundTripOptions", "get_client_transport", diff --git a/trpc_sdk/transport/_client/_client_transport_stream.py b/trpc_sdk/transport/_client/_client_stream_conn.py similarity index 78% rename from trpc_sdk/transport/_client/_client_transport_stream.py rename to trpc_sdk/transport/_client/_client_stream_conn.py index 2a97390..8263ffb 100644 --- a/trpc_sdk/transport/_client/_client_transport_stream.py +++ b/trpc_sdk/transport/_client/_client_stream_conn.py @@ -3,13 +3,12 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Pooled connection plus recv queue used by a client streaming call. -:class:`ClientConn` is what :class:`ClientTransport.start` stores under +:class:`ClientStreamConn` is what :class:`ClientTransport.start` stores under ``stream_id``. Later ``send`` / ``recv`` / ``close`` look it up. The -queue is filled either by a background :meth:`ClientConn.recv` loop or -by :meth:`ClientConn.push_data_to_recv_queue`. +queue is filled either by a background :meth:`ClientStreamConn.recv` loop or +by :meth:`ClientStreamConn.push_data_to_recv_queue`. """ from __future__ import annotations @@ -22,20 +21,21 @@ from trpc_sdk.exceptions import ClientTimeoutError from trpc_sdk.log import logger from trpc_sdk.utils import Queue -from .._pool import PooledConnection -from ._client_transport_tcp import get_remain_time + +from ._pool import Connection +from ._tcp_round_trip import get_remain_time from ._options import RoundTripOptions -class ClientConn: - """Client-side stream connection: pooled TCP plus a recv queue. +class ClientStreamConn: + """Client-side stream connection: connection plus a recv queue. Args: - conn: Pooled connection obtained by ``start``. + conn: Connection obtained by ``start``. options: Round-trip options, including the frame parser. """ - def __init__(self, conn: PooledConnection, options: RoundTripOptions): + def __init__(self, conn: Connection, options: RoundTripOptions): self._recv_queue = Queue() self._options = options self._conn = conn @@ -55,7 +55,7 @@ def push_data_to_recv_queue(self, data: Any): self._recv_queue.push(data) def close(self, force=False): - """Close the pooled connection. + """Close the connection. Args: force: Passed through to the pool conn. True drops it instead @@ -68,7 +68,7 @@ def close(self, force=False): async def recv_frame(self, ctx: TrpcContext): """Read one complete frame, bounded by ``ctx.deadline``. - On timeout or any other I/O error the pooled connection is + On timeout or any other I/O error the connection is force-closed and ``_conn`` is set to None so a later :meth:`close` does not touch it again. @@ -93,17 +93,13 @@ async def recv_frame(self, ctx: TrpcContext): self._conn.close(True) self._conn = None - raise ClientTimeoutError( - f"recv_frame deadline to {self._options.address}, {err} io error " - ) + raise ClientTimeoutError(f"recv_frame deadline to {self._options.address}, {err} io error ") except Exception as err: # pylint: disable=broad-except if self._conn: self._conn.close(True) self._conn = None - raise ClientInvokeError( - f"recv_frame failed {self._options.address}, error {err}" - ) + raise ClientInvokeError(f"recv_frame failed {self._options.address}, error {err}") return rsp @@ -112,7 +108,7 @@ async def recv(self): Runs until the remote side errors, a read fails, or :meth:`close` marks the connection closed. Any failure closes - the pooled connection (without force) and stops the loop; it + the connection (without force) and stops the loop; it does not raise to the caller. """ while not self._is_closed: @@ -133,7 +129,7 @@ async def recv(self): return def write(self, data: bytes): - """Write bytes on the pooled connection. + """Write bytes on the connection. Args: data: Encoded request (or stream frame) to send. diff --git a/trpc_sdk/transport/_client/_client_transport.py b/trpc_sdk/transport/_client/_client_transport.py index bb02ae0..9ecf856 100644 --- a/trpc_sdk/transport/_client/_client_transport.py +++ b/trpc_sdk/transport/_client/_client_transport.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Default client transport plugin. Importing this module registers :class:`ClientTransport` as @@ -14,13 +13,13 @@ Unary calls go through :meth:`ClientTransport.round_trip`, which picks TCP or UDP from :class:`RoundTripOptions`. Streaming calls never use ``round_trip``: :meth:`ClientTransport.start` -takes a pooled connection, stores a :class:`ClientConn` under the +takes a pooled connection, stores a :class:`ClientStreamConn` under the message ``stream_id``, and later :meth:`send` / :meth:`recv` / :meth:`close` look that conn up. -The TCP / UDP helpers live in ``_client_transport_tcp`` and -``_client_transport_udp``. :class:`ClientConn` lives in -``_client_transport_stream``. +The TCP / UDP helpers live in ``_tcp_round_trip`` and +``_udp_round_trip``. :class:`ClientStreamConn` lives in +``_client_stream_conn``. """ from __future__ import annotations @@ -34,11 +33,11 @@ from trpc_sdk.exceptions import ServerSystemError from trpc_sdk.plugin import get_plugin from trpc_sdk.plugin import register_plugin -from .._pool import get_pool_connection -from ._client_transport_stream import ClientConn as ClientStreamConn -from ._client_transport_tcp import get_remain_time -from ._client_transport_tcp import tcp_round_trip -from ._client_transport_udp import udp_round_trip +from ._pool import get_pool_connection +from ._client_stream_conn import ClientStreamConn +from ._tcp_round_trip import get_remain_time +from ._tcp_round_trip import tcp_round_trip +from ._udp_round_trip import udp_round_trip from ._options import RoundTripOptions @@ -48,7 +47,7 @@ class ClientTransport(BaseClientStreamTransport): Unary and stream paths share this class but not the same state. ``round_trip`` never reads :attr:`stream_id_to_conn`. The stream - methods only talk to the :class:`ClientConn` stored there. + methods only talk to the :class:`ClientStreamConn` stored there. Attributes: stream_id_to_conn: Live stream connections keyed by the tRPC @@ -69,7 +68,7 @@ async def round_trip(self, ctx: TrpcContext, req_data: bytes, options: RoundTrip Branch is ``options.network``: - - ``tcp``: :func:`tcp_round_trip` (pooled one-shot; + - ``tcp``: :func:`tcp_round_trip` (connection one-shot; ``close()`` in ``finally`` returns the conn to the pool) - ``udp``: :func:`udp_round_trip` @@ -94,7 +93,7 @@ async def round_trip(self, ctx: TrpcContext, req_data: bytes, options: RoundTrip raise ValueError(f"error network type {options.network}") def send(self, ctx: TrpcContext, req_data: bytes, _): - """Write one stream frame on the conn stored by :meth:`start`. + """Write one stream frame on the connection stored by :meth:`start`. Lookup is by ``ctx``'s client-message ``stream_id``, not by ``options``. The ABC still passes options; this method ignores diff --git a/trpc_sdk/transport/_client/_options.py b/trpc_sdk/transport/_client/_options.py index f485548..1ed4186 100644 --- a/trpc_sdk/transport/_client/_options.py +++ b/trpc_sdk/transport/_client/_options.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Per-call options the client transport reads on a round trip. :class:`RoundTripOptions` is the bag of knobs :class:`ClientTransport` @@ -23,9 +22,10 @@ from trpc_sdk.abc import BaseClientTransportOption from trpc_sdk.abc import BaseCodec from trpc_sdk.codec import TrpcClientParser + from .._constants import RequestType -from .._pool import ConnPoolOptions -from .._pool import ConnectionPoolManager +from ._pool import KeepLiveConnPoolOptions +from ._pool import KeepLiveConnPoolManager class RoundTripOptions(BaseClientTransportOption): @@ -52,7 +52,7 @@ class RoundTripOptions(BaseClientTransportOption): def __init__(self): super().__init__() self.parser = TrpcClientParser() - self.password = None + self.password: Optional[str] = None self.pool = None self.pool_opts = None @@ -86,16 +86,16 @@ def set_password(self, password: str): """ self.password = password - def set_pool(self, pool: ConnectionPoolManager): + def set_pool(self, pool: KeepLiveConnPoolManager): """Use a caller-supplied connection pool instead of the default. Args: - pool: Pool manager the TCP helper will ``get`` from. + pool: Connection pool manager the TCP helper will ``get`` from. """ self.pool = pool - def set_pool_options(self, pool_opts: ConnPoolOptions): - """Set options for the framework-built connection pool. + def set_pool_options(self, pool_opts: KeepLiveConnPoolOptions): + """Set options for the framework-built KeepLiveConnPool. Ignored when :meth:`set_pool` has already supplied a pool. diff --git a/trpc_sdk/transport/_client/_pool/__init__.py b/trpc_sdk/transport/_client/_pool/__init__.py new file mode 100644 index 0000000..6688f3a --- /dev/null +++ b/trpc_sdk/transport/_client/_pool/__init__.py @@ -0,0 +1,61 @@ +# Tencent is pleased to support the open source community by making tRPC-Python available. +# +# Copyright (C) 2026 Tencent. All rights reserved. +# +# tRPC-Python is licensed under Apache-2.0. +"""Client TCP / Unix connection pools used by the client transport half. + +Pooling is a tRPC-Python extension, not part of the cross-language tRPC +architecture, so it lives inside :mod:`trpc_sdk.transport._client` rather +than at the top level. Only the client round trips in +:mod:`trpc_sdk.transport._client` dial through it; the server half never +does. + +The package is split by responsibility: + +- :mod:`~trpc_sdk.transport._client._pool._base` -- the + ``BaseConnection`` / ``BaseConnectionPool`` contracts +- :mod:`~trpc_sdk.transport._client._pool._types` -- + :class:`KeepLiveConnPoolOptions` and address keys +- :mod:`~trpc_sdk.transport._client._pool._constants` -- default + stream-reader buffer limit +- :mod:`~trpc_sdk.transport._client._pool._dial` -- shared TCP/Unix + connect helper over the stdlib ``asyncio.open_connection`` +- :mod:`~trpc_sdk.transport._client._pool._connection` -- + :class:`Connection` +- :mod:`~trpc_sdk.transport._client._pool._short_conn_pool` -- one-shot + conn that is never queued idle +- :mod:`~trpc_sdk.transport._client._pool._keep_live_conn_pool` -- + idle-queue pool, manager, and per-loop manager cache +- :mod:`~trpc_sdk.transport._client._pool._pool_conn` -- + :func:`get_pool_connection` +""" + +from __future__ import annotations + +from asyncio import IncompleteReadError +from asyncio import LimitOverrunError + +from ._base import BaseConnectionPool +from ._connection import Connection +from ._keep_live_conn_pool import KeepLiveConnPool +from ._keep_live_conn_pool import KeepLiveConnPoolManager +from ._keep_live_conn_pool import KeepLiveConnPoolManagerCache +from ._pool_conn import get_pool_connection +from ._short_conn_pool import ShortConnPool +from ._types import ConnAddress +from ._types import KeepLiveConnPoolOptions + +__all__ = [ + "BaseConnectionPool", + "KeepLiveConnPool", + "KeepLiveConnPoolManager", + "KeepLiveConnPoolManagerCache", + "Connection", + "ConnAddress", + "KeepLiveConnPoolOptions", + "ShortConnPool", + "IncompleteReadError", + "LimitOverrunError", + "get_pool_connection", +] diff --git a/trpc_sdk/transport/_pool/_base.py b/trpc_sdk/transport/_client/_pool/_base.py similarity index 62% rename from trpc_sdk/transport/_pool/_base.py rename to trpc_sdk/transport/_client/_pool/_base.py index 9504333..e3b9ac8 100644 --- a/trpc_sdk/transport/_pool/_base.py +++ b/trpc_sdk/transport/_client/_pool/_base.py @@ -3,14 +3,14 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Abstract contract for a client connection pool. -:class:`BasePool` is the get/put surface that -:class:`~trpc_sdk.transport._pool.PooledConnection` talks to when it is -returned. :class:`~trpc_sdk.transport._pool.ConnectionPool` is the +:class:`BaseConnection` is the read/write/close surface every pooled +connection exposes. :class:`BaseConnectionPool` is the get/put surface that +:class:`~trpc_sdk.transport._client._pool.Connection` talks to when it is +returned. :class:`~trpc_sdk.transport._client._pool.KeepLiveConnPool` is the idle-queue implementation; -:class:`~trpc_sdk.transport._pool.ShortConnFactory` duck-types the same +:class:`~trpc_sdk.transport._client._pool.ShortConnPool` implements the same ``put`` so a short-lived conn can still call ``close``. """ @@ -19,17 +19,35 @@ from abc import ABC from abc import abstractmethod from asyncio import BaseEventLoop -from typing import TYPE_CHECKING from typing import Optional from trpc_sdk.abc import AddrType from trpc_sdk.common import get_or_create_event_loop -if TYPE_CHECKING: - from ._pooled_connection import PooledConnection + +class BaseConnection(ABC): + """Client connection that issues and takes back pooled connections. + + """ + + @abstractmethod + async def read(self, num: int) -> bytes: + """Read exactly ``num`` bytes from the underlying stream""" + + @abstractmethod + def write(self, data: bytes) -> int: + """Write data to the underlying stream""" + + @abstractmethod + def close(self, force: bool = False) -> None: + """Close the underlying stream""" + + @abstractmethod + def force_close(self) -> None: + """Force-close the underlying stream""" -class BasePool(ABC): +class BaseConnectionPool(ABC): """Client pool that issues and takes back pooled connections. ``address`` is the remote the pool dials. ``loop`` is the event @@ -48,16 +66,16 @@ def __init__(self, address: AddrType, loop: Optional[BaseEventLoop]): @property def address(self) -> AddrType: - """Remote address this pool dials.""" + """Remote address this connection pool dials.""" return self._address @property def loop(self) -> BaseEventLoop: - """Event loop the pool's idle queue and dials run on.""" + """Event loop the connection pool's idle queue and dials run on.""" return self._loop @abstractmethod - async def get(self, timeout: float) -> "PooledConnection": + async def get(self, timeout: float) -> BaseConnection: """Take one connection out of the pool, dialing if needed. Args: @@ -70,7 +88,7 @@ async def get(self, timeout: float) -> "PooledConnection": """ @abstractmethod - def put(self, pool_conn: "PooledConnection", force_close: bool = False) -> None: + def put(self, pool_conn: BaseConnection, force_close: bool = False) -> None: """Return a connection to the pool, or drop it. This is a return, not a socket close. ``force_close=True`` diff --git a/trpc_sdk/transport/_pool/_pooled_connection.py b/trpc_sdk/transport/_client/_pool/_connection.py similarity index 93% rename from trpc_sdk/transport/_pool/_pooled_connection.py rename to trpc_sdk/transport/_client/_pool/_connection.py index 1e412d5..619ba28 100644 --- a/trpc_sdk/transport/_pool/_pooled_connection.py +++ b/trpc_sdk/transport/_client/_pool/_connection.py @@ -3,11 +3,10 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Pooled wrapper around a dialed asyncio stream. -Callers receive a :class:`PooledConnection` from -:func:`~trpc_sdk.transport._pool.get_pool_connection`. ``close()`` +Callers receive a :class:`Connection` from +:func:`~trpc_sdk.transport._client._pool.get_pool_connection`. ``close()`` returns it to the pool; ``force_close()`` tears down the socket. ``read`` / ``write`` failures call ``pool.put(self, True)`` before re-raising so a broken conn is not reused. @@ -29,10 +28,11 @@ from trpc_sdk.utils import is_close_wait from trpc_sdk.utils import is_valid_socket -from ._base import BasePool +from ._base import BaseConnection +from ._base import BaseConnectionPool -class PooledConnection: +class Connection(BaseConnection): """One TCP (or Unix) connection borrowed from a client pool. ``begin_time`` is stamped when the conn is put back idle; the pool @@ -41,7 +41,7 @@ class PooledConnection: Args: reader: Reader half from - :func:`~trpc_sdk.transport._pool._dial.dial_connection`. + :func:`~trpc_sdk.transport._client._pool._dial.dial_connection`. writer: Writer half of the same stream. loop: Event loop the stream was dialed on. pool: Pool (or short-conn factory) that will take this conn @@ -51,14 +51,8 @@ class PooledConnection: force-closed on return. """ - def __init__( - self, - reader: StreamReader, - writer: StreamWriter, - loop: BaseEventLoop, - pool: BasePool, - address: AddrType, - is_short: bool): + def __init__(self, reader: StreamReader, writer: StreamWriter, loop: BaseEventLoop, pool: BaseConnectionPool, + address: AddrType, is_short: bool): self._reader = reader self._writer = writer self._created_time = time.time() diff --git a/trpc_sdk/transport/_pool/_constants.py b/trpc_sdk/transport/_client/_pool/_constants.py similarity index 88% rename from trpc_sdk/transport/_pool/_constants.py rename to trpc_sdk/transport/_client/_pool/_constants.py index 7792d71..0306718 100644 --- a/trpc_sdk/transport/_pool/_constants.py +++ b/trpc_sdk/transport/_client/_pool/_constants.py @@ -3,11 +3,10 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Constants used by the connection-pool package. :data:`DEFAULT_STREAM_LIMIT` is the read buffer half-limit -:func:`~trpc_sdk.transport._pool._dial.dial_connection` passes to +:func:`~trpc_sdk.transport._client._pool._dial.dial_connection` passes to ``asyncio.open_connection`` / ``asyncio.open_unix_connection``. """ diff --git a/trpc_sdk/transport/_pool/_dial.py b/trpc_sdk/transport/_client/_pool/_dial.py similarity index 85% rename from trpc_sdk/transport/_pool/_dial.py rename to trpc_sdk/transport/_client/_pool/_dial.py index 820865f..631a241 100644 --- a/trpc_sdk/transport/_pool/_dial.py +++ b/trpc_sdk/transport/_client/_pool/_dial.py @@ -3,13 +3,12 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Dial a TCP or Unix stream for the client connection pools. :func:`dial_connection` is the shared connect path used by -:class:`~trpc_sdk.transport._pool.ConnectionPoolManager` (as -``ConnectionPoolManager.dial``) and by -:class:`~trpc_sdk.transport._pool.ShortConnFactory`. Keeping it +:class:`~trpc_sdk.transport._client._pool.KeepLiveConnPoolManager` (as +``KeepLiveConnPoolManager.dial``) and by +:class:`~trpc_sdk.transport._client._pool.ShortConnPool`. Keeping it in this module avoids a cycle between those two files. The stdlib ``asyncio.open_connection`` / ``open_unix_connection`` do the @@ -38,10 +37,8 @@ from ._constants import DEFAULT_STREAM_LIMIT -async def dial_connection( - options: BaseClientTransportOption, - timeout: float, - loop: BaseEventLoop) -> Tuple[StreamReader, StreamWriter]: +async def dial_connection(options: BaseClientTransportOption, timeout: float, + loop: BaseEventLoop) -> Tuple[StreamReader, StreamWriter]: """Open a TCP or Unix stream. A connected ``socket.socket`` is adopted. A ``(host, port)`` @@ -80,10 +77,7 @@ async def dial_connection( family=socket.AF_INET6, local_addr=options.local_addr) else: - co_open = asyncio.open_connection(host, - port, - limit=DEFAULT_STREAM_LIMIT, - local_addr=options.local_addr) + co_open = asyncio.open_connection(host, port, limit=DEFAULT_STREAM_LIMIT, local_addr=options.local_addr) return await wait_for_by_loop(_open(co_open), timeout, loop=loop) assert False, f"address is error type {options.address}" diff --git a/trpc_sdk/transport/_pool/_connection_pool.py b/trpc_sdk/transport/_client/_pool/_keep_live_conn_pool.py similarity index 66% rename from trpc_sdk/transport/_pool/_connection_pool.py rename to trpc_sdk/transport/_client/_pool/_keep_live_conn_pool.py index 73b537a..9a3d648 100644 --- a/trpc_sdk/transport/_pool/_connection_pool.py +++ b/trpc_sdk/transport/_client/_pool/_keep_live_conn_pool.py @@ -3,27 +3,20 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - -"""Address-scoped TCP/Unix client connection pools. - -:class:`ConnectionPool` holds idle conns for one remote. -:class:`ConnectionPoolManager` maps a local+peer key onto those pools -and runs a periodic idle sweep. -:class:`~trpc_sdk.transport._pool.ShortConnFactory` dials a -one-shot conn that is force-closed on return and never queued; it lives -in :mod:`trpc_sdk.transport._pool._short_conn_factory` and is -re-exported here. -:func:`get_pool_connection` is the entry used by client transport: -short-conn options skip the manager; otherwise a per-loop manager is -cached in :class:`PoolCache`. - -:class:`Pool` is a historical alias of :class:`ConnectionPoolManager`. -Types and the pooled wrapper live in -:mod:`trpc_sdk.transport._pool._types` and -:mod:`trpc_sdk.transport._pool._pooled_connection`; the -:class:`BasePool` contract lives in -:mod:`trpc_sdk.transport._pool._base`. Dialing lives in -:mod:`trpc_sdk.transport._pool._dial`. +"""Address-scoped TCP/Unix keep-alive client connection pools. + +:class:`KeepLiveConnPool` holds idle conns for one remote. +:class:`KeepLiveConnPoolManager` maps a local+peer key onto those pools +and runs a periodic idle sweep. :class:`KeepLiveConnPoolManagerCache` +keeps one manager per event loop for +:func:`~trpc_sdk.transport._client._pool.get_pool_connection`. + +Types and the connection wrapper live in +:mod:`trpc_sdk.transport._client._pool._types` and +:mod:`trpc_sdk.transport._client._pool._connection`; the +:class:`BaseConnectionPool` contract lives in +:mod:`trpc_sdk.transport._client._pool._base`. Dialing lives in +:mod:`trpc_sdk.transport._client._pool._dial`. """ from __future__ import annotations @@ -44,15 +37,14 @@ from trpc_sdk.exceptions import ClientPoolLimitError from trpc_sdk.log import logger -from ._base import BasePool +from ._base import BaseConnectionPool from ._dial import dial_connection -from ._pooled_connection import PooledConnection -from ._short_conn_factory import ShortConnFactory +from ._connection import Connection from ._types import ConnAddress -from ._types import ConnPoolOptions +from ._types import KeepLiveConnPoolOptions -class ConnectionPool(BasePool): +class KeepLiveConnPool(BaseConnectionPool): """Idle-queue pool for one transport address. ``max_idle`` sizes the idle :class:`asyncio.Queue`. ``max_active`` @@ -65,17 +57,16 @@ class ConnectionPool(BasePool): trans_opt: Client transport options, including the remote address. options: Idle / active / lifetime tunables. Must not be - ``None`` at runtime; callers pass a :class:`ConnPoolOptions`. + ``None`` at runtime; callers pass a :class:`KeepLiveConnPoolOptions`. loop: Event loop bound to the idle queue, or ``None`` to pick the current one. """ - def __init__( - self, - dial: Callable, - trans_opt: BaseClientTransportOption, - options: Optional[ConnPoolOptions] = None, - loop: Optional[BaseEventLoop] = None): + def __init__(self, + dial: Callable, + trans_opt: BaseClientTransportOption, + options: Optional[KeepLiveConnPoolOptions] = None, + loop: Optional[BaseEventLoop] = None): super().__init__(address=trans_opt.address, loop=loop) self._dial = dial self._trans_opt = trans_opt @@ -95,7 +86,7 @@ def idle_conns_num(self) -> int: """How many conns currently sit in the idle queue.""" return self._idle_conns.qsize() - async def get(self, timeout: float) -> PooledConnection: + async def get(self, timeout: float) -> Connection: """Take a healthy idle conn, or dial a new one. Idle entries that fail :meth:`_checker` are force-closed and @@ -106,7 +97,7 @@ async def get(self, timeout: float) -> PooledConnection: timeout: Dial timeout in seconds for a new connection. Returns: - A :class:`PooledConnection` the caller must ``close``. + A :class:`Connection` the caller must ``close``. Raises: ClientPoolClosedError: :meth:`close` has already run. @@ -116,7 +107,7 @@ async def get(self, timeout: float) -> PooledConnection: raise ClientPoolClosedError("ErrPoolClosed") for _ in range(self._idle_conns.qsize()): - pool_conn: PooledConnection = self._idle_conns.get_nowait() + pool_conn: Connection = self._idle_conns.get_nowait() if self._checker(pool_conn): pool_conn.close(True) else: @@ -128,12 +119,12 @@ async def get(self, timeout: float) -> PooledConnection: return await self._idle_conns.get() reader, writer = await self._dial(options=self._trans_opt, timeout=timeout, loop=self.loop) - pool_conn = PooledConnection(reader=reader, - writer=writer, - loop=self.loop, - pool=self, - address=self.address, - is_short=False) + pool_conn = Connection(reader=reader, + writer=writer, + loop=self.loop, + pool=self, + address=self.address, + is_short=False) self._active_conn_num += 1 self._active_conns.add(pool_conn) return pool_conn @@ -141,7 +132,7 @@ async def get(self, timeout: float) -> PooledConnection: def _clear_all_conn(self) -> None: """Force-close every idle and in-use conn, then empty the active set.""" for _ in range(self._idle_conns.qsize()): - pool_conn: PooledConnection = self._idle_conns.get_nowait() + pool_conn: Connection = self._idle_conns.get_nowait() pool_conn.force_close() for pool_conn in self._active_conns: pool_conn.force_close() @@ -170,7 +161,7 @@ def __del__(self): logger.error(f"address: {self.address}, total: {self._active_conn_num}, \ qsize: {self._idle_conns.qsize()} err: {err}") - def put(self, pool_conn: PooledConnection, force_close: bool = False) -> None: + def put(self, pool_conn: Connection, force_close: bool = False) -> None: """Return ``pool_conn`` to the idle queue, or close it. When the idle queue is already at ``max_idle``, the returning @@ -202,7 +193,7 @@ def _over_limit(self) -> bool: """Return True when ``max_active`` is set and already reached.""" return self._pool_options.max_active > 0 and self._active_conn_num >= self._pool_options.max_active - def _checker(self, pool_conn: PooledConnection) -> bool: + def _checker(self, pool_conn: Connection) -> bool: """Return True if ``pool_conn`` must not be handed out again. Remote errors always fail. Otherwise idle_timeout is measured @@ -231,7 +222,7 @@ def _checker(self, pool_conn: PooledConnection) -> bool: def clean_idle_conn(self) -> None: """Drop idle conns that fail :meth:`_checker`, keep the rest. - Called periodically by :class:`ConnectionPoolManager`. If the + Called periodically by :class:`KeepLiveConnPoolManager`. If the pool is already closed or its loop is not running, every conn is force-closed instead. @@ -240,7 +231,7 @@ def clean_idle_conn(self) -> None: """ if self._closed is False and self.loop.is_running(): for _ in range(self._idle_conns.qsize()): - pool_conn: PooledConnection = self._idle_conns.get_nowait() + pool_conn: Connection = self._idle_conns.get_nowait() if self._checker(pool_conn): logger.debug("pool conn remote error") pool_conn.close(True) @@ -250,8 +241,8 @@ def clean_idle_conn(self) -> None: self._clear_all_conn() -class ConnectionPoolManager: - """Create and look up one :class:`ConnectionPool` per address key. +class KeepLiveConnPoolManager: + """Create and look up one :class:`KeepLiveConnPool` per address key. The key is ``local_addr + peer`` plus a ``_sock`` / ``_addr`` suffix, so the same remote with a different local bind does not @@ -259,25 +250,25 @@ class ConnectionPoolManager: ``loop``, which sleeps 1000s between sweeps. Args: - options: Shared :class:`ConnPoolOptions` for every pool this + options: Shared :class:`KeepLiveConnPoolOptions` for every pool this manager creates. ``None`` uses defaults. loop: Event loop for new pools and the idle-clean task. """ - def __init__(self, options: Optional[ConnPoolOptions] = None, loop: Optional[BaseEventLoop] = None): - self._options = options or ConnPoolOptions() - self._conn_pools: Dict[ConnAddress, ConnectionPool] = {} + def __init__(self, options: Optional[KeepLiveConnPoolOptions] = None, loop: Optional[BaseEventLoop] = None): + self._options = options or KeepLiveConnPoolOptions() + self._conn_pools: Dict[ConnAddress, KeepLiveConnPool] = {} self._loop = loop or get_or_create_event_loop() self._loop.create_task(self.__clean_idle_conn()) self._lock = asyncio.Lock() self._is_closed = False - # Kept as a staticmethod so ``ConnectionPoolManager.dial`` and - # ``ConnectionPool(dial=self.dial)`` keep working after the dial - # logic moved to :mod:`trpc_sdk.transport._pool._dial`. + # Kept as a staticmethod so ``KeepLiveConnPoolManager.dial`` and + # ``KeepLiveConnPool(dial=self.dial)`` keep working after the dial + # logic moved to :mod:`trpc_sdk.transport._client._pool._dial`. dial = staticmethod(dial_connection) - async def get(self, trans_opt: BaseClientTransportOption, timeout: float) -> PooledConnection: + async def get(self, trans_opt: BaseClientTransportOption, timeout: float) -> Connection: """Return a pooled conn for ``trans_opt``'s remote. ``timeout <= 0`` falls back to ``dial_timeout`` milliseconds @@ -291,7 +282,7 @@ async def get(self, trans_opt: BaseClientTransportOption, timeout: float) -> Poo timeout: Dial timeout in seconds, or ``0`` to use options. Returns: - A :class:`PooledConnection` from that address's pool. + A :class:`Connection` from that address's pool. """ timeout = timeout if timeout and timeout > 0 else self._options.dial_timeout / 1000 addr = trans_opt.sock or trans_opt.address @@ -306,12 +297,12 @@ async def get(self, trans_opt: BaseClientTransportOption, timeout: float) -> Poo if trans_opt.local_addr: index = f"{trans_opt.local_addr}" index = f"{index}_{addr}_addr" - conn_pool: ConnectionPool = self._conn_pools.get(index, None) + conn_pool: KeepLiveConnPool = self._conn_pools.get(index, None) if conn_pool: return await conn_pool.get(timeout) async with self._lock: - new_pool = ConnectionPool(dial=self.dial, trans_opt=trans_opt, options=self._options, loop=self._loop) + new_pool = KeepLiveConnPool(dial=self.dial, trans_opt=trans_opt, options=self._options, loop=self._loop) self._conn_pools[index] = new_pool return await new_pool.get(timeout) @@ -330,10 +321,7 @@ def __del__(self): self._conn_pools.clear() -Pool = ConnectionPoolManager - - -class PoolCache(threading.local): +class KeepLiveConnPoolManagerCache(threading.local): """Per-thread map from event loop (or address) to a pool manager. :func:`get_pool_connection` stores the manager under the loop id @@ -361,51 +349,3 @@ def __getitem__(self, key): def __setitem__(self, key, value): self.__dict__[key] = value - - -_short_conn_factory = ShortConnFactory() - -_default_connection_pools = PoolCache() - - -async def get_pool_connection(options: BaseClientTransportOption, - timeout: float, - loop: Optional[BaseEventLoop] = None) -> PooledConnection: - """Return a pooled (or short) connection for ``options``. - - ``options.short_conn`` uses :class:`ShortConnFactory` and never - touches the manager cache. Otherwise a :class:`ConnectionPoolManager` - is created once per event loop and reused. If the same address was - previously bound to a different loop, that stale loop entry is - deleted after a warning. - - Args: - options: Client transport options, including ``pool_opts`` when - a new manager must be built. - timeout: Dial timeout in seconds; ``<= 0`` uses pool options. - loop: Event loop that owns the manager; ``None`` picks current. - - Returns: - A :class:`PooledConnection` ready for ``read`` / ``write``. - """ - loop = loop or get_or_create_event_loop() - - if options.short_conn: - return await _short_conn_factory.get(options=options, timeout=timeout, loop=loop) - - conn_pool_mgr = _default_connection_pools.get(loop, None) - if not conn_pool_mgr: - old_loop: BaseEventLoop = _default_connection_pools.get(options.address, None) - if old_loop: - if id(old_loop) != id(loop): - logger.warning(f"address: {options.address} exist different loop, \ - old {id(old_loop)} != current loop: {loop}") - if old_loop in _default_connection_pools.__dict__: - del _default_connection_pools.__dict__[old_loop] - _default_connection_pools[options.address] = loop - - pool_opts = getattr(options, "pool_opts", None) - conn_pool_mgr = ConnectionPoolManager(options=pool_opts, loop=loop) - _default_connection_pools[loop] = conn_pool_mgr - - return await conn_pool_mgr.get(options, timeout) diff --git a/trpc_sdk/transport/_client/_pool/_pool_conn.py b/trpc_sdk/transport/_client/_pool/_pool_conn.py new file mode 100644 index 0000000..75954ba --- /dev/null +++ b/trpc_sdk/transport/_client/_pool/_pool_conn.py @@ -0,0 +1,76 @@ +# Tencent is pleased to support the open source community by making tRPC-Python available. +# +# Copyright (C) 2026 Tencent. All rights reserved. +# +# tRPC-Python is licensed under Apache-2.0. +"""Entry point the client round trips use to borrow a connection. + +:class:`~trpc_sdk.transport._client._pool.ShortConnPool` dials a +one-shot connection that is force-closed on return and never queued. +:class:`~trpc_sdk.transport._client._pool.KeepLiveConnPoolManager` maps a +local+peer key onto keep-alive connection pools. +:func:`get_pool_connection` is the entry used by client transport: +short-conn options skip the manager; otherwise a per-loop manager is +cached in :class:`KeepLiveConnPoolManagerCache`. +""" + +from __future__ import annotations + +from asyncio import BaseEventLoop +from typing import Optional + +from trpc_sdk.abc import BaseClientTransportOption +from trpc_sdk.common import get_or_create_event_loop +from trpc_sdk.log import logger + +from ._connection import Connection +from ._short_conn_pool import ShortConnPool +from ._keep_live_conn_pool import KeepLiveConnPoolManagerCache +from ._keep_live_conn_pool import KeepLiveConnPoolManager + +_short_conn_pool = ShortConnPool() + +_keep_live_conn_pool_manager_cache = KeepLiveConnPoolManagerCache() + + +async def get_pool_connection(options: BaseClientTransportOption, + timeout: float, + loop: Optional[BaseEventLoop] = None) -> Connection: + """Return a pooled (or short) connection for ``options``. + + ``options.short_conn`` uses :class:`ShortConnPool` and never + touches the manager cache. Otherwise a :class:`KeepLiveConnPoolManager` + is created once per event loop and reused. If the same address was + previously bound to a different loop, that stale loop entry is + deleted after a warning. + + Args: + options: Client transport options, including ``pool_opts`` when + a new manager must be built. + timeout: Dial timeout in seconds; ``<= 0`` uses pool options. + loop: Event loop that owns the manager; ``None`` picks current. + + Returns: + A :class:`Connection` ready for ``read`` / ``write``. + """ + loop = loop or get_or_create_event_loop() + + if options.short_conn: + return await _short_conn_pool.get(options=options, timeout=timeout, loop=loop) + + conn_pool_mgr = _keep_live_conn_pool_manager_cache.get(loop, None) + if not conn_pool_mgr: + old_loop: BaseEventLoop = _keep_live_conn_pool_manager_cache.get(options.address, None) + if old_loop: + if id(old_loop) != id(loop): + logger.warning(f"address: {options.address} exist different loop, \ + old {id(old_loop)} != current loop: {loop}") + if old_loop in _keep_live_conn_pool_manager_cache.__dict__: + del _keep_live_conn_pool_manager_cache.__dict__[old_loop] + _keep_live_conn_pool_manager_cache[options.address] = loop + + pool_opts = getattr(options, "pool_opts", None) + conn_pool_mgr = KeepLiveConnPoolManager(options=pool_opts, loop=loop) + _keep_live_conn_pool_manager_cache[loop] = conn_pool_mgr + + return await conn_pool_mgr.get(options, timeout) diff --git a/trpc_sdk/transport/_pool/_short_conn_factory.py b/trpc_sdk/transport/_client/_pool/_short_conn_pool.py similarity index 56% rename from trpc_sdk/transport/_pool/_short_conn_factory.py rename to trpc_sdk/transport/_client/_pool/_short_conn_pool.py index 83a678f..f91d054 100644 --- a/trpc_sdk/transport/_pool/_short_conn_factory.py +++ b/trpc_sdk/transport/_client/_pool/_short_conn_pool.py @@ -3,12 +3,11 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """One-shot TCP/Unix connections that are never returned to an idle queue. -:class:`ShortConnFactory` duck-types the ``get`` / ``put`` surface of -:class:`~trpc_sdk.transport._pool.BasePool` so a -:class:`~trpc_sdk.transport._pool.PooledConnection` can still +:class:`ShortConnPool` implements the ``get`` / ``put`` surface of +:class:`~trpc_sdk.transport._client._pool.BaseConnectionPool` so a +:class:`~trpc_sdk.transport._client._pool.Connection` can still ``close`` through ``pool.put``. ``put`` always force-closes. """ @@ -18,14 +17,15 @@ from trpc_sdk.abc import BaseClientTransportOption +from ._base import BaseConnectionPool from ._dial import dial_connection -from ._pooled_connection import PooledConnection +from ._connection import Connection -class ShortConnFactory: +class ShortConnPool(BaseConnectionPool): """Dial a one-shot conn that is never returned to an idle queue. - ``put`` always :meth:`~PooledConnection.force_close` so callers can + ``put`` always :meth:`~Connection.force_close` so callers can still use the pooled ``close`` path. ``is_short`` is True on the wrapper so logs can tell these apart from pooled conns. @@ -33,12 +33,12 @@ class ShortConnFactory: None. """ - async def get( - self, - options: BaseClientTransportOption, - timeout: float, - loop: BaseEventLoop) -> PooledConnection: - """Dial through :func:`~trpc_sdk.transport._pool._dial.dial_connection`. + def __init__(self): # pylint: disable=super-init-not-called + self._address = None + self._loop = None + + async def get(self, options: BaseClientTransportOption, timeout: float, loop: BaseEventLoop) -> Connection: + """Dial through :func:`~trpc_sdk.transport._client._pool._dial.dial_connection`. Args: options: Transport options with the remote address / sock. @@ -46,18 +46,12 @@ async def get( loop: Event loop the dial runs on. Returns: - A short-lived :class:`PooledConnection`. + A short-lived :class:`Connection`. """ reader, writer = await dial_connection(options=options, timeout=timeout, loop=loop) - return PooledConnection(reader=reader, - writer=writer, - loop=loop, - pool=self, - address=options.address, - is_short=True) + return Connection(reader=reader, writer=writer, loop=loop, pool=self, address=options.address, is_short=True) - @staticmethod - def put(pool_conn: PooledConnection, _: bool = True) -> None: + def put(self, pool_conn: Connection, _: bool = True) -> None: """Force-close ``pool_conn``; short conns are never cached. Args: diff --git a/trpc_sdk/transport/_pool/_types.py b/trpc_sdk/transport/_client/_pool/_types.py similarity index 64% rename from trpc_sdk/transport/_pool/_types.py rename to trpc_sdk/transport/_client/_pool/_types.py index 61c5b3a..b46b935 100644 --- a/trpc_sdk/transport/_pool/_types.py +++ b/trpc_sdk/transport/_client/_pool/_types.py @@ -3,12 +3,11 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Shared type definitions for the client connection pool. -:class:`ConnPoolOptions` is stamped onto client transport options and -read by :class:`~trpc_sdk.transport._pool.ConnectionPool` / -:class:`~trpc_sdk.transport._pool.ConnectionPoolManager`. +:class:`KeepLiveConnPoolOptions` is stamped onto client transport options and +read by :class:`~trpc_sdk.transport._client._pool.KeepLiveConnPool` / +:class:`~trpc_sdk.transport._client._pool.KeepLiveConnPoolManager`. :data:`ConnAddress` is the key type used when a manager indexes a pool by socket or ``(host, port)``. """ @@ -25,19 +24,19 @@ @dataclass -class ConnPoolOptions: - """Tunables for one address-scoped connection pool. +class KeepLiveConnPoolOptions: + """Tunables for one address-scoped KeepLiveConnPool. Attributes: dial_timeout: Connect timeout in milliseconds; divided by 1000 before use in - :meth:`trpc_sdk.transport._pool.ConnectionPoolManager.get`. - idle_timeout: Seconds an idle conn may sit in the queue. ``0`` + :meth:`trpc_sdk.transport._client._pool.KeepLiveConnPoolManager.get`. + idle_timeout: Seconds an idle connection may sit in the queue. ``0`` disables the idle check. - max_conn_lifetime: Hard lifetime in seconds from create time; + max_connection_lifetime: Hard lifetime in seconds from create time; ``0`` disables it. max_idle: Idle queue capacity; ``0`` means no idle caching. - max_active: Active conn cap; ``0`` means unlimited. + max_active: Active connection cap; ``0`` means unlimited. wait: When the active cap is hit, block on the idle queue instead of raising ``ClientPoolLimitError``. """ diff --git a/trpc_sdk/transport/_client/_client_transport_tcp.py b/trpc_sdk/transport/_client/_tcp_round_trip.py similarity index 98% rename from trpc_sdk/transport/_client/_client_transport_tcp.py rename to trpc_sdk/transport/_client/_tcp_round_trip.py index 79fa1cf..2bd1b0d 100644 --- a/trpc_sdk/transport/_client/_client_transport_tcp.py +++ b/trpc_sdk/transport/_client/_tcp_round_trip.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """TCP round-trip helper used by :class:`ClientTransport`. :func:`tcp_round_trip` takes a pooled connection, writes, optionally @@ -27,7 +26,7 @@ from trpc_sdk.utils import now_us from trpc_sdk.utils import set_addr_to_ctx_from_transport from .._constants import RequestType -from .._pool import get_pool_connection +from ._pool import get_pool_connection from ._options import RoundTripOptions @@ -104,4 +103,3 @@ async def tcp_round_trip(ctx: TrpcContext, req_data: bytes, options: RoundTripOp conn.close() return rsp - diff --git a/trpc_sdk/transport/_client/_udp_connection.py b/trpc_sdk/transport/_client/_udp_connection.py index 2d17680..e7e0401 100644 --- a/trpc_sdk/transport/_client/_udp_connection.py +++ b/trpc_sdk/transport/_client/_udp_connection.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Connected UDP endpoint used by the client UDP round trip. :func:`open_datagram_endpoint` builds a remote-addr-connected datagram diff --git a/trpc_sdk/transport/_client/_client_transport_udp.py b/trpc_sdk/transport/_client/_udp_round_trip.py similarity index 100% rename from trpc_sdk/transport/_client/_client_transport_udp.py rename to trpc_sdk/transport/_client/_udp_round_trip.py index c77bacb..4dc8867 100644 --- a/trpc_sdk/transport/_client/_client_transport_udp.py +++ b/trpc_sdk/transport/_client/_udp_round_trip.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """UDP round-trip helper used by :class:`ClientTransport`. Opens a connected datagram endpoint via @@ -24,6 +23,7 @@ from trpc_sdk.utils import now_ms from trpc_sdk.utils import now_us from trpc_sdk.utils import set_addr_to_ctx_from_transport + from .._constants import RequestType from ._udp_connection import open_datagram_endpoint from ._options import RoundTripOptions diff --git a/trpc_sdk/transport/_constants.py b/trpc_sdk/transport/_constants.py index dfd2792..8ebc357 100644 --- a/trpc_sdk/transport/_constants.py +++ b/trpc_sdk/transport/_constants.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Constants used by both halves of the transport package. The listen backlog lives in :data:`trpc_sdk.utils.DEFAULT_BACKLOG` next to @@ -25,7 +24,7 @@ from enum import IntEnum from enum import unique -# Inner IPC frame: big-endian ushort magic + uint32 total length. +# Inner IPC frame: big-endian uint16_t magic + uint32_t total length. INNER_MAGIC_VALUE = 1314 FRAME_HEAD_LEN = struct.calcsize("!HI") diff --git a/trpc_sdk/transport/_cython/__init__.py b/trpc_sdk/transport/_cython/__init__.py index d1cd352..044c2da 100644 --- a/trpc_sdk/transport/_cython/__init__.py +++ b/trpc_sdk/transport/_cython/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Cython inner-IPC framing used across dispatcher / worker / task pipes.""" from ._ipc_codec import InnerDatagramParser # pyright: ignore[reportMissingModuleSource] diff --git a/trpc_sdk/transport/_cython/_ipc_codec.pxd b/trpc_sdk/transport/_cython/_ipc_codec.pxd index 6fafbe9..c3a83bf 100644 --- a/trpc_sdk/transport/_cython/_ipc_codec.pxd +++ b/trpc_sdk/transport/_cython/_ipc_codec.pxd @@ -15,6 +15,7 @@ from libc.stdint cimport uint8_t from libc.stdint cimport uint16_t from libc.stdint cimport uint32_t +from libc.stdint cimport uint64_t # Datagram-IPC header used on the C dispatcher pipe. Not the stream @@ -42,10 +43,6 @@ cdef struct DataHeader: cdef enum: GLOBAL_MAX_IPC_SIZE = 8 * 1024 -ctypedef unsigned short ushort -ctypedef unsigned int uint -ctypedef unsigned long ulong - cdef class InnerStreamParser: cdef: diff --git a/trpc_sdk/transport/_cython/_ipc_codec.pyi b/trpc_sdk/transport/_cython/_ipc_codec.pyi index fcd6ef8..507ac05 100644 --- a/trpc_sdk/transport/_cython/_ipc_codec.pyi +++ b/trpc_sdk/transport/_cython/_ipc_codec.pyi @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Type hints for the Cython inner-IPC codec. Production dispatcher / worker / task paths import these symbols from @@ -22,7 +21,7 @@ _GLOBAL_MAX_IPC_SIZE: int class InnerStreamParser: """Split a byte stream into complete inner-IPC frames. - A frame is magic (ushort) plus total length (uint32) followed by the + A frame is magic (uint16_t) plus total length (uint32_t) followed by the payload. ``read`` returns every complete package currently buffered; an incomplete tail stays in the buffer across ``feeds_data``. """ diff --git a/trpc_sdk/transport/_cython/_ipc_codec.pyx b/trpc_sdk/transport/_cython/_ipc_codec.pyx index b764568..5366895 100644 --- a/trpc_sdk/transport/_cython/_ipc_codec.pyx +++ b/trpc_sdk/transport/_cython/_ipc_codec.pyx @@ -20,6 +20,9 @@ from the C++ driver's ``driver.h``. from libc.string cimport memcpy from libc.string cimport memmove +from libc.stdint cimport uint16_t +from libc.stdint cimport uint32_t +from libc.stdint cimport uint64_t from cpython.mem cimport PyMem_Free from cpython.mem cimport PyMem_Malloc from cpython.mem cimport PyMem_Realloc @@ -30,12 +33,12 @@ from .._constants import DEFAULT_MEM_SIZE as _PY_DEFAULT_MEM_SIZE from .._constants import FRAME_HEAD_LEN as _PY_FRAME_HEAD_LEN from .._constants import INNER_MAGIC_VALUE as _PY_INNER_MAGIC_VALUE -cdef ushort _INNER_MAGIC_VALUE = _PY_INNER_MAGIC_VALUE -cdef uint _FRAME_HEAD_LEN = _PY_FRAME_HEAD_LEN +cdef uint16_t _INNER_MAGIC_VALUE = _PY_INNER_MAGIC_VALUE +cdef uint32_t _FRAME_HEAD_LEN = _PY_FRAME_HEAD_LEN cdef int _DEFAULT_MEM_SIZE = _PY_DEFAULT_MEM_SIZE # sizeof(DataHeader) is a C layout fact; it cannot live in _constants.py. -cdef uint _C_UDP_PACKAGE_HEADER_LEN = sizeof(DataHeader) +cdef uint32_t _C_UDP_PACKAGE_HEADER_LEN = sizeof(DataHeader) _UDP_PACKAGE_HEADER_LEN = _C_UDP_PACKAGE_HEADER_LEN _GLOBAL_MAX_IPC_SIZE = GLOBAL_MAX_IPC_SIZE @@ -43,7 +46,7 @@ _GLOBAL_MAX_IPC_SIZE = GLOBAL_MAX_IPC_SIZE cdef class InnerStreamParser: """Split a byte stream into complete inner-IPC frames. - A frame is ``ushort`` magic plus ``uint32`` total length followed by + A frame is ``uint16_t`` magic plus ``uint32_t`` total length followed by the payload. ``read`` returns every complete package currently buffered; an incomplete tail stays in ``buf`` across ``feeds_data``. """ @@ -89,17 +92,17 @@ cdef class InnerStreamParser: results = [] cdef int scan_end = 0 - cdef ushort stx = 0 - cdef uint package_len = 0 + cdef uint16_t magic = 0 + cdef uint32_t package_len = 0 cdef int resize = 0 while self.write_len >= scan_end + _FRAME_HEAD_LEN: - stx = dereference((self.buf + scan_end)) - if stx != _INNER_MAGIC_VALUE: + magic = dereference((self.buf + scan_end)) + if magic != _INNER_MAGIC_VALUE: raise ServerDecodeError("invalid inner magic number in InnerStreamParser") - package_len = dereference((self.buf + scan_end + 2)) + package_len = dereference((self.buf + scan_end + 2)) if self.write_len < scan_end + package_len: break @@ -161,24 +164,24 @@ cdef class InnerDatagramParser: return header.flags -cpdef bytes encode_worker_msg_req(uint from_worker, bytes data): +cpdef bytes encode_worker_msg_req(uint32_t from_worker, bytes data): """Encode one inter-worker broadcast frame. - Layout after the payload is prefixed with ``+10`` bytes: + Layout after the payload is prefixed with ``10`` bytes: magic (2) + total length (4) + ``from_worker`` (4). Args: from_worker: Sender worker id written after the inner header. data: Payload bytes, not including a header. """ - cdef uint data_len = len(data) - cdef uint package_len = data_len + 10 + cdef uint32_t data_len = len(data) + cdef uint32_t package_len = data_len + 10 cdef char* to_ptr = PyMem_Malloc(package_len) - ((to_ptr))[0] = _INNER_MAGIC_VALUE - ((to_ptr + 2))[0] = package_len - ((to_ptr + 6))[0] = from_worker + ((to_ptr))[0] = _INNER_MAGIC_VALUE + ((to_ptr + 2))[0] = package_len + ((to_ptr + 6))[0] = from_worker cdef char* data_ptr = data memcpy(to_ptr + 10, data_ptr, data_len) @@ -199,17 +202,17 @@ cpdef decode_worker_msg_req(bytes data): """ cdef char* from_ptr = data - cdef magic = dereference((from_ptr)) + cdef magic = dereference((from_ptr)) if magic != _INNER_MAGIC_VALUE: raise ServerDecodeError("invalid inner magic number in decode_worker_msg_req") - cdef data_len = dereference((from_ptr + 2)) - cdef from_id = dereference((from_ptr + 6)) + cdef data_len = dereference((from_ptr + 2)) + cdef from_id = dereference((from_ptr + 6)) return from_id, bytes(from_ptr[10:data_len]) -cpdef bytes inner_encode_req(uint fd, uint port, uint session_id, ulong recv_time, bytes remote_ip, bytes data): +cpdef bytes inner_encode_req(uint32_t fd, uint32_t port, uint32_t session_id, uint64_t recv_time, bytes remote_ip, bytes data): """Encode one stream-IPC request from the Python dispatcher. The ``+28`` prefix is the historical hand-packed layout (magic, len, @@ -223,18 +226,18 @@ cpdef bytes inner_encode_req(uint fd, uint port, uint session_id, ulong recv_tim remote_ip: Packed peer address bytes. data: Request body. """ - cdef uint ip_len = len(remote_ip) - cdef uint data_len = len(data) - cdef uint package_len = data_len + 28 + ip_len + cdef uint32_t ip_len = len(remote_ip) + cdef uint32_t data_len = len(data) + cdef uint32_t package_len = data_len + 28 + ip_len cdef char* to_ptr = PyMem_Malloc(package_len) - ((to_ptr))[0] = _INNER_MAGIC_VALUE - ((to_ptr + 2))[0] = package_len - ((to_ptr + 6))[0] = fd - ((to_ptr + 10))[0] = port - ((to_ptr + 14))[0] = session_id - ((to_ptr + 18))[0] = recv_time + ((to_ptr))[0] = _INNER_MAGIC_VALUE + ((to_ptr + 2))[0] = package_len + ((to_ptr + 6))[0] = fd + ((to_ptr + 10))[0] = port + ((to_ptr + 14))[0] = session_id + ((to_ptr + 18))[0] = recv_time ((to_ptr + 26))[0] = ip_len cdef char* remote_ip_ptr = remote_ip @@ -248,7 +251,7 @@ cpdef bytes inner_encode_req(uint fd, uint port, uint session_id, ulong recv_tim return results -cpdef bytes inner_encode_data_header_req(uint fd, uint port, uint session_id, ulong recv_time, bytes remote_ip, bytes data): +cpdef bytes inner_encode_data_header_req(uint32_t fd, uint32_t port, uint32_t session_id, uint64_t recv_time, bytes remote_ip, bytes data): """Encode one datagram-IPC request using ``DataHeader``. Args: @@ -261,9 +264,9 @@ cpdef bytes inner_encode_data_header_req(uint fd, uint port, uint session_id, ul """ # port and remote_ip are intentionally not packed; C dispatcher # recovers the peer from its connection table. - cdef uint ip_len = len(remote_ip) - cdef uint data_len = len(data) - cdef uint package_len = data_len + _C_UDP_PACKAGE_HEADER_LEN + cdef uint32_t ip_len = len(remote_ip) + cdef uint32_t data_len = len(data) + cdef uint32_t package_len = data_len + _C_UDP_PACKAGE_HEADER_LEN cdef DataHeader* to_ptr = PyMem_Malloc(package_len) @@ -293,15 +296,15 @@ cpdef inner_decode_req(bytes data): """ cdef char* from_ptr = data - cdef magic = dereference((from_ptr)) + cdef magic = dereference((from_ptr)) if magic != _INNER_MAGIC_VALUE: raise ServerDecodeError("invalid inner magic number in inner_decode_req") - cdef data_len = dereference((from_ptr + 2)) - cdef fd = dereference((from_ptr + 6)) - cdef port = dereference((from_ptr + 10)) - cdef session_id = dereference((from_ptr + 14)) - cdef recv_time = dereference((from_ptr + 18)) + cdef data_len = dereference((from_ptr + 2)) + cdef fd = dereference((from_ptr + 6)) + cdef port = dereference((from_ptr + 10)) + cdef session_id = dereference((from_ptr + 14)) + cdef recv_time = dereference((from_ptr + 18)) cdef ip_len = dereference((from_ptr + 26)) return fd, port, session_id, recv_time, bytes(from_ptr[28:28 + ip_len]), bytes(from_ptr[28 + ip_len:data_len]) @@ -315,7 +318,7 @@ cdef class PipeDataHeader: """ cdef DataHeader *header cdef public int fd - cdef public long session_id + cdef public uint32_t session_id cdef public double recv_time cdef public int port_id cdef public int worker_id @@ -350,7 +353,7 @@ cpdef inner_decode_data_header_req(bytes data): return header -cpdef bytes inner_encode_rsp(uint fd, uint session_id, uint timeout, bytes data): +cpdef bytes inner_encode_rsp(uint32_t fd, uint32_t session_id, uint32_t timeout, bytes data): """Encode one stream-IPC response from a worker to the dispatcher. The ``+18`` prefix is magic (2) + len (4) + fd (4) + session (4) + @@ -363,16 +366,16 @@ cpdef bytes inner_encode_rsp(uint fd, uint session_id, uint timeout, bytes data) timeout: Unused timeout slot kept for the historical frame layout. data: Response body. """ - cdef uint data_len = len(data) - cdef uint package_len = data_len + 18 + cdef uint32_t data_len = len(data) + cdef uint32_t package_len = data_len + 18 cdef char* to_ptr = PyMem_Malloc(package_len) - ((to_ptr))[0] = _INNER_MAGIC_VALUE - ((to_ptr + 2))[0] = package_len - ((to_ptr + 6))[0] = fd - ((to_ptr + 10))[0] = session_id - ((to_ptr + 14))[0] = timeout + ((to_ptr))[0] = _INNER_MAGIC_VALUE + ((to_ptr + 2))[0] = package_len + ((to_ptr + 6))[0] = fd + ((to_ptr + 10))[0] = session_id + ((to_ptr + 14))[0] = timeout cdef char* data_ptr = data memcpy(to_ptr + 18, data_ptr, data_len) @@ -382,7 +385,7 @@ cpdef bytes inner_encode_rsp(uint fd, uint session_id, uint timeout, bytes data) return results -cpdef bytes inner_encode_data_header_rsp(uint fd, uint session_id, uint worker_id, uint flag, bytes data): +cpdef bytes inner_encode_data_header_rsp(uint32_t fd, uint32_t session_id, uint32_t worker_id, uint32_t flag, bytes data): """Encode one datagram-IPC response using ``DataHeader``. ``flags`` is CHUNK / CHUNK_END so the C dispatcher can reassemble a @@ -395,8 +398,8 @@ cpdef bytes inner_encode_data_header_rsp(uint fd, uint session_id, uint worker_i flag: A :class:`~trpc_sdk.transport._types.UDPPackageType` value. data: One datagram body, possibly a slice of a larger response. """ - cdef uint data_len = len(data) - cdef uint package_len = data_len + _C_UDP_PACKAGE_HEADER_LEN + cdef uint32_t data_len = len(data) + cdef uint32_t package_len = data_len + _C_UDP_PACKAGE_HEADER_LEN cdef DataHeader *header = PyMem_Malloc(package_len) @@ -427,13 +430,13 @@ cpdef inner_decode_rsp(bytes data): """ cdef char* from_ptr = data - cdef magic = dereference((from_ptr)) + cdef magic = dereference((from_ptr)) if magic != _INNER_MAGIC_VALUE: raise ServerDecodeError("invalid inner magic number in inner_decode_rsp") - cdef data_len = dereference((from_ptr + 2)) - cdef fd = dereference((from_ptr + 6)) - cdef session_id = dereference((from_ptr + 10)) - cdef timeout = dereference((from_ptr + 14)) + cdef data_len = dereference((from_ptr + 2)) + cdef fd = dereference((from_ptr + 6)) + cdef session_id = dereference((from_ptr + 10)) + cdef timeout = dereference((from_ptr + 14)) return fd, session_id, timeout, bytes(from_ptr[18:data_len]) diff --git a/trpc_sdk/transport/_pool/__init__.py b/trpc_sdk/transport/_pool/__init__.py deleted file mode 100644 index 4c5164c..0000000 --- a/trpc_sdk/transport/_pool/__init__.py +++ /dev/null @@ -1,61 +0,0 @@ -# Tencent is pleased to support the open source community by making tRPC-Python available. -# -# Copyright (C) 2026 Tencent. All rights reserved. -# -# tRPC-Python is licensed under Apache-2.0. - -"""Client TCP / Unix connection pools used by the client transport half. - -Pooling is a tRPC-Python extension, not part of the cross-language tRPC -architecture, so it lives inside :mod:`trpc_sdk.transport` rather than -at the top level. Only the client round trips in -``_client_transport*`` dial through it; the server half never does. - -The package is split by responsibility: - -- :mod:`~trpc_sdk.transport._pool._base` -- the ``BasePool`` get/put - contract -- :mod:`~trpc_sdk.transport._pool._types` -- :class:`ConnPoolOptions` - and address keys -- :mod:`~trpc_sdk.transport._pool._constants` -- default stream-reader - buffer limit -- :mod:`~trpc_sdk.transport._pool._dial` -- shared TCP/Unix connect - helper over the stdlib ``asyncio.open_connection`` -- :mod:`~trpc_sdk.transport._pool._pooled_connection` -- - :class:`PooledConnection` -- :mod:`~trpc_sdk.transport._pool._short_conn_factory` -- one-shot conn - that is never queued idle -- :mod:`~trpc_sdk.transport._pool._connection_pool` -- idle-queue pool, - manager, and :func:`get_pool_connection` -""" - -from __future__ import annotations - -from asyncio import IncompleteReadError -from asyncio import LimitOverrunError - -from ._base import BasePool -from ._connection_pool import ConnectionPool -from ._connection_pool import ConnectionPoolManager -from ._connection_pool import Pool -from ._connection_pool import PoolCache -from ._connection_pool import get_pool_connection -from ._pooled_connection import PooledConnection -from ._short_conn_factory import ShortConnFactory -from ._types import ConnAddress -from ._types import ConnPoolOptions - -__all__ = [ - "BasePool", - "ConnAddress", - "ConnPoolOptions", - "PooledConnection", - "ConnectionPool", - "ConnectionPoolManager", - "Pool", - "PoolCache", - "ShortConnFactory", - "get_pool_connection", - "IncompleteReadError", - "LimitOverrunError", -] diff --git a/trpc_sdk/transport/_scheduler.py b/trpc_sdk/transport/_scheduler.py index 02677c4..ea7727f 100644 --- a/trpc_sdk/transport/_scheduler.py +++ b/trpc_sdk/transport/_scheduler.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Dispatcher-side worker selection. After the dispatcher splits a complete frame, it must choose which worker IPC @@ -117,8 +116,9 @@ def select_rpc_task(schedule: SchedulerParams, alive: Sequence[bool]) -> Optiona return picked if not _warned_bad_hook_index: _warned_bad_hook_index = True - logger.warning("[scheduler] custom scheduler returned %r, which is not a live rpc task in [0, %s); " - "falling back to round-robin (reported once)", picked, count) + logger.warning( + "[scheduler] custom scheduler returned %r, which is not a live rpc task in [0, %s); " + "falling back to round-robin (reported once)", picked, count) for _ in range(count): index = _default_dispatcher_worker(schedule) @@ -127,9 +127,8 @@ def select_rpc_task(schedule: SchedulerParams, alive: Sequence[bool]) -> Optiona return None -def register_dispatcher_worker_func( - dispatcher_worker: Optional[Callable[[SchedulerParams], int]], - is_scheduler: bool = False) -> None: +def register_dispatcher_worker_func(dispatcher_worker: Optional[Callable[[SchedulerParams], int]], + is_scheduler: bool = False) -> None: """Install or clear a custom unary worker-selection hook. Passing ``None`` clears that hook. Streaming frames ignore both hooks. diff --git a/trpc_sdk/transport/_separate.py b/trpc_sdk/transport/_separate.py index e3a0a1a..c4b3d9b 100644 --- a/trpc_sdk/transport/_separate.py +++ b/trpc_sdk/transport/_separate.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """asyncio protocols for both ends of the separate-mode IPC pipes. The I/O process (``app`` is its :class:`~trpc_sdk.runtime.SeparateWorker`) @@ -232,8 +231,7 @@ def _forward_frames_to_workers(self, packages) -> None: report_attr("trpc_dispatcher_worker_conn_closed", 1) logger.warning("[dispatcher] pipe to rpc task %s is closed; frame dropped", index) continue - worker_conn.write(inner_encode_req(self.fd, self.index, self.session_id, now_ms(), self.addr_info, - package)) + worker_conn.write(inner_encode_req(self.fd, self.index, self.session_id, now_ms(), self.addr_info, package)) def data_received(self, data: bytes) -> None: """Feed upstream bytes into the parser and forward complete frames. diff --git a/trpc_sdk/transport/_server/_acceptor.py b/trpc_sdk/transport/_server/_acceptor.py index 6c49050..3a41806 100644 --- a/trpc_sdk/transport/_server/_acceptor.py +++ b/trpc_sdk/transport/_server/_acceptor.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Main-thread accept loop that hands connections to serving loop threads. A threaded worker binds each public address once and accepts on the main @@ -211,8 +210,8 @@ def _pause_on_resource_error(self, err: OSError) -> None: Args: err: The ``OSError`` that made ``accept()`` fail. """ - logger.error("[acceptor] accept on %s out of resources (%s); pausing %.1fs", - self.address, repr(err), ACCEPT_RETRY_DELAY) + logger.error("[acceptor] accept on %s out of resources (%s); pausing %.1fs", self.address, repr(err), + ACCEPT_RETRY_DELAY) self._disarm_reader() self._loop.call_later(ACCEPT_RETRY_DELAY, self._arm_reader) @@ -247,9 +246,7 @@ class StreamListener: where it was started. """ - def __init__(self, - server: Optional[asyncio.AbstractServer] = None, - acceptor: Optional[Acceptor] = None) -> None: + def __init__(self, server: Optional[asyncio.AbstractServer] = None, acceptor: Optional[Acceptor] = None) -> None: self.server = server self.acceptor = acceptor self._closed = False diff --git a/trpc_sdk/transport/_server/_conn_writer.py b/trpc_sdk/transport/_server/_conn_writer.py index 2a3c9cf..e8fc597 100644 --- a/trpc_sdk/transport/_server/_conn_writer.py +++ b/trpc_sdk/transport/_server/_conn_writer.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Write-back handle that answers on a connection's transport from any thread. An asyncio transport may only be touched from the loop that created it. diff --git a/trpc_sdk/transport/_server/_constants.py b/trpc_sdk/transport/_server/_constants.py index 7608bcd..6def336 100644 --- a/trpc_sdk/transport/_server/_constants.py +++ b/trpc_sdk/transport/_server/_constants.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Constants of the server listen transports.""" from __future__ import annotations diff --git a/trpc_sdk/transport/_server/_custom_transport.py b/trpc_sdk/transport/_server/_custom_transport.py index 1d67cb3..e7824cb 100644 --- a/trpc_sdk/transport/_server/_custom_transport.py +++ b/trpc_sdk/transport/_server/_custom_transport.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """User protocol starters, served through :class:`UserProtocolTransport`. A service whose ``protocol`` has a starter registered with diff --git a/trpc_sdk/transport/_server/_cython/__init__.py b/trpc_sdk/transport/_server/_cython/__init__.py index 319d9e6..6671537 100644 --- a/trpc_sdk/transport/_server/_cython/__init__.py +++ b/trpc_sdk/transport/_server/_cython/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Cython TCP asyncio Protocol used by merge workers and executors.""" from ._tcp_protocol import TCPConnection # pyright: ignore[reportMissingModuleSource] diff --git a/trpc_sdk/transport/_server/_cython/_tcp_protocol.pxd b/trpc_sdk/transport/_server/_cython/_tcp_protocol.pxd index 3fabd79..864980b 100644 --- a/trpc_sdk/transport/_server/_cython/_tcp_protocol.pxd +++ b/trpc_sdk/transport/_server/_cython/_tcp_protocol.pxd @@ -20,7 +20,7 @@ cdef class TCPConnection: public object aio_connection # asyncio.Transport; None until connection_made. public object parser # Per-connection frame splitter from parser.create(). public object shared_pool # SharedHandlerPool (io_handle_type: separate), else None. - public object writer # ConnWriter: from connection_made under shared_pool, else from the first stream frame. + public object writer # ConnWriter: connection_made if shared_pool, else the first stream frame. readonly int session_id # Process-unique, non-zero; assigned in connection_made. readonly bint has_streams # Set by the first stream frame; close() then aborts the streams. readonly object stream_dispatcher # StreamDispatcher of the service; None until the first stream frame. diff --git a/trpc_sdk/transport/_server/_cython/_tcp_protocol.pyi b/trpc_sdk/transport/_server/_cython/_tcp_protocol.pyi index 86bae3d..a27a847 100644 --- a/trpc_sdk/transport/_server/_cython/_tcp_protocol.pyi +++ b/trpc_sdk/transport/_server/_cython/_tcp_protocol.pyi @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Type hints for the merge / executor TCP asyncio Protocol. ``TCPConnection`` is the Protocol bound to one accepted client socket. diff --git a/trpc_sdk/transport/_server/_stream_connection.py b/trpc_sdk/transport/_server/_stream_connection.py index 645794a..332a0ce 100644 --- a/trpc_sdk/transport/_server/_stream_connection.py +++ b/trpc_sdk/transport/_server/_stream_connection.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Accepted stream connections of a server listen socket, and their options. A listen socket's protocol factory is one of two shapes, chosen by @@ -77,9 +76,9 @@ def _to_host_port(addr: Any) -> Tuple[str, int]: class ServerConnection(Protocol): """What ``TrpcServerTransport._msg_handler`` reads from ``conn``. - For TCP it is the :class:`DefaultIoConnection` itself; one connection - has one peer, so its addresses never change. - For UDP it is a per-datagram ``DatagramPeer``, so a handler always sees + For TCP it is the :class:`DefaultIoConnection` itself; one connection + has one peer, so its addresses never change. + For UDP it is a per-datagram ``DatagramPeer``, so a handler always sees its own datagram's source no matter how many datagrams arrived after it. Attributes: @@ -227,8 +226,7 @@ def __init__(self, option: ConnectionOption) -> None: self.parser = option.parser.create() self._init_handler = option.connection_init_handler or self._default_connection_init_handler self._close_handler = option.connection_close_handler or self._default_connection_close_handler - self._idle_clean_handler = (option.connection_idle_clean_handler - or self._default_connection_idle_clean_handler) + self._idle_clean_handler = (option.connection_idle_clean_handler or self._default_connection_idle_clean_handler) def connection_made(self, transport: asyncio.BaseTransport) -> None: """Record the transport and addresses, run the init callback, start the idle timer.""" @@ -260,14 +258,18 @@ def data_received(self, data: bytes) -> None: frames = self.parser.read() except ServerDecodeError as err: report_attr("trpc_io_connection_read_err", 1) - logger.error(f"[io_connection] failed to decode in client conn, remote_addr: " - f"{self.remote_addr}, err: {err}", exc_info=True) + logger.error( + f"[io_connection] failed to decode in client conn, remote_addr: " + f"{self.remote_addr}, err: {err}", + exc_info=True) self.close() return except Exception as err: # pylint: disable=broad-except report_attr("trpc_io_connection_read_fatal_err", 1) - logger.error(f"[io_connection] fatal err while decoding in client conn, remote_addr: " - f"{self.remote_addr}, err: {err}", exc_info=True) + logger.error( + f"[io_connection] fatal err while decoding in client conn, remote_addr: " + f"{self.remote_addr}, err: {err}", + exc_info=True) self.close() return if not frames: diff --git a/trpc_sdk/transport/_server/_stream_factory.py b/trpc_sdk/transport/_server/_stream_factory.py index 875c70f..5a2e994 100644 --- a/trpc_sdk/transport/_server/_stream_factory.py +++ b/trpc_sdk/transport/_server/_stream_factory.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Plugin factory and public aliases for the tRPC server transport. Importing this module registers ``TrpcServerTransportFactory`` under diff --git a/trpc_sdk/transport/_server/_trpc_transport.py b/trpc_sdk/transport/_server/_trpc_transport.py index e1e5523..3b79eaa 100644 --- a/trpc_sdk/transport/_server/_trpc_transport.py +++ b/trpc_sdk/transport/_server/_trpc_transport.py @@ -112,9 +112,9 @@ class TrpcServerTransport(BaseServerTransport): default. A subclass serving another protocol over the same listen machinery calls :meth:`set_io_connection`, overrides :meth:`_msg_handler` and, when the framing differs, sets another ``opts.parser``; its - connections are then :class:`DefaultIoConnection` objects. Datagrams - are always served by :class:`DefaultDatagramConnection`, which - hands every frame to :meth:`_msg_handler`. + connections are then :class:`DefaultIoConnection` objects. Datagrams are + always served by :class:`DefaultDatagramConnection`, which hands every + frame to :meth:`_msg_handler`. Attributes: opts: Options recorded by :meth:`bind`. diff --git a/trpc_sdk/transport/_types.py b/trpc_sdk/transport/_types.py index 8221f48..b88f9bc 100644 --- a/trpc_sdk/transport/_types.py +++ b/trpc_sdk/transport/_types.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Shared type definitions for the server-side transport package.""" from __future__ import annotations @@ -77,7 +76,7 @@ class SchedulerParams: class UDPPackageType(IntEnum): """Flag values written into ``DataHeader.flags`` for C-dispatcher UDP IPC. - ``feeds_data`` and ``inner_encode_data_header_rsp`` exchange these as C ``uint``. + ``feeds_data`` and ``inner_encode_data_header_rsp`` exchange these as C ``uint32_t``. ``IntEnum`` keeps ``package_flag == UDPPackageType.COMPLETE`` true when the Cython side returns a plain ``int``. """ diff --git a/trpc_sdk/utils/__init__.py b/trpc_sdk/utils/__init__.py index 7a3c09f..08198a6 100644 --- a/trpc_sdk/utils/__init__.py +++ b/trpc_sdk/utils/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Shared helpers used across tRPC-Python packages. Public symbols are re-exported here. Callers should ``from trpc_sdk.utils diff --git a/trpc_sdk/utils/_address.py b/trpc_sdk/utils/_address.py index 2645742..aaccdf0 100644 --- a/trpc_sdk/utils/_address.py +++ b/trpc_sdk/utils/_address.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Host/port helpers for asyncio transports and the tRPC message context. :data:`AddrType` is defined in :mod:`trpc.utils._types` and re-exported diff --git a/trpc_sdk/utils/_constants.py b/trpc_sdk/utils/_constants.py index 4038b68..e8c35d5 100644 --- a/trpc_sdk/utils/_constants.py +++ b/trpc_sdk/utils/_constants.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Shared constants for :mod:`trpc_sdk.utils`. This module is the bottom of the utils import graph: it must not import diff --git a/trpc_sdk/utils/_cython/__init__.py b/trpc_sdk/utils/_cython/__init__.py index 8677205..aa0e398 100644 --- a/trpc_sdk/utils/_cython/__init__.py +++ b/trpc_sdk/utils/_cython/__init__.py @@ -3,5 +3,4 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Header-only Cython helpers (``.pxd`` with ``cdef inline`` functions); nothing to import at runtime.""" diff --git a/trpc_sdk/utils/_dict_to_pb.py b/trpc_sdk/utils/_dict_to_pb.py index ed966cb..0fa84e1 100644 --- a/trpc_sdk/utils/_dict_to_pb.py +++ b/trpc_sdk/utils/_dict_to_pb.py @@ -9,7 +9,6 @@ # https://github.com/kaporzhu/protobuf-to-dict). That work is dedicated # to the public domain under the Unlicense. This file keeps only the # dict-to-protobuf direction. - """Fill a protobuf message from a dict (form / query-string path). """ @@ -53,11 +52,11 @@ def dict_to_protobuf( - pb_class_or_instance: PbMessage, - values: Dict[str, Any], - type_callable_map: Optional[Dict[Any, Any]] = None, - strict: bool = True, - ignore_none: bool = False, + pb_class_or_instance: PbMessage, + values: Dict[str, Any], + type_callable_map: Optional[Dict[Any, Any]] = None, + strict: bool = True, + ignore_none: bool = False, ) -> PbMessage: """Populate a protobuf message from a dictionary. @@ -85,9 +84,9 @@ def dict_to_protobuf( def _collect_field_entries( - pb_msg: PbMessage, - values: Dict[str, Any], - strict: bool, + pb_msg: PbMessage, + values: Dict[str, Any], + strict: bool, ) -> List[Tuple[FieldDescriptor, Any, object]]: """Resolve dict keys to ``(descriptor, input_value, target)`` entries. @@ -133,11 +132,11 @@ def _collect_field_entries( def _fill_message( - pb_msg: PbMessage, - values: Dict[str, Any], - type_callable_map: Dict[Any, Any], - strict: bool, - ignore_none: bool, + pb_msg: PbMessage, + values: Dict[str, Any], + type_callable_map: Dict[Any, Any], + strict: bool, + ignore_none: bool, ) -> PbMessage: """Write every resolved entry of ``values`` onto ``pb_msg``. @@ -191,11 +190,11 @@ def _fill_message( def _extend_repeated_field( - field: FieldDescriptor, - items: Iterable, - target: object, - type_callable_map: Dict[Any, Any], - strict: bool, + field: FieldDescriptor, + items: Iterable, + target: object, + type_callable_map: Dict[Any, Any], + strict: bool, ) -> None: """Append coerced scalar ``items`` to the repeated container ``target``. @@ -224,10 +223,10 @@ def _extend_repeated_field( def _coerce_scalar( - field: FieldDescriptor, - input_value: Any, - type_callable_map: Dict[Any, Any], - strict: bool, + field: FieldDescriptor, + input_value: Any, + type_callable_map: Dict[Any, Any], + strict: bool, ) -> Optional[Any]: """Convert one raw value to the Python type expected by ``field``. diff --git a/trpc_sdk/utils/_loop_lib.py b/trpc_sdk/utils/_loop_lib.py index 0499f77..00e90b8 100644 --- a/trpc_sdk/utils/_loop_lib.py +++ b/trpc_sdk/utils/_loop_lib.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Event-loop policy helpers for the tRPC process. Whether uvloop is used comes from the ``global.enable_uvloop`` key of the diff --git a/trpc_sdk/utils/_network.py b/trpc_sdk/utils/_network.py index eff10a5..278102e 100644 --- a/trpc_sdk/utils/_network.py +++ b/trpc_sdk/utils/_network.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """IP, port, and socket helpers used by the server adapter and connection pool. Port probes here are *availability* checks, not format-only validators: @@ -39,7 +38,6 @@ from ._types import IpType from ._types import PortType - # Maps ``ipaddress.IPv*Address.version`` (4 / 6) onto ``socket.AF_*``. # Used only by :func:`create_probe_socket` for short-lived port probes; # listen sockets are created by :func:`create_new_socket`. @@ -220,13 +218,11 @@ def _probe_port_available(ip: IpType, port: PortType, is_udp: bool) -> bool: socket_tmp.bind((ip, port)) return True if socket_tmp.connect_ex((ip, port)) == 0: - logger.error( - f"tcp port valid check failed, (ip:{ip} port:{port}) has been occupied") + logger.error(f"tcp port valid check failed, (ip:{ip} port:{port}) has been occupied") return False return True except Exception as err: # pylint: disable=broad-except - logger.error( - f"{protocol} port valid check failed, (ip:{ip} port:{port}) appear err: {err}") + logger.error(f"{protocol} port valid check failed, (ip:{ip} port:{port}) appear err: {err}") return False finally: if socket_tmp: diff --git a/trpc_sdk/utils/_process_sync.py b/trpc_sdk/utils/_process_sync.py index c76786d..972c163 100644 --- a/trpc_sdk/utils/_process_sync.py +++ b/trpc_sdk/utils/_process_sync.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Cross-process synchronization primitives shared across fork. Three primitives live here, all backed by ``multiprocessing`` objects @@ -88,7 +87,7 @@ def io_ready_reached(cnt: int) -> bool: Returns: True once ``_io_ready_cnt.value >= cnt``. """ - global _io_ready_cnt, _io_lock + global _io_ready_cnt, _io_lock # noqa: F824 with _io_lock: return _io_ready_cnt.value >= cnt @@ -101,7 +100,7 @@ def inc_io_wait_count() -> None: :func:`wait_notify_in_io` return once the counter reaches their configured threshold. """ - global _io_ready_cnt, _io_lock + global _io_ready_cnt, _io_lock # noqa: F824 with _io_lock: _io_ready_cnt.value += 1 diff --git a/trpc_sdk/utils/_queue.py b/trpc_sdk/utils/_queue.py index e395da2..4fb5e2b 100644 --- a/trpc_sdk/utils/_queue.py +++ b/trpc_sdk/utils/_queue.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Async hand-off queue used by stream transports. Unlike :class:`asyncio.Queue`, this type is a single-waiter rendezvous diff --git a/trpc_sdk/utils/_singleton.py b/trpc_sdk/utils/_singleton.py index b267ba9..69d2dcd 100644 --- a/trpc_sdk/utils/_singleton.py +++ b/trpc_sdk/utils/_singleton.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Process-local singleton decorator. :func:`singleton` stores the first constructed instance in a closure @@ -49,19 +48,18 @@ def __init__(self, connection_string): instances = {} def get_instance(*args: Any, **kw: Any) -> _T: - """ - Creates or returns the singleton instance of the decorated class. - + """Creates or returns the singleton instance of the decorated class. + The first call creates the instance with provided arguments. Subsequent calls ignore the arguments and return the existing instance. - + Args: *args: Positional arguments for the class constructor (only used on first call) **kw: Keyword arguments for the class constructor (only used on first call) - + Returns: The singleton instance of the decorated class - + Note: If called with different arguments after first instantiation, the original instance will still be returned and new arguments diff --git a/trpc_sdk/utils/_str_utils.py b/trpc_sdk/utils/_str_utils.py index 313af20..9b8f9e8 100644 --- a/trpc_sdk/utils/_str_utils.py +++ b/trpc_sdk/utils/_str_utils.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """String helpers used by config parsing. :func:`str2bool` is the distutils-style truth parser consumed by diff --git a/trpc_sdk/utils/_time_utils.py b/trpc_sdk/utils/_time_utils.py index cf9a6c1..f1b2166 100644 --- a/trpc_sdk/utils/_time_utils.py +++ b/trpc_sdk/utils/_time_utils.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Unix timestamps used by RPCZ, the client, and transport timeouts. :func:`now_us` and :func:`now_ms` are bound at import time. When diff --git a/trpc_sdk/utils/_timer.py b/trpc_sdk/utils/_timer.py index 53bddba..13a69c0 100644 --- a/trpc_sdk/utils/_timer.py +++ b/trpc_sdk/utils/_timer.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Timer tasks, their registration records, and per-process / per-thread executors. Decorators run at import time in the parent. The executor instantiates @@ -185,8 +184,8 @@ class TimerExecutor: the process executor. """ - __slots__ = ("loop", "name", "thread_index", "_timers", "_handles", "_tasks", "_built", "_started", - "_owner_pid", "_owner_tid") + __slots__ = ("loop", "name", "thread_index", "_timers", "_handles", "_tasks", "_built", "_started", "_owner_pid", + "_owner_tid") def __init__(self, loop: Optional[asyncio.AbstractEventLoop] = None, diff --git a/trpc_sdk/utils/_types.py b/trpc_sdk/utils/_types.py index e558a61..6a20ce4 100644 --- a/trpc_sdk/utils/_types.py +++ b/trpc_sdk/utils/_types.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Shared type aliases for :mod:`trpc_sdk.utils`. Address, IP, and port aliases are used by :mod:`trpc_sdk.utils._address` diff --git a/trpc_sdk/utils/ipc/__init__.py b/trpc_sdk/utils/ipc/__init__.py index 7693136..648e1e8 100644 --- a/trpc_sdk/utils/ipc/__init__.py +++ b/trpc_sdk/utils/ipc/__init__.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Inter-process primitives shared by every tRPC-Python process. A pipe here is a Unix-domain socketpair, and it is always created **before diff --git a/trpc_sdk/utils/ipc/_constants.py b/trpc_sdk/utils/ipc/_constants.py index e9c9e8b..6691266 100644 --- a/trpc_sdk/utils/ipc/_constants.py +++ b/trpc_sdk/utils/ipc/_constants.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Constants for tRPC-Python IPC primitives.""" from __future__ import annotations diff --git a/trpc_sdk/utils/ipc/_pipe.py b/trpc_sdk/utils/ipc/_pipe.py index 9ac1cb5..5de44c3 100644 --- a/trpc_sdk/utils/ipc/_pipe.py +++ b/trpc_sdk/utils/ipc/_pipe.py @@ -3,7 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. - """Unix-domain socketpairs used as IPC pipes between processes. :func:`create_pipe` makes the pair; :class:`PipeConnection` wraps one end of it diff --git a/trpc_sdk/version.py b/trpc_sdk/version.py index 82c8036..e636fb8 100644 --- a/trpc_sdk/version.py +++ b/trpc_sdk/version.py @@ -3,5 +3,6 @@ # Copyright (C) 2026 Tencent. All rights reserved. # # tRPC-Python is licensed under Apache-2.0. +"""tRPC-Python package version.""" __version__ = "1.0.0"