base.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. # Copyright 2015 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. """The base interface of RPC Framework.
  15. Implementations of this interface support the conduct of "operations":
  16. exchanges between two distinct ends of an arbitrary number of data payloads
  17. and metadata such as a name for the operation, initial and terminal metadata
  18. in each direction, and flow control. These operations may be used for transfers
  19. of data, remote procedure calls, status indication, or anything else
  20. applications choose.
  21. """
  22. # threading is referenced from specification in this module.
  23. import abc
  24. import enum
  25. import threading # pylint: disable=unused-import
  26. import six
  27. # pylint: disable=too-many-arguments
  28. class NoSuchMethodError(Exception):
  29. """Indicates that an unrecognized operation has been called.
  30. Attributes:
  31. code: A code value to communicate to the other side of the operation
  32. along with indication of operation termination. May be None.
  33. details: A details value to communicate to the other side of the
  34. operation along with indication of operation termination. May be None.
  35. """
  36. def __init__(self, code, details):
  37. """Constructor.
  38. Args:
  39. code: A code value to communicate to the other side of the operation
  40. along with indication of operation termination. May be None.
  41. details: A details value to communicate to the other side of the
  42. operation along with indication of operation termination. May be None.
  43. """
  44. super(NoSuchMethodError, self).__init__()
  45. self.code = code
  46. self.details = details
  47. class Outcome(object):
  48. """The outcome of an operation.
  49. Attributes:
  50. kind: A Kind value coarsely identifying how the operation terminated.
  51. code: An application-specific code value or None if no such value was
  52. provided.
  53. details: An application-specific details value or None if no such value was
  54. provided.
  55. """
  56. @enum.unique
  57. class Kind(enum.Enum):
  58. """Ways in which an operation can terminate."""
  59. COMPLETED = 'completed'
  60. CANCELLED = 'cancelled'
  61. EXPIRED = 'expired'
  62. LOCAL_SHUTDOWN = 'local shutdown'
  63. REMOTE_SHUTDOWN = 'remote shutdown'
  64. RECEPTION_FAILURE = 'reception failure'
  65. TRANSMISSION_FAILURE = 'transmission failure'
  66. LOCAL_FAILURE = 'local failure'
  67. REMOTE_FAILURE = 'remote failure'
  68. class Completion(six.with_metaclass(abc.ABCMeta)):
  69. """An aggregate of the values exchanged upon operation completion.
  70. Attributes:
  71. terminal_metadata: A terminal metadata value for the operaton.
  72. code: A code value for the operation.
  73. message: A message value for the operation.
  74. """
  75. class OperationContext(six.with_metaclass(abc.ABCMeta)):
  76. """Provides operation-related information and action."""
  77. @abc.abstractmethod
  78. def outcome(self):
  79. """Indicates the operation's outcome (or that the operation is ongoing).
  80. Returns:
  81. None if the operation is still active or the Outcome value for the
  82. operation if it has terminated.
  83. """
  84. raise NotImplementedError()
  85. @abc.abstractmethod
  86. def add_termination_callback(self, callback):
  87. """Adds a function to be called upon operation termination.
  88. Args:
  89. callback: A callable to be passed an Outcome value on operation
  90. termination.
  91. Returns:
  92. None if the operation has not yet terminated and the passed callback will
  93. later be called when it does terminate, or if the operation has already
  94. terminated an Outcome value describing the operation termination and the
  95. passed callback will not be called as a result of this method call.
  96. """
  97. raise NotImplementedError()
  98. @abc.abstractmethod
  99. def time_remaining(self):
  100. """Describes the length of allowed time remaining for the operation.
  101. Returns:
  102. A nonnegative float indicating the length of allowed time in seconds
  103. remaining for the operation to complete before it is considered to have
  104. timed out. Zero is returned if the operation has terminated.
  105. """
  106. raise NotImplementedError()
  107. @abc.abstractmethod
  108. def cancel(self):
  109. """Cancels the operation if the operation has not yet terminated."""
  110. raise NotImplementedError()
  111. @abc.abstractmethod
  112. def fail(self, exception):
  113. """Indicates that the operation has failed.
  114. Args:
  115. exception: An exception germane to the operation failure. May be None.
  116. """
  117. raise NotImplementedError()
  118. class Operator(six.with_metaclass(abc.ABCMeta)):
  119. """An interface through which to participate in an operation."""
  120. @abc.abstractmethod
  121. def advance(self,
  122. initial_metadata=None,
  123. payload=None,
  124. completion=None,
  125. allowance=None):
  126. """Progresses the operation.
  127. Args:
  128. initial_metadata: An initial metadata value. Only one may ever be
  129. communicated in each direction for an operation, and they must be
  130. communicated no later than either the first payload or the completion.
  131. payload: A payload value.
  132. completion: A Completion value. May only ever be non-None once in either
  133. direction, and no payloads may be passed after it has been communicated.
  134. allowance: A positive integer communicating the number of additional
  135. payloads allowed to be passed by the remote side of the operation.
  136. """
  137. raise NotImplementedError()
  138. class ProtocolReceiver(six.with_metaclass(abc.ABCMeta)):
  139. """A means of receiving protocol values during an operation."""
  140. @abc.abstractmethod
  141. def context(self, protocol_context):
  142. """Accepts the protocol context object for the operation.
  143. Args:
  144. protocol_context: The protocol context object for the operation.
  145. """
  146. raise NotImplementedError()
  147. class Subscription(six.with_metaclass(abc.ABCMeta)):
  148. """Describes customer code's interest in values from the other side.
  149. Attributes:
  150. kind: A Kind value describing the overall kind of this value.
  151. termination_callback: A callable to be passed the Outcome associated with
  152. the operation after it has terminated. Must be non-None if kind is
  153. Kind.TERMINATION_ONLY. Must be None otherwise.
  154. allowance: A callable behavior that accepts positive integers representing
  155. the number of additional payloads allowed to be passed to the other side
  156. of the operation. Must be None if kind is Kind.FULL. Must not be None
  157. otherwise.
  158. operator: An Operator to be passed values from the other side of the
  159. operation. Must be non-None if kind is Kind.FULL. Must be None otherwise.
  160. protocol_receiver: A ProtocolReceiver to be passed protocol objects as they
  161. become available during the operation. Must be non-None if kind is
  162. Kind.FULL.
  163. """
  164. @enum.unique
  165. class Kind(enum.Enum):
  166. NONE = 'none'
  167. TERMINATION_ONLY = 'termination only'
  168. FULL = 'full'
  169. class Servicer(six.with_metaclass(abc.ABCMeta)):
  170. """Interface for service implementations."""
  171. @abc.abstractmethod
  172. def service(self, group, method, context, output_operator):
  173. """Services an operation.
  174. Args:
  175. group: The group identifier of the operation to be serviced.
  176. method: The method identifier of the operation to be serviced.
  177. context: An OperationContext object affording contextual information and
  178. actions.
  179. output_operator: An Operator that will accept output values of the
  180. operation.
  181. Returns:
  182. A Subscription via which this object may or may not accept more values of
  183. the operation.
  184. Raises:
  185. NoSuchMethodError: If this Servicer does not handle operations with the
  186. given group and method.
  187. abandonment.Abandoned: If the operation has been aborted and there no
  188. longer is any reason to service the operation.
  189. """
  190. raise NotImplementedError()
  191. class End(six.with_metaclass(abc.ABCMeta)):
  192. """Common type for entry-point objects on both sides of an operation."""
  193. @abc.abstractmethod
  194. def start(self):
  195. """Starts this object's service of operations."""
  196. raise NotImplementedError()
  197. @abc.abstractmethod
  198. def stop(self, grace):
  199. """Stops this object's service of operations.
  200. This object will refuse service of new operations as soon as this method is
  201. called but operations under way at the time of the call may be given a
  202. grace period during which they are allowed to finish.
  203. Args:
  204. grace: A duration of time in seconds to allow ongoing operations to
  205. terminate before being forcefully terminated by the stopping of this
  206. End. May be zero to terminate all ongoing operations and immediately
  207. stop.
  208. Returns:
  209. A threading.Event that will be set to indicate all operations having
  210. terminated and this End having completely stopped. The returned event
  211. may not be set until after the full grace period (if some ongoing
  212. operation continues for the full length of the period) or it may be set
  213. much sooner (if for example this End had no operations in progress at
  214. the time its stop method was called).
  215. """
  216. raise NotImplementedError()
  217. @abc.abstractmethod
  218. def operate(self,
  219. group,
  220. method,
  221. subscription,
  222. timeout,
  223. initial_metadata=None,
  224. payload=None,
  225. completion=None,
  226. protocol_options=None):
  227. """Commences an operation.
  228. Args:
  229. group: The group identifier of the invoked operation.
  230. method: The method identifier of the invoked operation.
  231. subscription: A Subscription to which the results of the operation will be
  232. passed.
  233. timeout: A length of time in seconds to allow for the operation.
  234. initial_metadata: An initial metadata value to be sent to the other side
  235. of the operation. May be None if the initial metadata will be later
  236. passed via the returned operator or if there will be no initial metadata
  237. passed at all.
  238. payload: An initial payload for the operation.
  239. completion: A Completion value indicating the end of transmission to the
  240. other side of the operation.
  241. protocol_options: A value specified by the provider of a Base interface
  242. implementation affording custom state and behavior.
  243. Returns:
  244. A pair of objects affording information about the operation and action
  245. continuing the operation. The first element of the returned pair is an
  246. OperationContext for the operation and the second element of the
  247. returned pair is an Operator to which operation values not passed in
  248. this call should later be passed.
  249. """
  250. raise NotImplementedError()
  251. @abc.abstractmethod
  252. def operation_stats(self):
  253. """Reports the number of terminated operations broken down by outcome.
  254. Returns:
  255. A dictionary from Outcome.Kind value to an integer identifying the number
  256. of operations that terminated with that outcome kind.
  257. """
  258. raise NotImplementedError()
  259. @abc.abstractmethod
  260. def add_idle_action(self, action):
  261. """Adds an action to be called when this End has no ongoing operations.
  262. Args:
  263. action: A callable that accepts no arguments.
  264. """
  265. raise NotImplementedError()