1# Protocol Buffers - Google's data interchange format
2# Copyright 2008 Google Inc.  All rights reserved.
3# https://developers.google.com/protocol-buffers/
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met:
8#
9#     * Redistributions of source code must retain the above copyright
10# notice, this list of conditions and the following disclaimer.
11#     * Redistributions in binary form must reproduce the above
12# copyright notice, this list of conditions and the following disclaimer
13# in the documentation and/or other materials provided with the
14# distribution.
15#     * Neither the name of Google Inc. nor the names of its
16# contributors may be used to endorse or promote products derived from
17# this software without specific prior written permission.
18#
19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31"""Contains metaclasses used to create protocol service and service stub
32classes from ServiceDescriptor objects at runtime.
33
34The GeneratedServiceType and GeneratedServiceStubType metaclasses are used to
35inject all useful functionality into the classes output by the protocol
36compiler at compile-time.
37"""
38
39__author__ = 'petar@google.com (Petar Petrov)'
40
41
42class GeneratedServiceType(type):
43
44  """Metaclass for service classes created at runtime from ServiceDescriptors.
45
46  Implementations for all methods described in the Service class are added here
47  by this class. We also create properties to allow getting/setting all fields
48  in the protocol message.
49
50  The protocol compiler currently uses this metaclass to create protocol service
51  classes at runtime. Clients can also manually create their own classes at
52  runtime, as in this example::
53
54    mydescriptor = ServiceDescriptor(.....)
55    class MyProtoService(service.Service):
56      __metaclass__ = GeneratedServiceType
57      DESCRIPTOR = mydescriptor
58    myservice_instance = MyProtoService()
59    # ...
60  """
61
62  _DESCRIPTOR_KEY = 'DESCRIPTOR'
63
64  def __init__(cls, name, bases, dictionary):
65    """Creates a message service class.
66
67    Args:
68      name: Name of the class (ignored, but required by the metaclass
69        protocol).
70      bases: Base classes of the class being constructed.
71      dictionary: The class dictionary of the class being constructed.
72        dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object
73        describing this protocol service type.
74    """
75    # Don't do anything if this class doesn't have a descriptor. This happens
76    # when a service class is subclassed.
77    if GeneratedServiceType._DESCRIPTOR_KEY not in dictionary:
78      return
79
80    descriptor = dictionary[GeneratedServiceType._DESCRIPTOR_KEY]
81    service_builder = _ServiceBuilder(descriptor)
82    service_builder.BuildService(cls)
83    cls.DESCRIPTOR = descriptor
84
85
86class GeneratedServiceStubType(GeneratedServiceType):
87
88  """Metaclass for service stubs created at runtime from ServiceDescriptors.
89
90  This class has similar responsibilities as GeneratedServiceType, except that
91  it creates the service stub classes.
92  """
93
94  _DESCRIPTOR_KEY = 'DESCRIPTOR'
95
96  def __init__(cls, name, bases, dictionary):
97    """Creates a message service stub class.
98
99    Args:
100      name: Name of the class (ignored, here).
101      bases: Base classes of the class being constructed.
102      dictionary: The class dictionary of the class being constructed.
103        dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object
104        describing this protocol service type.
105    """
106    super(GeneratedServiceStubType, cls).__init__(name, bases, dictionary)
107    # Don't do anything if this class doesn't have a descriptor. This happens
108    # when a service stub is subclassed.
109    if GeneratedServiceStubType._DESCRIPTOR_KEY not in dictionary:
110      return
111
112    descriptor = dictionary[GeneratedServiceStubType._DESCRIPTOR_KEY]
113    service_stub_builder = _ServiceStubBuilder(descriptor)
114    service_stub_builder.BuildServiceStub(cls)
115
116
117class _ServiceBuilder(object):
118
119  """This class constructs a protocol service class using a service descriptor.
120
121  Given a service descriptor, this class constructs a class that represents
122  the specified service descriptor. One service builder instance constructs
123  exactly one service class. That means all instances of that class share the
124  same builder.
125  """
126
127  def __init__(self, service_descriptor):
128    """Initializes an instance of the service class builder.
129
130    Args:
131      service_descriptor: ServiceDescriptor to use when constructing the
132        service class.
133    """
134    self.descriptor = service_descriptor
135
136  def BuildService(self, cls):
137    """Constructs the service class.
138
139    Args:
140      cls: The class that will be constructed.
141    """
142
143    # CallMethod needs to operate with an instance of the Service class. This
144    # internal wrapper function exists only to be able to pass the service
145    # instance to the method that does the real CallMethod work.
146    def _WrapCallMethod(srvc, method_descriptor,
147                        rpc_controller, request, callback):
148      return self._CallMethod(srvc, method_descriptor,
149                       rpc_controller, request, callback)
150    self.cls = cls
151    cls.CallMethod = _WrapCallMethod
152    cls.GetDescriptor = staticmethod(lambda: self.descriptor)
153    cls.GetDescriptor.__doc__ = "Returns the service descriptor."
154    cls.GetRequestClass = self._GetRequestClass
155    cls.GetResponseClass = self._GetResponseClass
156    for method in self.descriptor.methods:
157      setattr(cls, method.name, self._GenerateNonImplementedMethod(method))
158
159  def _CallMethod(self, srvc, method_descriptor,
160                  rpc_controller, request, callback):
161    """Calls the method described by a given method descriptor.
162
163    Args:
164      srvc: Instance of the service for which this method is called.
165      method_descriptor: Descriptor that represent the method to call.
166      rpc_controller: RPC controller to use for this method's execution.
167      request: Request protocol message.
168      callback: A callback to invoke after the method has completed.
169    """
170    if method_descriptor.containing_service != self.descriptor:
171      raise RuntimeError(
172          'CallMethod() given method descriptor for wrong service type.')
173    method = getattr(srvc, method_descriptor.name)
174    return method(rpc_controller, request, callback)
175
176  def _GetRequestClass(self, method_descriptor):
177    """Returns the class of the request protocol message.
178
179    Args:
180      method_descriptor: Descriptor of the method for which to return the
181        request protocol message class.
182
183    Returns:
184      A class that represents the input protocol message of the specified
185      method.
186    """
187    if method_descriptor.containing_service != self.descriptor:
188      raise RuntimeError(
189          'GetRequestClass() given method descriptor for wrong service type.')
190    return method_descriptor.input_type._concrete_class
191
192  def _GetResponseClass(self, method_descriptor):
193    """Returns the class of the response protocol message.
194
195    Args:
196      method_descriptor: Descriptor of the method for which to return the
197        response protocol message class.
198
199    Returns:
200      A class that represents the output protocol message of the specified
201      method.
202    """
203    if method_descriptor.containing_service != self.descriptor:
204      raise RuntimeError(
205          'GetResponseClass() given method descriptor for wrong service type.')
206    return method_descriptor.output_type._concrete_class
207
208  def _GenerateNonImplementedMethod(self, method):
209    """Generates and returns a method that can be set for a service methods.
210
211    Args:
212      method: Descriptor of the service method for which a method is to be
213        generated.
214
215    Returns:
216      A method that can be added to the service class.
217    """
218    return lambda inst, rpc_controller, request, callback: (
219        self._NonImplementedMethod(method.name, rpc_controller, callback))
220
221  def _NonImplementedMethod(self, method_name, rpc_controller, callback):
222    """The body of all methods in the generated service class.
223
224    Args:
225      method_name: Name of the method being executed.
226      rpc_controller: RPC controller used to execute this method.
227      callback: A callback which will be invoked when the method finishes.
228    """
229    rpc_controller.SetFailed('Method %s not implemented.' % method_name)
230    callback(None)
231
232
233class _ServiceStubBuilder(object):
234
235  """Constructs a protocol service stub class using a service descriptor.
236
237  Given a service descriptor, this class constructs a suitable stub class.
238  A stub is just a type-safe wrapper around an RpcChannel which emulates a
239  local implementation of the service.
240
241  One service stub builder instance constructs exactly one class. It means all
242  instances of that class share the same service stub builder.
243  """
244
245  def __init__(self, service_descriptor):
246    """Initializes an instance of the service stub class builder.
247
248    Args:
249      service_descriptor: ServiceDescriptor to use when constructing the
250        stub class.
251    """
252    self.descriptor = service_descriptor
253
254  def BuildServiceStub(self, cls):
255    """Constructs the stub class.
256
257    Args:
258      cls: The class that will be constructed.
259    """
260
261    def _ServiceStubInit(stub, rpc_channel):
262      stub.rpc_channel = rpc_channel
263    self.cls = cls
264    cls.__init__ = _ServiceStubInit
265    for method in self.descriptor.methods:
266      setattr(cls, method.name, self._GenerateStubMethod(method))
267
268  def _GenerateStubMethod(self, method):
269    return (lambda inst, rpc_controller, request, callback=None:
270        self._StubMethod(inst, method, rpc_controller, request, callback))
271
272  def _StubMethod(self, stub, method_descriptor,
273                  rpc_controller, request, callback):
274    """The body of all service methods in the generated stub class.
275
276    Args:
277      stub: Stub instance.
278      method_descriptor: Descriptor of the invoked method.
279      rpc_controller: Rpc controller to execute the method.
280      request: Request protocol message.
281      callback: A callback to execute when the method finishes.
282    Returns:
283      Response message (in case of blocking call).
284    """
285    return stub.rpc_channel.CallMethod(
286        method_descriptor, rpc_controller, request,
287        method_descriptor.output_type._concrete_class, callback)
288