implementations.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. # Copyright 2015-2016 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. """Entry points into the Beta API of gRPC Python."""
  15. # threading is referenced from specification in this module.
  16. import threading # pylint: disable=unused-import
  17. # interfaces, cardinality, and face are referenced from specification in this
  18. # module.
  19. import grpc
  20. from grpc import _auth
  21. from grpc.beta import _client_adaptations
  22. from grpc.beta import _metadata
  23. from grpc.beta import _server_adaptations
  24. from grpc.beta import interfaces # pylint: disable=unused-import
  25. from grpc.framework.common import cardinality # pylint: disable=unused-import
  26. from grpc.framework.interfaces.face import face # pylint: disable=unused-import
  27. # pylint: disable=too-many-arguments
  28. ChannelCredentials = grpc.ChannelCredentials
  29. ssl_channel_credentials = grpc.ssl_channel_credentials
  30. CallCredentials = grpc.CallCredentials
  31. def metadata_call_credentials(metadata_plugin, name=None):
  32. def plugin(context, callback):
  33. def wrapped_callback(beta_metadata, error):
  34. callback(_metadata.unbeta(beta_metadata), error)
  35. metadata_plugin(context, wrapped_callback)
  36. return grpc.metadata_call_credentials(plugin, name=name)
  37. def google_call_credentials(credentials):
  38. """Construct CallCredentials from GoogleCredentials.
  39. Args:
  40. credentials: A GoogleCredentials object from the oauth2client library.
  41. Returns:
  42. A CallCredentials object for use in a GRPCCallOptions object.
  43. """
  44. return metadata_call_credentials(_auth.GoogleCallCredentials(credentials))
  45. access_token_call_credentials = grpc.access_token_call_credentials
  46. composite_call_credentials = grpc.composite_call_credentials
  47. composite_channel_credentials = grpc.composite_channel_credentials
  48. class Channel(object):
  49. """A channel to a remote host through which RPCs may be conducted.
  50. Only the "subscribe" and "unsubscribe" methods are supported for application
  51. use. This class' instance constructor and all other attributes are
  52. unsupported.
  53. """
  54. def __init__(self, channel):
  55. self._channel = channel
  56. def subscribe(self, callback, try_to_connect=None):
  57. """Subscribes to this Channel's connectivity.
  58. Args:
  59. callback: A callable to be invoked and passed an
  60. interfaces.ChannelConnectivity identifying this Channel's connectivity.
  61. The callable will be invoked immediately upon subscription and again for
  62. every change to this Channel's connectivity thereafter until it is
  63. unsubscribed.
  64. try_to_connect: A boolean indicating whether or not this Channel should
  65. attempt to connect if it is not already connected and ready to conduct
  66. RPCs.
  67. """
  68. self._channel.subscribe(callback, try_to_connect=try_to_connect)
  69. def unsubscribe(self, callback):
  70. """Unsubscribes a callback from this Channel's connectivity.
  71. Args:
  72. callback: A callable previously registered with this Channel from having
  73. been passed to its "subscribe" method.
  74. """
  75. self._channel.unsubscribe(callback)
  76. def insecure_channel(host, port):
  77. """Creates an insecure Channel to a remote host.
  78. Args:
  79. host: The name of the remote host to which to connect.
  80. port: The port of the remote host to which to connect.
  81. If None only the 'host' part will be used.
  82. Returns:
  83. A Channel to the remote host through which RPCs may be conducted.
  84. """
  85. channel = grpc.insecure_channel(
  86. host if port is None else "%s:%d" % (host, port)
  87. )
  88. return Channel(channel)
  89. def secure_channel(host, port, channel_credentials):
  90. """Creates a secure Channel to a remote host.
  91. Args:
  92. host: The name of the remote host to which to connect.
  93. port: The port of the remote host to which to connect.
  94. If None only the 'host' part will be used.
  95. channel_credentials: A ChannelCredentials.
  96. Returns:
  97. A secure Channel to the remote host through which RPCs may be conducted.
  98. """
  99. channel = grpc.secure_channel(
  100. host if port is None else "%s:%d" % (host, port), channel_credentials
  101. )
  102. return Channel(channel)
  103. class StubOptions(object):
  104. """A value encapsulating the various options for creation of a Stub.
  105. This class and its instances have no supported interface - it exists to define
  106. the type of its instances and its instances exist to be passed to other
  107. functions.
  108. """
  109. def __init__(
  110. self,
  111. host,
  112. request_serializers,
  113. response_deserializers,
  114. metadata_transformer,
  115. thread_pool,
  116. thread_pool_size,
  117. ):
  118. self.host = host
  119. self.request_serializers = request_serializers
  120. self.response_deserializers = response_deserializers
  121. self.metadata_transformer = metadata_transformer
  122. self.thread_pool = thread_pool
  123. self.thread_pool_size = thread_pool_size
  124. _EMPTY_STUB_OPTIONS = StubOptions(None, None, None, None, None, None)
  125. def stub_options(
  126. host=None,
  127. request_serializers=None,
  128. response_deserializers=None,
  129. metadata_transformer=None,
  130. thread_pool=None,
  131. thread_pool_size=None,
  132. ):
  133. """Creates a StubOptions value to be passed at stub creation.
  134. All parameters are optional and should always be passed by keyword.
  135. Args:
  136. host: A host string to set on RPC calls.
  137. request_serializers: A dictionary from service name-method name pair to
  138. request serialization behavior.
  139. response_deserializers: A dictionary from service name-method name pair to
  140. response deserialization behavior.
  141. metadata_transformer: A callable that given a metadata object produces
  142. another metadata object to be used in the underlying communication on the
  143. wire.
  144. thread_pool: A thread pool to use in stubs.
  145. thread_pool_size: The size of thread pool to create for use in stubs;
  146. ignored if thread_pool has been passed.
  147. Returns:
  148. A StubOptions value created from the passed parameters.
  149. """
  150. return StubOptions(
  151. host,
  152. request_serializers,
  153. response_deserializers,
  154. metadata_transformer,
  155. thread_pool,
  156. thread_pool_size,
  157. )
  158. def generic_stub(channel, options=None):
  159. """Creates a face.GenericStub on which RPCs can be made.
  160. Args:
  161. channel: A Channel for use by the created stub.
  162. options: A StubOptions customizing the created stub.
  163. Returns:
  164. A face.GenericStub on which RPCs can be made.
  165. """
  166. effective_options = _EMPTY_STUB_OPTIONS if options is None else options
  167. return _client_adaptations.generic_stub(
  168. channel._channel, # pylint: disable=protected-access
  169. effective_options.host,
  170. effective_options.metadata_transformer,
  171. effective_options.request_serializers,
  172. effective_options.response_deserializers,
  173. )
  174. def dynamic_stub(channel, service, cardinalities, options=None):
  175. """Creates a face.DynamicStub with which RPCs can be invoked.
  176. Args:
  177. channel: A Channel for the returned face.DynamicStub to use.
  178. service: The package-qualified full name of the service.
  179. cardinalities: A dictionary from RPC method name to cardinality.Cardinality
  180. value identifying the cardinality of the RPC method.
  181. options: An optional StubOptions value further customizing the functionality
  182. of the returned face.DynamicStub.
  183. Returns:
  184. A face.DynamicStub with which RPCs can be invoked.
  185. """
  186. effective_options = _EMPTY_STUB_OPTIONS if options is None else options
  187. return _client_adaptations.dynamic_stub(
  188. channel._channel, # pylint: disable=protected-access
  189. service,
  190. cardinalities,
  191. effective_options.host,
  192. effective_options.metadata_transformer,
  193. effective_options.request_serializers,
  194. effective_options.response_deserializers,
  195. )
  196. ServerCredentials = grpc.ServerCredentials
  197. ssl_server_credentials = grpc.ssl_server_credentials
  198. class ServerOptions(object):
  199. """A value encapsulating the various options for creation of a Server.
  200. This class and its instances have no supported interface - it exists to define
  201. the type of its instances and its instances exist to be passed to other
  202. functions.
  203. """
  204. def __init__(
  205. self,
  206. multi_method_implementation,
  207. request_deserializers,
  208. response_serializers,
  209. thread_pool,
  210. thread_pool_size,
  211. default_timeout,
  212. maximum_timeout,
  213. ):
  214. self.multi_method_implementation = multi_method_implementation
  215. self.request_deserializers = request_deserializers
  216. self.response_serializers = response_serializers
  217. self.thread_pool = thread_pool
  218. self.thread_pool_size = thread_pool_size
  219. self.default_timeout = default_timeout
  220. self.maximum_timeout = maximum_timeout
  221. _EMPTY_SERVER_OPTIONS = ServerOptions(None, None, None, None, None, None, None)
  222. def server_options(
  223. multi_method_implementation=None,
  224. request_deserializers=None,
  225. response_serializers=None,
  226. thread_pool=None,
  227. thread_pool_size=None,
  228. default_timeout=None,
  229. maximum_timeout=None,
  230. ):
  231. """Creates a ServerOptions value to be passed at server creation.
  232. All parameters are optional and should always be passed by keyword.
  233. Args:
  234. multi_method_implementation: A face.MultiMethodImplementation to be called
  235. to service an RPC if the server has no specific method implementation for
  236. the name of the RPC for which service was requested.
  237. request_deserializers: A dictionary from service name-method name pair to
  238. request deserialization behavior.
  239. response_serializers: A dictionary from service name-method name pair to
  240. response serialization behavior.
  241. thread_pool: A thread pool to use in stubs.
  242. thread_pool_size: The size of thread pool to create for use in stubs;
  243. ignored if thread_pool has been passed.
  244. default_timeout: A duration in seconds to allow for RPC service when
  245. servicing RPCs that did not include a timeout value when invoked.
  246. maximum_timeout: A duration in seconds to allow for RPC service when
  247. servicing RPCs no matter what timeout value was passed when the RPC was
  248. invoked.
  249. Returns:
  250. A StubOptions value created from the passed parameters.
  251. """
  252. return ServerOptions(
  253. multi_method_implementation,
  254. request_deserializers,
  255. response_serializers,
  256. thread_pool,
  257. thread_pool_size,
  258. default_timeout,
  259. maximum_timeout,
  260. )
  261. def server(service_implementations, options=None):
  262. """Creates an interfaces.Server with which RPCs can be serviced.
  263. Args:
  264. service_implementations: A dictionary from service name-method name pair to
  265. face.MethodImplementation.
  266. options: An optional ServerOptions value further customizing the
  267. functionality of the returned Server.
  268. Returns:
  269. An interfaces.Server with which RPCs can be serviced.
  270. """
  271. effective_options = _EMPTY_SERVER_OPTIONS if options is None else options
  272. return _server_adaptations.server(
  273. service_implementations,
  274. effective_options.multi_method_implementation,
  275. effective_options.request_deserializers,
  276. effective_options.response_serializers,
  277. effective_options.thread_pool,
  278. effective_options.thread_pool_size,
  279. )