protoc-gen-grpc-py 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025-2026 Buf Technologies, Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,111 @@
1
+ Metadata-Version: 2.4
2
+ Name: protoc-gen-grpc-py
3
+ Version: 0.0.1
4
+ Summary:
5
+ Keywords: grpc,protobuf,rpc
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Environment :: Console
10
+ Classifier: Environment :: Plugins
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: Free Threading
21
+ Classifier: Topic :: File Formats
22
+ Classifier: Topic :: Software Development :: Code Generators
23
+ Requires-Dist: protobuf-py>=0.0.1
24
+ Requires-Python: >=3.10
25
+ Project-URL: Documentation, https://protobufpython.com/
26
+ Project-URL: Homepage, https://github.com/bufbuild/protobuf-py
27
+ Project-URL: Issues, https://github.com/bufbuild/protobuf-py/issues
28
+ Project-URL: Source, https://github.com/bufbuild/protobuf-py
29
+ Description-Content-Type: text/markdown
30
+
31
+ # protoc-gen-grpc-py
32
+
33
+ The gRPC code generator plugin for Protocol Buffers for Python. Learn more about the project at [github.com/bufbuild/protobuf-py](https://github.com/bufbuild/protobuf-py).
34
+
35
+ ## Overview
36
+
37
+ `protoc-gen-grpc-py` generates fully typed, idiomatic [gRPC](https://grpc.io) clients and servicers that use [protobuf-py](https://pypi.org/project/protobuf-py/) messages for serialization. Unlike the stock gRPC Python plugin, the generated stubs:
38
+
39
+ - are fully typed, so editors and type checkers understand every RPC method
40
+ - serialize `protobuf-py` messages directly, with no dependency on the `_pb2` Protobuf runtime
41
+ - ship both asyncio (`grpc.aio`) and synchronous variants.
42
+
43
+ For each service it emits a servicer base class (with an `add_to_server` method) and a client, in both async and sync flavors (the sync names are suffixed with `Sync`). Message types are generated separately by [`protoc-gen-py`](https://pypi.org/project/protoc-gen-py/).
44
+
45
+ ## Installation
46
+
47
+ The generated code requires the runtime libraries [protobuf-py](https://pypi.org/project/protobuf-py/) and [grpcio](https://pypi.org/project/grpcio/). The plugin is compatible with Protocol Buffer compilers like [buf](https://github.com/bufbuild/buf) and [protoc](https://github.com/protocolbuffers/protobuf/releases).
48
+
49
+ ```shellsession
50
+ $ uv add protobuf-py grpcio
51
+ $ uv add --dev protoc-gen-py protoc-gen-grpc-py buf-bin
52
+ ```
53
+
54
+ ## Generating code
55
+
56
+ ### With buf
57
+
58
+ Add `protoc-gen-grpc-py` alongside `protoc-gen-py` in your `buf.gen.yaml`:
59
+
60
+ ```yaml
61
+ version: v2
62
+ inputs:
63
+ - directory: proto
64
+ plugins:
65
+ # Generates message types (*_pb.py).
66
+ - local: protoc-gen-py
67
+ out: src/gen
68
+ # Generates gRPC service stubs (*_pb_grpc.py).
69
+ - local: protoc-gen-grpc-py
70
+ out: src/gen
71
+ ```
72
+
73
+ To generate code for all Protobuf files within your project, run:
74
+
75
+ ```shellsession
76
+ $ uv run -- buf generate
77
+ ```
78
+
79
+ ### With `protoc`
80
+
81
+ ```shellsession
82
+ $ uv run protoc --proto_path proto \
83
+ --py_out src/gen \
84
+ --grpc-py_out src/gen \
85
+ proto/a.proto proto/b.proto proto/c.proto
86
+ ```
87
+
88
+ A `*_pb_grpc.py` file is generated only for proto files that declare a service. The plugin does not emit `__init__.py` files; let `protoc-gen-py` manage those.
89
+
90
+ ## Plugin options
91
+
92
+ ### `io`
93
+
94
+ Controls which flavor of code is generated:
95
+
96
+ - unset (default): generate both asynchronous (`grpc.aio`) and synchronous (`grpc`) code;
97
+ - `io=async`: generate only asynchronous code;
98
+ - `io=sync`: generate only synchronous code.
99
+
100
+ For example, in `buf.gen.yaml`:
101
+
102
+ ```yaml
103
+ plugins:
104
+ - local: protoc-gen-grpc-py
105
+ out: src/gen
106
+ opt: io=async
107
+ ```
108
+
109
+ ## Example
110
+
111
+ See the [gRPC example](https://github.com/bufbuild/protobuf-py/tree/main/examples/grpc) for a complete client and server using the generated stubs.
@@ -0,0 +1,81 @@
1
+ # protoc-gen-grpc-py
2
+
3
+ The gRPC code generator plugin for Protocol Buffers for Python. Learn more about the project at [github.com/bufbuild/protobuf-py](https://github.com/bufbuild/protobuf-py).
4
+
5
+ ## Overview
6
+
7
+ `protoc-gen-grpc-py` generates fully typed, idiomatic [gRPC](https://grpc.io) clients and servicers that use [protobuf-py](https://pypi.org/project/protobuf-py/) messages for serialization. Unlike the stock gRPC Python plugin, the generated stubs:
8
+
9
+ - are fully typed, so editors and type checkers understand every RPC method
10
+ - serialize `protobuf-py` messages directly, with no dependency on the `_pb2` Protobuf runtime
11
+ - ship both asyncio (`grpc.aio`) and synchronous variants.
12
+
13
+ For each service it emits a servicer base class (with an `add_to_server` method) and a client, in both async and sync flavors (the sync names are suffixed with `Sync`). Message types are generated separately by [`protoc-gen-py`](https://pypi.org/project/protoc-gen-py/).
14
+
15
+ ## Installation
16
+
17
+ The generated code requires the runtime libraries [protobuf-py](https://pypi.org/project/protobuf-py/) and [grpcio](https://pypi.org/project/grpcio/). The plugin is compatible with Protocol Buffer compilers like [buf](https://github.com/bufbuild/buf) and [protoc](https://github.com/protocolbuffers/protobuf/releases).
18
+
19
+ ```shellsession
20
+ $ uv add protobuf-py grpcio
21
+ $ uv add --dev protoc-gen-py protoc-gen-grpc-py buf-bin
22
+ ```
23
+
24
+ ## Generating code
25
+
26
+ ### With buf
27
+
28
+ Add `protoc-gen-grpc-py` alongside `protoc-gen-py` in your `buf.gen.yaml`:
29
+
30
+ ```yaml
31
+ version: v2
32
+ inputs:
33
+ - directory: proto
34
+ plugins:
35
+ # Generates message types (*_pb.py).
36
+ - local: protoc-gen-py
37
+ out: src/gen
38
+ # Generates gRPC service stubs (*_pb_grpc.py).
39
+ - local: protoc-gen-grpc-py
40
+ out: src/gen
41
+ ```
42
+
43
+ To generate code for all Protobuf files within your project, run:
44
+
45
+ ```shellsession
46
+ $ uv run -- buf generate
47
+ ```
48
+
49
+ ### With `protoc`
50
+
51
+ ```shellsession
52
+ $ uv run protoc --proto_path proto \
53
+ --py_out src/gen \
54
+ --grpc-py_out src/gen \
55
+ proto/a.proto proto/b.proto proto/c.proto
56
+ ```
57
+
58
+ A `*_pb_grpc.py` file is generated only for proto files that declare a service. The plugin does not emit `__init__.py` files; let `protoc-gen-py` manage those.
59
+
60
+ ## Plugin options
61
+
62
+ ### `io`
63
+
64
+ Controls which flavor of code is generated:
65
+
66
+ - unset (default): generate both asynchronous (`grpc.aio`) and synchronous (`grpc`) code;
67
+ - `io=async`: generate only asynchronous code;
68
+ - `io=sync`: generate only synchronous code.
69
+
70
+ For example, in `buf.gen.yaml`:
71
+
72
+ ```yaml
73
+ plugins:
74
+ - local: protoc-gen-grpc-py
75
+ out: src/gen
76
+ opt: io=async
77
+ ```
78
+
79
+ ## Example
80
+
81
+ See the [gRPC example](https://github.com/bufbuild/protobuf-py/tree/main/examples/grpc) for a complete client and server using the generated stubs.
@@ -0,0 +1,57 @@
1
+ [project]
2
+ name = "protoc-gen-grpc-py"
3
+ version = "0.0.1"
4
+ description = ""
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ keywords = ["grpc", "protobuf", "rpc"]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Environment :: Console",
13
+ "Environment :: Plugins",
14
+ "Intended Audience :: Developers",
15
+ "Operating System :: OS Independent",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Programming Language :: Python :: Free Threading",
24
+ "Topic :: File Formats",
25
+ "Topic :: Software Development :: Code Generators",
26
+ ]
27
+ dependencies = [
28
+ "protobuf-py>=0.0.1",
29
+ ]
30
+
31
+ [project.urls]
32
+ Documentation = "https://protobufpython.com/"
33
+ Homepage = "https://github.com/bufbuild/protobuf-py"
34
+ Issues = "https://github.com/bufbuild/protobuf-py/issues"
35
+ Source = "https://github.com/bufbuild/protobuf-py"
36
+
37
+ [project.scripts]
38
+ protoc-gen-grpc-py = "protoc_gen_grpc_py:main"
39
+
40
+ [dependency-groups]
41
+ dev = [
42
+ "buf-bin==1.71.0",
43
+ # grpcio ships no wheels for PyPy; we do not build it from source there.
44
+ "grpcio==1.81.1 ; platform_python_implementation != 'PyPy'",
45
+ "protoc-gen-py>=0.0.1",
46
+ "pytest==9.1.1",
47
+ "pytest-asyncio==1.4.0",
48
+ ]
49
+
50
+ [build-system]
51
+ requires = ["uv_build>=0.11.2,<0.12"]
52
+ build-backend = "uv_build"
53
+
54
+ [tool.pytest.ini_options]
55
+ asyncio_mode = "strict"
56
+ asyncio_default_fixture_loop_scope = "session"
57
+ asyncio_default_test_loop_scope = "session"
@@ -0,0 +1,354 @@
1
+ # Copyright (c) 2025-2026 Buf Technologies, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """protoc-gen-grpc-py: a protoc plugin that generates gRPC Python stubs.
15
+
16
+ The generated stubs are fully typed and idiomatic, and use ``protobuf-py``
17
+ messages for serialization rather than the classic ``protobuf`` runtime.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import importlib.metadata
23
+ import re
24
+ from dataclasses import dataclass, field
25
+ from enum import Enum
26
+ from typing import TYPE_CHECKING
27
+
28
+ from protobuf._sanitization import (
29
+ PYTHON_KEYWORDS,
30
+ escape_identifier,
31
+ escape_public_identifier,
32
+ )
33
+ from protobuf.plugin import File, Ident, Module, Schema, get_comments, run
34
+
35
+ if TYPE_CHECKING:
36
+ from protobuf import DescFile, DescMethod, DescService
37
+
38
+ _RESERVED_METHOD_NAMES = PYTHON_KEYWORDS | {"add_to_server"}
39
+
40
+ _COLLECTIONS_ABC = Module("collections.abc")
41
+ _ASYNC_ITERATOR = _COLLECTIONS_ABC.ident("AsyncIterator", type_only=True)
42
+ _ITERATOR = _COLLECTIONS_ABC.ident("Iterator", type_only=True)
43
+ _SEQUENCE = _COLLECTIONS_ABC.ident("Sequence", type_only=True)
44
+
45
+ _GRPC = Module("grpc")
46
+ _STATUS_CODE = _GRPC.ident("StatusCode")
47
+ _UNARY_UNARY_HANDLER = _GRPC.ident("unary_unary_rpc_method_handler")
48
+ _UNARY_STREAM_HANDLER = _GRPC.ident("unary_stream_rpc_method_handler")
49
+ _STREAM_UNARY_HANDLER = _GRPC.ident("stream_unary_rpc_method_handler")
50
+ _STREAM_STREAM_HANDLER = _GRPC.ident("stream_stream_rpc_method_handler")
51
+ _GENERIC_HANDLER = _GRPC.ident("method_handlers_generic_handler")
52
+
53
+ _CHANNEL = _GRPC.ident("Channel", type_only=True)
54
+ _SERVER = _GRPC.ident("Server", type_only=True)
55
+ _SERVICER_CONTEXT = _GRPC.ident("ServicerContext", type_only=True)
56
+ _CALL_CREDENTIALS = _GRPC.ident("CallCredentials", type_only=True)
57
+ _COMPRESSION = _GRPC.ident("Compression", type_only=True)
58
+ _CALL_ITERATOR = _GRPC.ident("_CallIterator", type_only=True)
59
+ _AIO_METADATA = _GRPC.ident("aio.Metadata", type_only=True)
60
+ _AIO_CHANNEL = _GRPC.ident("aio.Channel", type_only=True)
61
+ _AIO_SERVER = _GRPC.ident("aio.Server", type_only=True)
62
+ _AIO_SERVICER_CONTEXT = _GRPC.ident("aio.ServicerContext", type_only=True)
63
+ _AIO_UNARY_UNARY_CALL = _GRPC.ident("aio.UnaryUnaryCall", type_only=True)
64
+ _AIO_UNARY_STREAM_CALL = _GRPC.ident("aio.UnaryStreamCall", type_only=True)
65
+ _AIO_STREAM_UNARY_CALL = _GRPC.ident("aio.StreamUnaryCall", type_only=True)
66
+ _AIO_STREAM_STREAM_CALL = _GRPC.ident("aio.StreamStreamCall", type_only=True)
67
+
68
+ _UNIMPLEMENTED_DETAILS = "Method not implemented!"
69
+
70
+
71
+ class _IOOption(Enum):
72
+ """Whether to generate synchronous or asynchronous code."""
73
+
74
+ SYNC = "sync"
75
+ """Generates only synchronous code."""
76
+
77
+ ASYNC = "async"
78
+ """Generates only asynchronous code."""
79
+
80
+
81
+ @dataclass
82
+ class _Options:
83
+ """Options for the protoc-gen-grpc-py plugin."""
84
+
85
+ io: _IOOption | None = field(default=None)
86
+ """The I/O mode for generated code."""
87
+
88
+
89
+ def _generate(schema: Schema[_Options]) -> None:
90
+ for file in schema.files_to_generate:
91
+ if not file.services:
92
+ continue
93
+ _generate_file(schema.generate_file(file, "_pb_grpc.py"), file, schema.options)
94
+
95
+
96
+ def _generate_file(f: File, desc: DescFile, options: _Options) -> None:
97
+ f.preamble(desc)
98
+ for service in desc.services:
99
+ if not options.io or options.io == _IOOption.ASYNC:
100
+ _generate_async_stubs(f, service)
101
+ if not options.io or options.io == _IOOption.SYNC:
102
+ _generate_sync_stubs(f, service)
103
+
104
+
105
+ def _generate_async_stubs(f: File, service: DescService) -> None:
106
+ _generate_servicer(f, service, is_async=True)
107
+ _generate_client(f, service, is_async=True)
108
+
109
+
110
+ def _generate_sync_stubs(f: File, service: DescService) -> None:
111
+ _generate_servicer(f, service, is_async=False)
112
+ _generate_client(f, service, is_async=False)
113
+
114
+
115
+ def _generate_servicer(f: File, service: DescService, *, is_async: bool) -> None:
116
+ context = _AIO_SERVICER_CONTEXT if is_async else _SERVICER_CONTEXT
117
+ with f.scope("class ", _servicer_name(service, is_async=is_async), ":"):
118
+ _generate_docstring(f, service)
119
+ for method in service.methods:
120
+ # Unary-response handlers are coroutines; streaming handlers are
121
+ # plain functions returning an (async) iterator
122
+ prefix = "async " if is_async and not _response_stream(method) else ""
123
+ with f.scope(
124
+ prefix,
125
+ "def ",
126
+ _method_local_name(method),
127
+ "(self, request",
128
+ "_iterator" if _request_stream(method) else "",
129
+ ": ",
130
+ *_request_type(method, is_async=is_async),
131
+ ", context: ",
132
+ context,
133
+ ") -> ",
134
+ *_servicer_return_type(method, is_async=is_async),
135
+ ":",
136
+ ):
137
+ _generate_docstring(f, method)
138
+ f.print("context.set_code(", _STATUS_CODE, ".UNIMPLEMENTED)")
139
+ f.print('context.set_details("', _UNIMPLEMENTED_DETAILS, '")')
140
+ f.print('raise NotImplementedError("', _UNIMPLEMENTED_DETAILS, '")')
141
+ f.print()
142
+ _generate_add_to_server(f, service, is_async=is_async)
143
+ f.print()
144
+
145
+
146
+ def _generate_add_to_server(f: File, service: DescService, *, is_async: bool) -> None:
147
+ server = _AIO_SERVER if is_async else _SERVER
148
+ with f.scope("def add_to_server(self, server: ", server, ") -> None:"):
149
+ with f.doc("Register this servicer's RPC handlers with a grpc server."):
150
+ pass
151
+ with f.scope("rpc_method_handlers = {"):
152
+ for method in service.methods:
153
+ with f.scope('"', method.name, '": ', _handler_factory(method), "("):
154
+ f.print("self.", _method_local_name(method), ",")
155
+ f.print("request_deserializer=", method.input, ".from_binary,")
156
+ f.print("response_serializer=", method.output, ".to_binary,")
157
+ f.print("),")
158
+ f.print("}")
159
+ with f.scope("generic_handler = ", _GENERIC_HANDLER, "("):
160
+ f.print('"', service.type_name, '",')
161
+ f.print("rpc_method_handlers,")
162
+ f.print(")")
163
+ f.print("server.add_generic_rpc_handlers((generic_handler,))")
164
+ f.print()
165
+
166
+
167
+ def _generate_client(f: File, service: DescService, *, is_async: bool) -> None:
168
+ channel = _AIO_CHANNEL if is_async else _CHANNEL
169
+ with f.scope("class ", _client_name(service, is_async=is_async), ":"):
170
+ _generate_docstring(f, service)
171
+ with f.scope("def __init__(self, channel: ", channel, ") -> None:"):
172
+ for method in service.methods:
173
+ with f.scope(
174
+ "self._",
175
+ _method_local_name(method),
176
+ " = channel.",
177
+ _channel_method(method),
178
+ "(",
179
+ ):
180
+ f.print('"', _method_url(method), '",')
181
+ f.print("request_serializer=", method.input, ".to_binary,")
182
+ f.print("response_deserializer=", method.output, ".from_binary,")
183
+ f.print(")")
184
+ f.print()
185
+ for method in service.methods:
186
+ _generate_client_method(f, method, is_async=is_async)
187
+ f.print()
188
+
189
+
190
+ def _generate_client_method(f: File, method: DescMethod, *, is_async: bool) -> None:
191
+ request_arg = "request_iterator" if _request_stream(method) else "request"
192
+ with f.scope("def ", _method_local_name(method), "("):
193
+ f.print("self,")
194
+ f.print(request_arg, ": ", *_request_type(method, is_async=is_async), ",")
195
+ f.print("*,")
196
+ # These per-call options mirror grpc's *MultiCallable.__call__ methods.
197
+ # grpc's own generated stubs type these as Any; we mirror them explicitly
198
+ # and must keep them in sync when grpc adds parameters. As of grpcio
199
+ # 1.81.1 the full set is: timeout, metadata, credentials, wait_for_ready,
200
+ # compression. See the *MultiCallable.__call__ signatures (pinned to the
201
+ # grpcio version this generator targets):
202
+ # sync: https://github.com/grpc/grpc/blob/e84a8a2f04095f2772ba42a4abccde4f9243e75b/src/python/grpcio/grpc/__init__.py#L683
203
+ # async: https://github.com/grpc/grpc/blob/e84a8a2f04095f2772ba42a4abccde4f9243e75b/src/python/grpcio/grpc/aio/_base_channel.py#L38
204
+ f.print("timeout: float | None = None,")
205
+ f.print("metadata: ", *_metadata_type(is_async=is_async), " | None = None,")
206
+ f.print("credentials: ", _CALL_CREDENTIALS, " | None = None,")
207
+ f.print("wait_for_ready: bool | None = None,")
208
+ f.print("compression: ", _COMPRESSION, " | None = None,")
209
+ with f.scope(") -> ", *_client_return_type(method, is_async=is_async), ":"):
210
+ _generate_docstring(f, method)
211
+ f.print(
212
+ "return self._",
213
+ _method_local_name(method),
214
+ "(",
215
+ request_arg,
216
+ ", timeout=timeout, metadata=metadata, credentials=credentials,"
217
+ " wait_for_ready=wait_for_ready, compression=compression)",
218
+ )
219
+ f.print()
220
+
221
+
222
+ def _request_type(method: DescMethod, *, is_async: bool) -> list[object]:
223
+ if _request_stream(method):
224
+ iterator = _ASYNC_ITERATOR if is_async else _ITERATOR
225
+ return [iterator, "[", method.input, "]"]
226
+ return [method.input]
227
+
228
+
229
+ def _metadata_type(*, is_async: bool) -> list[object]:
230
+ # The accepted metadata type differs between the sync and async APIs (these
231
+ # stubs are type-checked against typeshed).
232
+ # https://github.com/python/typeshed/blob/3f74e6eba99eb7ce60522e044cbb5d38f4c0dd92/stubs/grpcio/grpc/__init__.pyi#L37
233
+ # https://github.com/python/typeshed/blob/3f74e6eba99eb7ce60522e044cbb5d38f4c0dd92/stubs/grpcio/grpc/aio/__init__.pyi#L442
234
+ if is_async:
235
+ return [_AIO_METADATA, " | ", _SEQUENCE, "[tuple[str, str | bytes]]"]
236
+ return ["tuple[tuple[str, str | bytes], ...]"]
237
+
238
+
239
+ def _servicer_return_type(method: DescMethod, *, is_async: bool) -> list[object]:
240
+ # Servicer methods are the handlers grpc invokes: streaming handlers are
241
+ # (async) iterators/generators of the response message.
242
+ if _response_stream(method):
243
+ iterator = _ASYNC_ITERATOR if is_async else _ITERATOR
244
+ return [iterator, "[", method.output, "]"]
245
+ return [method.output]
246
+
247
+
248
+ def _client_return_type(method: DescMethod, *, is_async: bool) -> list[object]:
249
+ # Client methods return grpc's real call objects so callers keep full
250
+ # access to the response, status code, metadata, cancellation, etc.
251
+ if is_async:
252
+ return [_aio_call_ident(method), "[", method.input, ", ", method.output, "]"]
253
+ if _response_stream(method):
254
+ return [_CALL_ITERATOR, "[", method.output, "]"]
255
+ return [method.output]
256
+
257
+
258
+ def _servicer_name(service: DescService, *, is_async: bool) -> str:
259
+ suffix = "" if is_async else "Sync"
260
+ return f"{escape_identifier(service.name)}Servicer{suffix}"
261
+
262
+
263
+ def _client_name(service: DescService, *, is_async: bool) -> str:
264
+ suffix = "" if is_async else "Sync"
265
+ return f"{escape_identifier(service.name)}Client{suffix}"
266
+
267
+
268
+ def _request_stream(method: DescMethod) -> bool:
269
+ return method.method_kind in ("client_streaming", "bidi_streaming")
270
+
271
+
272
+ def _response_stream(method: DescMethod) -> bool:
273
+ return method.method_kind in ("server_streaming", "bidi_streaming")
274
+
275
+
276
+ def _channel_method(method: DescMethod) -> str:
277
+ request = "stream" if _request_stream(method) else "unary"
278
+ response = "stream" if _response_stream(method) else "unary"
279
+ return f"{request}_{response}"
280
+
281
+
282
+ def _handler_factory(method: DescMethod) -> Ident:
283
+ match method.method_kind:
284
+ case "unary":
285
+ return _UNARY_UNARY_HANDLER
286
+ case "server_streaming":
287
+ return _UNARY_STREAM_HANDLER
288
+ case "client_streaming":
289
+ return _STREAM_UNARY_HANDLER
290
+ case _:
291
+ return _STREAM_STREAM_HANDLER
292
+
293
+
294
+ def _aio_call_ident(method: DescMethod) -> Ident:
295
+ match method.method_kind:
296
+ case "unary":
297
+ return _AIO_UNARY_UNARY_CALL
298
+ case "server_streaming":
299
+ return _AIO_UNARY_STREAM_CALL
300
+ case "client_streaming":
301
+ return _AIO_STREAM_UNARY_CALL
302
+ case _:
303
+ return _AIO_STREAM_STREAM_CALL
304
+
305
+
306
+ def _method_local_name(method: DescMethod) -> str:
307
+ return escape_public_identifier(
308
+ _pascal_to_snake_case(method.name), _RESERVED_METHOD_NAMES
309
+ )
310
+
311
+
312
+ def _method_url(method: DescMethod) -> str:
313
+ return f"/{method.parent.type_name}/{method.name}"
314
+
315
+
316
+ _RE_UPPER_TO_LOWER = re.compile("([^_])([A-Z][a-z]+)")
317
+ _RE_LOWER_TO_UPPER = re.compile("([a-z])([A-Z])")
318
+
319
+
320
+ def _pascal_to_snake_case(text: str) -> str:
321
+ """Convert a PascalCase RPC name to snake_case."""
322
+ s1 = _RE_UPPER_TO_LOWER.sub(r"\1_\2", text)
323
+ return _RE_LOWER_TO_UPPER.sub(r"\1_\2", s1).lower()
324
+
325
+
326
+ def _generate_docstring(f: File, desc: DescService | DescMethod) -> None:
327
+ comments = get_comments(desc)
328
+ text = ""
329
+ if comments.leading:
330
+ text += comments.leading.removesuffix("\n")
331
+ if comments.trailing:
332
+ if text:
333
+ text += "\n\n"
334
+ text += comments.trailing.removesuffix("\n")
335
+ if not text:
336
+ return
337
+ lines = [line.removeprefix(" ") for line in text.splitlines()]
338
+ if len(lines) == 1:
339
+ with f.doc(lines[0]):
340
+ pass
341
+ else:
342
+ with f.doc():
343
+ for line in lines:
344
+ f.print(line)
345
+
346
+
347
+ def main() -> None:
348
+ """Entry point for the protoc-gen-grpc-py plugin."""
349
+ run(
350
+ "protoc-gen-grpc-py",
351
+ importlib.metadata.version("protoc-gen-grpc-py"),
352
+ _Options,
353
+ _generate,
354
+ )