service_reflection.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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
  34. protocol).
  35. bases: Base classes of the class being constructed.
  36. dictionary: The class dictionary of the class being constructed.
  37. dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object
  38. describing this protocol service type.
  39. """
  40. # Don't do anything if this class doesn't have a descriptor. This happens
  41. # when a service class is subclassed.
  42. if GeneratedServiceType._DESCRIPTOR_KEY not in dictionary:
  43. return
  44. descriptor = dictionary[GeneratedServiceType._DESCRIPTOR_KEY]
  45. service_builder = _ServiceBuilder(descriptor)
  46. service_builder.BuildService(cls)
  47. cls.DESCRIPTOR = descriptor
  48. class GeneratedServiceStubType(GeneratedServiceType):
  49. """Metaclass for service stubs created at runtime from ServiceDescriptors.
  50. This class has similar responsibilities as GeneratedServiceType, except that
  51. it creates the service stub classes.
  52. """
  53. _DESCRIPTOR_KEY = 'DESCRIPTOR'
  54. def __init__(cls, name, bases, dictionary):
  55. """Creates a message service stub class.
  56. Args:
  57. name: Name of the class (ignored, here).
  58. bases: Base classes of the class being constructed.
  59. dictionary: The class dictionary of the class being constructed.
  60. dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object
  61. describing this protocol service type.
  62. """
  63. super(GeneratedServiceStubType, cls).__init__(name, bases, dictionary)
  64. # Don't do anything if this class doesn't have a descriptor. This happens
  65. # when a service stub is subclassed.
  66. if GeneratedServiceStubType._DESCRIPTOR_KEY not in dictionary:
  67. return
  68. descriptor = dictionary[GeneratedServiceStubType._DESCRIPTOR_KEY]
  69. service_stub_builder = _ServiceStubBuilder(descriptor)
  70. service_stub_builder.BuildServiceStub(cls)
  71. class _ServiceBuilder(object):
  72. """This class constructs a protocol service class using a service descriptor.
  73. Given a service descriptor, this class constructs a class that represents
  74. the specified service descriptor. One service builder instance constructs
  75. exactly one service class. That means all instances of that class share the
  76. same builder.
  77. """
  78. def __init__(self, service_descriptor):
  79. """Initializes an instance of the service class builder.
  80. Args:
  81. service_descriptor: ServiceDescriptor to use when constructing the
  82. service class.
  83. """
  84. self.descriptor = service_descriptor
  85. def BuildService(builder, cls):
  86. """Constructs the service class.
  87. Args:
  88. cls: The class that will be constructed.
  89. """
  90. # CallMethod needs to operate with an instance of the Service class. This
  91. # internal wrapper function exists only to be able to pass the service
  92. # instance to the method that does the real CallMethod work.
  93. # Making sure to use exact argument names from the abstract interface in
  94. # service.py to match the type signature
  95. def _WrapCallMethod(self, method_descriptor, rpc_controller, request, done):
  96. return builder._CallMethod(self, method_descriptor, rpc_controller,
  97. request, done)
  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(self, srvc, method_descriptor,
  111. rpc_controller, request, callback):
  112. """Calls the method described by a given method descriptor.
  113. Args:
  114. srvc: Instance of the service for which this method is called.
  115. method_descriptor: Descriptor that represent the method to call.
  116. rpc_controller: RPC controller to use for this method's execution.
  117. request: Request protocol message.
  118. callback: A callback to invoke after the method has completed.
  119. """
  120. if method_descriptor.containing_service != self.descriptor:
  121. raise RuntimeError(
  122. 'CallMethod() given method descriptor for wrong service type.')
  123. method = getattr(srvc, method_descriptor.name)
  124. return method(rpc_controller, request, callback)
  125. def _GetRequestClass(self, method_descriptor):
  126. """Returns the class of the request protocol message.
  127. Args:
  128. method_descriptor: Descriptor of the method for which to return the
  129. request protocol message class.
  130. Returns:
  131. A class that represents the input protocol message of the specified
  132. method.
  133. """
  134. if method_descriptor.containing_service != self.descriptor:
  135. raise RuntimeError(
  136. 'GetRequestClass() given method descriptor for wrong service type.')
  137. return method_descriptor.input_type._concrete_class
  138. def _GetResponseClass(self, method_descriptor):
  139. """Returns the class of the response protocol message.
  140. Args:
  141. method_descriptor: Descriptor of the method for which to return the
  142. response protocol message class.
  143. Returns:
  144. A class that represents the output protocol message of the specified
  145. method.
  146. """
  147. if method_descriptor.containing_service != self.descriptor:
  148. raise RuntimeError(
  149. 'GetResponseClass() given method descriptor for wrong service type.')
  150. return method_descriptor.output_type._concrete_class
  151. def _GenerateNonImplementedMethod(self, method):
  152. """Generates and returns a method that can be set for a service methods.
  153. Args:
  154. method: Descriptor of the service method for which a method is to be
  155. generated.
  156. Returns:
  157. A method that can be added to the service class.
  158. """
  159. return lambda inst, rpc_controller, request, callback: (
  160. self._NonImplementedMethod(method.name, rpc_controller, callback))
  161. def _NonImplementedMethod(self, method_name, rpc_controller, callback):
  162. """The body of all methods in the generated service class.
  163. Args:
  164. method_name: Name of the method being executed.
  165. rpc_controller: RPC controller used to execute this method.
  166. callback: A callback which will be invoked when the method finishes.
  167. """
  168. rpc_controller.SetFailed('Method %s not implemented.' % method_name)
  169. callback(None)
  170. class _ServiceStubBuilder(object):
  171. """Constructs a protocol service stub class using a service descriptor.
  172. Given a service descriptor, this class constructs a suitable stub class.
  173. A stub is just a type-safe wrapper around an RpcChannel which emulates a
  174. local implementation of the service.
  175. One service stub builder instance constructs exactly one class. It means all
  176. instances of that class share the same service stub builder.
  177. """
  178. def __init__(self, service_descriptor):
  179. """Initializes an instance of the service stub class builder.
  180. Args:
  181. service_descriptor: ServiceDescriptor to use when constructing the
  182. stub class.
  183. """
  184. self.descriptor = service_descriptor
  185. def BuildServiceStub(self, cls):
  186. """Constructs the stub class.
  187. Args:
  188. cls: The class that will be constructed.
  189. """
  190. def _ServiceStubInit(stub, rpc_channel):
  191. stub.rpc_channel = rpc_channel
  192. self.cls = cls
  193. cls.__init__ = _ServiceStubInit
  194. for method in self.descriptor.methods:
  195. setattr(cls, method.name, self._GenerateStubMethod(method))
  196. def _GenerateStubMethod(self, method):
  197. return (lambda inst, rpc_controller, request, callback=None:
  198. self._StubMethod(inst, method, rpc_controller, request, callback))
  199. def _StubMethod(self, stub, method_descriptor,
  200. rpc_controller, request, callback):
  201. """The body of all service methods in the generated stub class.
  202. Args:
  203. stub: Stub instance.
  204. method_descriptor: Descriptor of the invoked method.
  205. rpc_controller: Rpc controller to execute the method.
  206. request: Request protocol message.
  207. callback: A callback to execute when the method finishes.
  208. Returns:
  209. Response message (in case of blocking call).
  210. """
  211. return stub.rpc_channel.CallMethod(
  212. method_descriptor, rpc_controller, request,
  213. method_descriptor.output_type._concrete_class, callback)