xref: /aosp_15_r20/external/grpc-grpc/src/python/grpcio/grpc/_runtime_protos.py (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1# Copyright 2020 The gRPC authors.
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
15import sys
16import types
17from typing import Tuple, Union
18
19_REQUIRED_SYMBOLS = ("_protos", "_services", "_protos_and_services")
20_MINIMUM_VERSION = (3, 5, 0)
21
22_UNINSTALLED_TEMPLATE = (
23    "Install the grpcio-tools package (1.32.0+) to use the {} function."
24)
25_VERSION_ERROR_TEMPLATE = (
26    "The {} function is only on available on Python 3.X interpreters."
27)
28
29
30def _has_runtime_proto_symbols(mod: types.ModuleType) -> bool:
31    return all(hasattr(mod, sym) for sym in _REQUIRED_SYMBOLS)
32
33
34def _is_grpc_tools_importable() -> bool:
35    try:
36        import grpc_tools  # pylint: disable=unused-import # pytype: disable=import-error
37
38        return True
39    except ImportError as e:
40        # NOTE: It's possible that we're encountering a transitive ImportError, so
41        # we check for that and re-raise if so.
42        if "grpc_tools" not in e.args[0]:
43            raise
44        return False
45
46
47def _call_with_lazy_import(
48    fn_name: str, protobuf_path: str
49) -> Union[types.ModuleType, Tuple[types.ModuleType, types.ModuleType]]:
50    """Calls one of the three functions, lazily importing grpc_tools.
51
52    Args:
53      fn_name: The name of the function to import from grpc_tools.protoc.
54      protobuf_path: The path to import.
55
56    Returns:
57      The appropriate module object.
58    """
59    if sys.version_info < _MINIMUM_VERSION:
60        raise NotImplementedError(_VERSION_ERROR_TEMPLATE.format(fn_name))
61    else:
62        if not _is_grpc_tools_importable():
63            raise NotImplementedError(_UNINSTALLED_TEMPLATE.format(fn_name))
64        import grpc_tools.protoc  # pytype: disable=import-error
65
66        if _has_runtime_proto_symbols(grpc_tools.protoc):
67            fn = getattr(grpc_tools.protoc, "_" + fn_name)
68            return fn(protobuf_path)
69        else:
70            raise NotImplementedError(_UNINSTALLED_TEMPLATE.format(fn_name))
71
72
73def protos(protobuf_path):  # pylint: disable=unused-argument
74    """Returns a module generated by the indicated .proto file.
75
76    THIS IS AN EXPERIMENTAL API.
77
78    Use this function to retrieve classes corresponding to message
79    definitions in the .proto file.
80
81    To inspect the contents of the returned module, use the dir function.
82    For example:
83
84    ```
85    protos = grpc.protos("foo.proto")
86    print(dir(protos))
87    ```
88
89    The returned module object corresponds to the _pb2.py file generated
90    by protoc. The path is expected to be relative to an entry on sys.path
91    and all transitive dependencies of the file should also be resolveable
92    from an entry on sys.path.
93
94    To completely disable the machinery behind this function, set the
95    GRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to "true".
96
97    Args:
98      protobuf_path: The path to the .proto file on the filesystem. This path
99        must be resolveable from an entry on sys.path and so must all of its
100        transitive dependencies.
101
102    Returns:
103      A module object corresponding to the message code for the indicated
104      .proto file. Equivalent to a generated _pb2.py file.
105    """
106    return _call_with_lazy_import("protos", protobuf_path)
107
108
109def services(protobuf_path):  # pylint: disable=unused-argument
110    """Returns a module generated by the indicated .proto file.
111
112    THIS IS AN EXPERIMENTAL API.
113
114    Use this function to retrieve classes and functions corresponding to
115    service definitions in the .proto file, including both stub and servicer
116    definitions.
117
118    To inspect the contents of the returned module, use the dir function.
119    For example:
120
121    ```
122    services = grpc.services("foo.proto")
123    print(dir(services))
124    ```
125
126    The returned module object corresponds to the _pb2_grpc.py file generated
127    by protoc. The path is expected to be relative to an entry on sys.path
128    and all transitive dependencies of the file should also be resolveable
129    from an entry on sys.path.
130
131    To completely disable the machinery behind this function, set the
132    GRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to "true".
133
134    Args:
135      protobuf_path: The path to the .proto file on the filesystem. This path
136        must be resolveable from an entry on sys.path and so must all of its
137        transitive dependencies.
138
139    Returns:
140      A module object corresponding to the stub/service code for the indicated
141      .proto file. Equivalent to a generated _pb2_grpc.py file.
142    """
143    return _call_with_lazy_import("services", protobuf_path)
144
145
146def protos_and_services(protobuf_path):  # pylint: disable=unused-argument
147    """Returns a 2-tuple of modules corresponding to protos and services.
148
149    THIS IS AN EXPERIMENTAL API.
150
151    The return value of this function is equivalent to a call to protos and a
152    call to services.
153
154    To completely disable the machinery behind this function, set the
155    GRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to "true".
156
157    Args:
158      protobuf_path: The path to the .proto file on the filesystem. This path
159        must be resolveable from an entry on sys.path and so must all of its
160        transitive dependencies.
161
162    Returns:
163      A 2-tuple of module objects corresponding to (protos(path), services(path)).
164    """
165    return _call_with_lazy_import("protos_and_services", protobuf_path)
166