service_reflection.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. #
  4. # Use of this source code is governed by a BSD-style
  5. # license that can be found in the LICENSE file or at
  6. # https://developers.google.com/open-source/licenses/bsd
  7. """Contains metaclasses used to create protocol service and service stub
  8. classes from ServiceDescriptor objects at runtime.
  9. The GeneratedServiceType and GeneratedServiceStubType metaclasses are used to
  10. inject all useful functionality into the classes output by the protocol
  11. compiler at compile-time.
  12. """
  13. __author__ = 'petar@google.com (Petar Petrov)'
  14. class GeneratedServiceType(type):
  15. """Metaclass for service classes created at runtime from ServiceDescriptors.
  16. Implementations for all methods described in the Service class are added here
  17. by this class. We also create properties to allow getting/setting all fields
  18. in the protocol message.
  19. The protocol compiler currently uses this metaclass to create protocol service
  20. classes at runtime. Clients can also manually create their own classes at
  21. runtime, as in this example::
  22. mydescriptor = ServiceDescriptor(.....)
  23. class MyProtoService(service.Service):
  24. __metaclass__ = GeneratedServiceType
  25. DESCRIPTOR = mydescriptor
  26. myservice_instance = MyProtoService()
  27. # ...
  28. """
  29. _DESCRIPTOR_KEY = 'DESCRIPTOR'
  30. def __init__(cls, name, bases, dictionary):
  31. """Creates a message service class.
  32. Args:
  33. name: Name of the class (ignored, but required by the metaclass protocol).
  34. bases: Base classes of the class being constructed.
  35. dictionary: The class dictionary of the class being constructed.
  36. dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object
  37. describing this protocol service type.
  38. """
  39. # Don't do anything if this class doesn't have a descriptor. This happens
  40. # when a service class is subclassed.
  41. if GeneratedServiceType._DESCRIPTOR_KEY not in dictionary:
  42. return
  43. descriptor = dictionary[GeneratedServiceType._DESCRIPTOR_KEY]
  44. service_builder = _ServiceBuilder(descriptor)
  45. service_builder.BuildService(cls)
  46. cls.DESCRIPTOR = descriptor
  47. class GeneratedServiceStubType(GeneratedServiceType):
  48. """Metaclass for service stubs created at runtime from ServiceDescriptors.
  49. This class has similar responsibilities as GeneratedServiceType, except that
  50. it creates the service stub classes.
  51. """
  52. _DESCRIPTOR_KEY = 'DESCRIPTOR'
  53. def __init__(cls, name, bases, dictionary):
  54. """Creates a message service stub class.
  55. Args:
  56. name: Name of the class (ignored, here).
  57. bases: Base classes of the class being constructed.
  58. dictionary: The class dictionary of the class being constructed.
  59. dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object
  60. describing this protocol service type.
  61. """
  62. super(GeneratedServiceStubType, cls).__init__(name, bases, dictionary)
  63. # Don't do anything if this class doesn't have a descriptor. This happens
  64. # when a service stub is subclassed.
  65. if GeneratedServiceStubType._DESCRIPTOR_KEY not in dictionary:
  66. return
  67. descriptor = dictionary[GeneratedServiceStubType._DESCRIPTOR_KEY]
  68. service_stub_builder = _ServiceStubBuilder(descriptor)
  69. service_stub_builder.BuildServiceStub(cls)
  70. class _ServiceBuilder(object):
  71. """This class constructs a protocol service class using a service descriptor.
  72. Given a service descriptor, this class constructs a class that represents
  73. the specified service descriptor. One service builder instance constructs
  74. exactly one service class. That means all instances of that class share the
  75. same builder.
  76. """
  77. def __init__(self, service_descriptor):
  78. """Initializes an instance of the service class builder.
  79. Args:
  80. service_descriptor: ServiceDescriptor to use when constructing the service
  81. class.
  82. """
  83. self.descriptor = service_descriptor
  84. def BuildService(builder, cls):
  85. """Constructs the service class.
  86. Args:
  87. cls: The class that will be constructed.
  88. """
  89. # CallMethod needs to operate with an instance of the Service class. This
  90. # internal wrapper function exists only to be able to pass the service
  91. # instance to the method that does the real CallMethod work.
  92. # Making sure to use exact argument names from the abstract interface in
  93. # service.py to match the type signature
  94. def _WrapCallMethod(self, method_descriptor, rpc_controller, request, done):
  95. return builder._CallMethod(
  96. self, method_descriptor, rpc_controller, request, done
  97. )
  98. def _WrapGetRequestClass(self, method_descriptor):
  99. return builder._GetRequestClass(method_descriptor)
  100. def _WrapGetResponseClass(self, method_descriptor):
  101. return builder._GetResponseClass(method_descriptor)
  102. builder.cls = cls
  103. cls.CallMethod = _WrapCallMethod
  104. cls.GetDescriptor = staticmethod(lambda: builder.descriptor)
  105. cls.GetDescriptor.__doc__ = 'Returns the service descriptor.'
  106. cls.GetRequestClass = _WrapGetRequestClass
  107. cls.GetResponseClass = _WrapGetResponseClass
  108. for method in builder.descriptor.methods:
  109. setattr(cls, method.name, builder._GenerateNonImplementedMethod(method))
  110. def _CallMethod(
  111. self, srvc, method_descriptor, rpc_controller, request, callback
  112. ):
  113. """Calls the method described by a given method descriptor.
  114. Args:
  115. srvc: Instance of the service for which this method is called.
  116. method_descriptor: Descriptor that represent the method to call.
  117. rpc_controller: RPC controller to use for this method's execution.
  118. request: Request protocol message.
  119. callback: A callback to invoke after the method has completed.
  120. """
  121. if method_descriptor.containing_service != self.descriptor:
  122. raise RuntimeError(
  123. 'CallMethod() given method descriptor for wrong service type.'
  124. )
  125. method = getattr(srvc, method_descriptor.name)
  126. return method(rpc_controller, request, callback)
  127. def _GetRequestClass(self, method_descriptor):
  128. """Returns the class of the request protocol message.
  129. Args:
  130. method_descriptor: Descriptor of the method for which to return the
  131. request protocol message class.
  132. Returns:
  133. A class that represents the input protocol message of the specified
  134. method.
  135. """
  136. if method_descriptor.containing_service != self.descriptor:
  137. raise RuntimeError(
  138. 'GetRequestClass() given method descriptor for wrong service type.'
  139. )
  140. return method_descriptor.input_type._concrete_class
  141. def _GetResponseClass(self, method_descriptor):
  142. """Returns the class of the response protocol message.
  143. Args:
  144. method_descriptor: Descriptor of the method for which to return the
  145. response protocol message class.
  146. Returns:
  147. A class that represents the output protocol message of the specified
  148. method.
  149. """
  150. if method_descriptor.containing_service != self.descriptor:
  151. raise RuntimeError(
  152. 'GetResponseClass() given method descriptor for wrong service type.'
  153. )
  154. return method_descriptor.output_type._concrete_class
  155. def _GenerateNonImplementedMethod(self, method):
  156. """Generates and returns a method that can be set for a service methods.
  157. Args:
  158. method: Descriptor of the service method for which a method is to be
  159. generated.
  160. Returns:
  161. A method that can be added to the service class.
  162. """
  163. return lambda inst, rpc_controller, request, callback: (
  164. self._NonImplementedMethod(method.name, rpc_controller, callback)
  165. )
  166. def _NonImplementedMethod(self, method_name, rpc_controller, callback):
  167. """The body of all methods in the generated service class.
  168. Args:
  169. method_name: Name of the method being executed.
  170. rpc_controller: RPC controller used to execute this method.
  171. callback: A callback which will be invoked when the method finishes.
  172. """
  173. rpc_controller.SetFailed('Method %s not implemented.' % method_name)
  174. callback(None)
  175. class _ServiceStubBuilder(object):
  176. """Constructs a protocol service stub class using a service descriptor.
  177. Given a service descriptor, this class constructs a suitable stub class.
  178. A stub is just a type-safe wrapper around an RpcChannel which emulates a
  179. local implementation of the service.
  180. One service stub builder instance constructs exactly one class. It means all
  181. instances of that class share the same service stub builder.
  182. """
  183. def __init__(self, service_descriptor):
  184. """Initializes an instance of the service stub class builder.
  185. Args:
  186. service_descriptor: ServiceDescriptor to use when constructing the stub
  187. class.
  188. """
  189. self.descriptor = service_descriptor
  190. def BuildServiceStub(self, cls):
  191. """Constructs the stub class.
  192. Args:
  193. cls: The class that will be constructed.
  194. """
  195. def _ServiceStubInit(stub, rpc_channel):
  196. stub.rpc_channel = rpc_channel
  197. self.cls = cls
  198. cls.__init__ = _ServiceStubInit
  199. for method in self.descriptor.methods:
  200. setattr(cls, method.name, self._GenerateStubMethod(method))
  201. def _GenerateStubMethod(self, method):
  202. return (
  203. lambda inst, rpc_controller, request, callback=None: self._StubMethod(
  204. inst, method, rpc_controller, request, callback
  205. )
  206. )
  207. def _StubMethod(
  208. self, stub, method_descriptor, rpc_controller, request, callback
  209. ):
  210. """The body of all service methods in the generated stub class.
  211. Args:
  212. stub: Stub instance.
  213. method_descriptor: Descriptor of the invoked method.
  214. rpc_controller: Rpc controller to execute the method.
  215. request: Request protocol message.
  216. callback: A callback to execute when the method finishes.
  217. Returns:
  218. Response message (in case of blocking call).
  219. """
  220. return stub.rpc_channel.CallMethod(
  221. method_descriptor,
  222. rpc_controller,
  223. request,
  224. method_descriptor.output_type._concrete_class,
  225. callback,
  226. )