__init__.py 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174
  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. """gRPC's Python API."""
  15. import abc
  16. import contextlib
  17. import enum
  18. import logging
  19. import sys
  20. from grpc import _compression
  21. from grpc._cython import cygrpc as _cygrpc
  22. from grpc._runtime_protos import protos
  23. from grpc._runtime_protos import protos_and_services
  24. from grpc._runtime_protos import services
  25. logging.getLogger(__name__).addHandler(logging.NullHandler())
  26. try:
  27. # pylint: disable=ungrouped-imports
  28. from grpc._grpcio_metadata import __version__
  29. except ImportError:
  30. __version__ = "dev0"
  31. ############################## Future Interface ###############################
  32. class FutureTimeoutError(Exception):
  33. """Indicates that a method call on a Future timed out."""
  34. class FutureCancelledError(Exception):
  35. """Indicates that the computation underlying a Future was cancelled."""
  36. class Future(abc.ABC):
  37. """A representation of a computation in another control flow.
  38. Computations represented by a Future may be yet to be begun,
  39. may be ongoing, or may have already completed.
  40. """
  41. @abc.abstractmethod
  42. def cancel(self):
  43. """Attempts to cancel the computation.
  44. This method does not block.
  45. Returns:
  46. bool:
  47. Returns True if the computation was canceled.
  48. Returns False under all other circumstances, for example:
  49. 1. computation has begun and could not be canceled.
  50. 2. computation has finished
  51. 3. computation is scheduled for execution and it is impossible
  52. to determine its state without blocking.
  53. """
  54. raise NotImplementedError()
  55. @abc.abstractmethod
  56. def cancelled(self):
  57. """Describes whether the computation was cancelled.
  58. This method does not block.
  59. Returns:
  60. bool:
  61. Returns True if the computation was cancelled before its result became
  62. available.
  63. Returns False under all other circumstances, for example:
  64. 1. computation was not cancelled.
  65. 2. computation's result is available.
  66. """
  67. raise NotImplementedError()
  68. @abc.abstractmethod
  69. def running(self):
  70. """Describes whether the computation is taking place.
  71. This method does not block.
  72. Returns:
  73. Returns True if the computation is scheduled for execution or
  74. currently executing.
  75. Returns False if the computation already executed or was cancelled.
  76. """
  77. raise NotImplementedError()
  78. @abc.abstractmethod
  79. def done(self):
  80. """Describes whether the computation has taken place.
  81. This method does not block.
  82. Returns:
  83. bool:
  84. Returns True if the computation already executed or was cancelled.
  85. Returns False if the computation is scheduled for execution or
  86. currently executing.
  87. This is exactly opposite of the running() method's result.
  88. """
  89. raise NotImplementedError()
  90. @abc.abstractmethod
  91. def result(self, timeout=None):
  92. """Returns the result of the computation or raises its exception.
  93. This method may return immediately or may block.
  94. Args:
  95. timeout: The length of time in seconds to wait for the computation to
  96. finish or be cancelled. If None, the call will block until the
  97. computations's termination.
  98. Returns:
  99. The return value of the computation.
  100. Raises:
  101. FutureTimeoutError: If a timeout value is passed and the computation
  102. does not terminate within the allotted time.
  103. FutureCancelledError: If the computation was cancelled.
  104. Exception: If the computation raised an exception, this call will
  105. raise the same exception.
  106. """
  107. raise NotImplementedError()
  108. @abc.abstractmethod
  109. def exception(self, timeout=None):
  110. """Return the exception raised by the computation.
  111. This method may return immediately or may block.
  112. Args:
  113. timeout: The length of time in seconds to wait for the computation to
  114. terminate or be cancelled. If None, the call will block until the
  115. computations's termination.
  116. Returns:
  117. The exception raised by the computation, or None if the computation
  118. did not raise an exception.
  119. Raises:
  120. FutureTimeoutError: If a timeout value is passed and the computation
  121. does not terminate within the allotted time.
  122. FutureCancelledError: If the computation was cancelled.
  123. """
  124. raise NotImplementedError()
  125. @abc.abstractmethod
  126. def traceback(self, timeout=None):
  127. """Access the traceback of the exception raised by the computation.
  128. This method may return immediately or may block.
  129. Args:
  130. timeout: The length of time in seconds to wait for the computation
  131. to terminate or be cancelled. If None, the call will block until
  132. the computation's termination.
  133. Returns:
  134. The traceback of the exception raised by the computation, or None
  135. if the computation did not raise an exception.
  136. Raises:
  137. FutureTimeoutError: If a timeout value is passed and the computation
  138. does not terminate within the allotted time.
  139. FutureCancelledError: If the computation was cancelled.
  140. """
  141. raise NotImplementedError()
  142. @abc.abstractmethod
  143. def add_done_callback(self, fn):
  144. """Adds a function to be called at completion of the computation.
  145. The callback will be passed this Future object describing the outcome
  146. of the computation. Callbacks will be invoked after the future is
  147. terminated, whether successfully or not.
  148. If the computation has already completed, the callback will be called
  149. immediately.
  150. Exceptions raised in the callback will be logged at ERROR level, but
  151. will not terminate any threads of execution.
  152. Args:
  153. fn: A callable taking this Future object as its single parameter.
  154. """
  155. raise NotImplementedError()
  156. ################################ gRPC Enums ##################################
  157. @enum.unique
  158. class ChannelConnectivity(enum.Enum):
  159. """Mirrors grpc_connectivity_state in the gRPC Core.
  160. Attributes:
  161. IDLE: The channel is idle.
  162. CONNECTING: The channel is connecting.
  163. READY: The channel is ready to conduct RPCs.
  164. TRANSIENT_FAILURE: The channel has seen a failure from which it expects
  165. to recover.
  166. SHUTDOWN: The channel has seen a failure from which it cannot recover.
  167. """
  168. IDLE = (_cygrpc.ConnectivityState.idle, 'idle')
  169. CONNECTING = (_cygrpc.ConnectivityState.connecting, 'connecting')
  170. READY = (_cygrpc.ConnectivityState.ready, 'ready')
  171. TRANSIENT_FAILURE = (_cygrpc.ConnectivityState.transient_failure,
  172. 'transient failure')
  173. SHUTDOWN = (_cygrpc.ConnectivityState.shutdown, 'shutdown')
  174. @enum.unique
  175. class StatusCode(enum.Enum):
  176. """Mirrors grpc_status_code in the gRPC Core.
  177. Attributes:
  178. OK: Not an error; returned on success
  179. CANCELLED: The operation was cancelled (typically by the caller).
  180. UNKNOWN: Unknown error.
  181. INVALID_ARGUMENT: Client specified an invalid argument.
  182. DEADLINE_EXCEEDED: Deadline expired before operation could complete.
  183. NOT_FOUND: Some requested entity (e.g., file or directory) was not found.
  184. ALREADY_EXISTS: Some entity that we attempted to create (e.g., file or directory)
  185. already exists.
  186. PERMISSION_DENIED: The caller does not have permission to execute the specified
  187. operation.
  188. UNAUTHENTICATED: The request does not have valid authentication credentials for the
  189. operation.
  190. RESOURCE_EXHAUSTED: Some resource has been exhausted, perhaps a per-user quota, or
  191. perhaps the entire file system is out of space.
  192. FAILED_PRECONDITION: Operation was rejected because the system is not in a state
  193. required for the operation's execution.
  194. ABORTED: The operation was aborted, typically due to a concurrency issue
  195. like sequencer check failures, transaction aborts, etc.
  196. UNIMPLEMENTED: Operation is not implemented or not supported/enabled in this service.
  197. INTERNAL: Internal errors. Means some invariants expected by underlying
  198. system has been broken.
  199. UNAVAILABLE: The service is currently unavailable.
  200. DATA_LOSS: Unrecoverable data loss or corruption.
  201. """
  202. OK = (_cygrpc.StatusCode.ok, 'ok')
  203. CANCELLED = (_cygrpc.StatusCode.cancelled, 'cancelled')
  204. UNKNOWN = (_cygrpc.StatusCode.unknown, 'unknown')
  205. INVALID_ARGUMENT = (_cygrpc.StatusCode.invalid_argument, 'invalid argument')
  206. DEADLINE_EXCEEDED = (_cygrpc.StatusCode.deadline_exceeded,
  207. 'deadline exceeded')
  208. NOT_FOUND = (_cygrpc.StatusCode.not_found, 'not found')
  209. ALREADY_EXISTS = (_cygrpc.StatusCode.already_exists, 'already exists')
  210. PERMISSION_DENIED = (_cygrpc.StatusCode.permission_denied,
  211. 'permission denied')
  212. RESOURCE_EXHAUSTED = (_cygrpc.StatusCode.resource_exhausted,
  213. 'resource exhausted')
  214. FAILED_PRECONDITION = (_cygrpc.StatusCode.failed_precondition,
  215. 'failed precondition')
  216. ABORTED = (_cygrpc.StatusCode.aborted, 'aborted')
  217. OUT_OF_RANGE = (_cygrpc.StatusCode.out_of_range, 'out of range')
  218. UNIMPLEMENTED = (_cygrpc.StatusCode.unimplemented, 'unimplemented')
  219. INTERNAL = (_cygrpc.StatusCode.internal, 'internal')
  220. UNAVAILABLE = (_cygrpc.StatusCode.unavailable, 'unavailable')
  221. DATA_LOSS = (_cygrpc.StatusCode.data_loss, 'data loss')
  222. UNAUTHENTICATED = (_cygrpc.StatusCode.unauthenticated, 'unauthenticated')
  223. ############################# gRPC Status ################################
  224. class Status(abc.ABC):
  225. """Describes the status of an RPC.
  226. This is an EXPERIMENTAL API.
  227. Attributes:
  228. code: A StatusCode object to be sent to the client.
  229. details: A UTF-8-encodable string to be sent to the client upon
  230. termination of the RPC.
  231. trailing_metadata: The trailing :term:`metadata` in the RPC.
  232. """
  233. ############################# gRPC Exceptions ################################
  234. class RpcError(Exception):
  235. """Raised by the gRPC library to indicate non-OK-status RPC termination."""
  236. ############################## Shared Context ################################
  237. class RpcContext(abc.ABC):
  238. """Provides RPC-related information and action."""
  239. @abc.abstractmethod
  240. def is_active(self):
  241. """Describes whether the RPC is active or has terminated.
  242. Returns:
  243. bool:
  244. True if RPC is active, False otherwise.
  245. """
  246. raise NotImplementedError()
  247. @abc.abstractmethod
  248. def time_remaining(self):
  249. """Describes the length of allowed time remaining for the RPC.
  250. Returns:
  251. A nonnegative float indicating the length of allowed time in seconds
  252. remaining for the RPC to complete before it is considered to have
  253. timed out, or None if no deadline was specified for the RPC.
  254. """
  255. raise NotImplementedError()
  256. @abc.abstractmethod
  257. def cancel(self):
  258. """Cancels the RPC.
  259. Idempotent and has no effect if the RPC has already terminated.
  260. """
  261. raise NotImplementedError()
  262. @abc.abstractmethod
  263. def add_callback(self, callback):
  264. """Registers a callback to be called on RPC termination.
  265. Args:
  266. callback: A no-parameter callable to be called on RPC termination.
  267. Returns:
  268. True if the callback was added and will be called later; False if
  269. the callback was not added and will not be called (because the RPC
  270. already terminated or some other reason).
  271. """
  272. raise NotImplementedError()
  273. ######################### Invocation-Side Context ############################
  274. class Call(RpcContext, metaclass=abc.ABCMeta):
  275. """Invocation-side utility object for an RPC."""
  276. @abc.abstractmethod
  277. def initial_metadata(self):
  278. """Accesses the initial metadata sent by the server.
  279. This method blocks until the value is available.
  280. Returns:
  281. The initial :term:`metadata`.
  282. """
  283. raise NotImplementedError()
  284. @abc.abstractmethod
  285. def trailing_metadata(self):
  286. """Accesses the trailing metadata sent by the server.
  287. This method blocks until the value is available.
  288. Returns:
  289. The trailing :term:`metadata`.
  290. """
  291. raise NotImplementedError()
  292. @abc.abstractmethod
  293. def code(self):
  294. """Accesses the status code sent by the server.
  295. This method blocks until the value is available.
  296. Returns:
  297. The StatusCode value for the RPC.
  298. """
  299. raise NotImplementedError()
  300. @abc.abstractmethod
  301. def details(self):
  302. """Accesses the details sent by the server.
  303. This method blocks until the value is available.
  304. Returns:
  305. The details string of the RPC.
  306. """
  307. raise NotImplementedError()
  308. ############## Invocation-Side Interceptor Interfaces & Classes ##############
  309. class ClientCallDetails(abc.ABC):
  310. """Describes an RPC to be invoked.
  311. Attributes:
  312. method: The method name of the RPC.
  313. timeout: An optional duration of time in seconds to allow for the RPC.
  314. metadata: Optional :term:`metadata` to be transmitted to
  315. the service-side of the RPC.
  316. credentials: An optional CallCredentials for the RPC.
  317. wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
  318. compression: An element of grpc.compression, e.g.
  319. grpc.compression.Gzip.
  320. """
  321. class UnaryUnaryClientInterceptor(abc.ABC):
  322. """Affords intercepting unary-unary invocations."""
  323. @abc.abstractmethod
  324. def intercept_unary_unary(self, continuation, client_call_details, request):
  325. """Intercepts a unary-unary invocation asynchronously.
  326. Args:
  327. continuation: A function that proceeds with the invocation by
  328. executing the next interceptor in chain or invoking the
  329. actual RPC on the underlying Channel. It is the interceptor's
  330. responsibility to call it if it decides to move the RPC forward.
  331. The interceptor can use
  332. `response_future = continuation(client_call_details, request)`
  333. to continue with the RPC. `continuation` returns an object that is
  334. both a Call for the RPC and a Future. In the event of RPC
  335. completion, the return Call-Future's result value will be
  336. the response message of the RPC. Should the event terminate
  337. with non-OK status, the returned Call-Future's exception value
  338. will be an RpcError.
  339. client_call_details: A ClientCallDetails object describing the
  340. outgoing RPC.
  341. request: The request value for the RPC.
  342. Returns:
  343. An object that is both a Call for the RPC and a Future.
  344. In the event of RPC completion, the return Call-Future's
  345. result value will be the response message of the RPC.
  346. Should the event terminate with non-OK status, the returned
  347. Call-Future's exception value will be an RpcError.
  348. """
  349. raise NotImplementedError()
  350. class UnaryStreamClientInterceptor(abc.ABC):
  351. """Affords intercepting unary-stream invocations."""
  352. @abc.abstractmethod
  353. def intercept_unary_stream(self, continuation, client_call_details,
  354. request):
  355. """Intercepts a unary-stream invocation.
  356. Args:
  357. continuation: A function that proceeds with the invocation by
  358. executing the next interceptor in chain or invoking the
  359. actual RPC on the underlying Channel. It is the interceptor's
  360. responsibility to call it if it decides to move the RPC forward.
  361. The interceptor can use
  362. `response_iterator = continuation(client_call_details, request)`
  363. to continue with the RPC. `continuation` returns an object that is
  364. both a Call for the RPC and an iterator for response values.
  365. Drawing response values from the returned Call-iterator may
  366. raise RpcError indicating termination of the RPC with non-OK
  367. status.
  368. client_call_details: A ClientCallDetails object describing the
  369. outgoing RPC.
  370. request: The request value for the RPC.
  371. Returns:
  372. An object that is both a Call for the RPC and an iterator of
  373. response values. Drawing response values from the returned
  374. Call-iterator may raise RpcError indicating termination of
  375. the RPC with non-OK status. This object *should* also fulfill the
  376. Future interface, though it may not.
  377. """
  378. raise NotImplementedError()
  379. class StreamUnaryClientInterceptor(abc.ABC):
  380. """Affords intercepting stream-unary invocations."""
  381. @abc.abstractmethod
  382. def intercept_stream_unary(self, continuation, client_call_details,
  383. request_iterator):
  384. """Intercepts a stream-unary invocation asynchronously.
  385. Args:
  386. continuation: A function that proceeds with the invocation by
  387. executing the next interceptor in chain or invoking the
  388. actual RPC on the underlying Channel. It is the interceptor's
  389. responsibility to call it if it decides to move the RPC forward.
  390. The interceptor can use
  391. `response_future = continuation(client_call_details, request_iterator)`
  392. to continue with the RPC. `continuation` returns an object that is
  393. both a Call for the RPC and a Future. In the event of RPC completion,
  394. the return Call-Future's result value will be the response message
  395. of the RPC. Should the event terminate with non-OK status, the
  396. returned Call-Future's exception value will be an RpcError.
  397. client_call_details: A ClientCallDetails object describing the
  398. outgoing RPC.
  399. request_iterator: An iterator that yields request values for the RPC.
  400. Returns:
  401. An object that is both a Call for the RPC and a Future.
  402. In the event of RPC completion, the return Call-Future's
  403. result value will be the response message of the RPC.
  404. Should the event terminate with non-OK status, the returned
  405. Call-Future's exception value will be an RpcError.
  406. """
  407. raise NotImplementedError()
  408. class StreamStreamClientInterceptor(abc.ABC):
  409. """Affords intercepting stream-stream invocations."""
  410. @abc.abstractmethod
  411. def intercept_stream_stream(self, continuation, client_call_details,
  412. request_iterator):
  413. """Intercepts a stream-stream invocation.
  414. Args:
  415. continuation: A function that proceeds with the invocation by
  416. executing the next interceptor in chain or invoking the
  417. actual RPC on the underlying Channel. It is the interceptor's
  418. responsibility to call it if it decides to move the RPC forward.
  419. The interceptor can use
  420. `response_iterator = continuation(client_call_details, request_iterator)`
  421. to continue with the RPC. `continuation` returns an object that is
  422. both a Call for the RPC and an iterator for response values.
  423. Drawing response values from the returned Call-iterator may
  424. raise RpcError indicating termination of the RPC with non-OK
  425. status.
  426. client_call_details: A ClientCallDetails object describing the
  427. outgoing RPC.
  428. request_iterator: An iterator that yields request values for the RPC.
  429. Returns:
  430. An object that is both a Call for the RPC and an iterator of
  431. response values. Drawing response values from the returned
  432. Call-iterator may raise RpcError indicating termination of
  433. the RPC with non-OK status. This object *should* also fulfill the
  434. Future interface, though it may not.
  435. """
  436. raise NotImplementedError()
  437. ############ Authentication & Authorization Interfaces & Classes #############
  438. class ChannelCredentials(object):
  439. """An encapsulation of the data required to create a secure Channel.
  440. This class has no supported interface - it exists to define the type of its
  441. instances and its instances exist to be passed to other functions. For
  442. example, ssl_channel_credentials returns an instance of this class and
  443. secure_channel requires an instance of this class.
  444. """
  445. def __init__(self, credentials):
  446. self._credentials = credentials
  447. class CallCredentials(object):
  448. """An encapsulation of the data required to assert an identity over a call.
  449. A CallCredentials has to be used with secure Channel, otherwise the
  450. metadata will not be transmitted to the server.
  451. A CallCredentials may be composed with ChannelCredentials to always assert
  452. identity for every call over that Channel.
  453. This class has no supported interface - it exists to define the type of its
  454. instances and its instances exist to be passed to other functions.
  455. """
  456. def __init__(self, credentials):
  457. self._credentials = credentials
  458. class AuthMetadataContext(abc.ABC):
  459. """Provides information to call credentials metadata plugins.
  460. Attributes:
  461. service_url: A string URL of the service being called into.
  462. method_name: A string of the fully qualified method name being called.
  463. """
  464. class AuthMetadataPluginCallback(abc.ABC):
  465. """Callback object received by a metadata plugin."""
  466. def __call__(self, metadata, error):
  467. """Passes to the gRPC runtime authentication metadata for an RPC.
  468. Args:
  469. metadata: The :term:`metadata` used to construct the CallCredentials.
  470. error: An Exception to indicate error or None to indicate success.
  471. """
  472. raise NotImplementedError()
  473. class AuthMetadataPlugin(abc.ABC):
  474. """A specification for custom authentication."""
  475. def __call__(self, context, callback):
  476. """Implements authentication by passing metadata to a callback.
  477. This method will be invoked asynchronously in a separate thread.
  478. Args:
  479. context: An AuthMetadataContext providing information on the RPC that
  480. the plugin is being called to authenticate.
  481. callback: An AuthMetadataPluginCallback to be invoked either
  482. synchronously or asynchronously.
  483. """
  484. raise NotImplementedError()
  485. class ServerCredentials(object):
  486. """An encapsulation of the data required to open a secure port on a Server.
  487. This class has no supported interface - it exists to define the type of its
  488. instances and its instances exist to be passed to other functions.
  489. """
  490. def __init__(self, credentials):
  491. self._credentials = credentials
  492. class ServerCertificateConfiguration(object):
  493. """A certificate configuration for use with an SSL-enabled Server.
  494. Instances of this class can be returned in the certificate configuration
  495. fetching callback.
  496. This class has no supported interface -- it exists to define the
  497. type of its instances and its instances exist to be passed to
  498. other functions.
  499. """
  500. def __init__(self, certificate_configuration):
  501. self._certificate_configuration = certificate_configuration
  502. ######################## Multi-Callable Interfaces ###########################
  503. class UnaryUnaryMultiCallable(abc.ABC):
  504. """Affords invoking a unary-unary RPC from client-side."""
  505. @abc.abstractmethod
  506. def __call__(self,
  507. request,
  508. timeout=None,
  509. metadata=None,
  510. credentials=None,
  511. wait_for_ready=None,
  512. compression=None):
  513. """Synchronously invokes the underlying RPC.
  514. Args:
  515. request: The request value for the RPC.
  516. timeout: An optional duration of time in seconds to allow
  517. for the RPC.
  518. metadata: Optional :term:`metadata` to be transmitted to the
  519. service-side of the RPC.
  520. credentials: An optional CallCredentials for the RPC. Only valid for
  521. secure Channel.
  522. wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
  523. compression: An element of grpc.compression, e.g.
  524. grpc.compression.Gzip.
  525. Returns:
  526. The response value for the RPC.
  527. Raises:
  528. RpcError: Indicating that the RPC terminated with non-OK status. The
  529. raised RpcError will also be a Call for the RPC affording the RPC's
  530. metadata, status code, and details.
  531. """
  532. raise NotImplementedError()
  533. @abc.abstractmethod
  534. def with_call(self,
  535. request,
  536. timeout=None,
  537. metadata=None,
  538. credentials=None,
  539. wait_for_ready=None,
  540. compression=None):
  541. """Synchronously invokes the underlying RPC.
  542. Args:
  543. request: The request value for the RPC.
  544. timeout: An optional durating of time in seconds to allow for
  545. the RPC.
  546. metadata: Optional :term:`metadata` to be transmitted to the
  547. service-side of the RPC.
  548. credentials: An optional CallCredentials for the RPC. Only valid for
  549. secure Channel.
  550. wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
  551. compression: An element of grpc.compression, e.g.
  552. grpc.compression.Gzip.
  553. Returns:
  554. The response value for the RPC and a Call value for the RPC.
  555. Raises:
  556. RpcError: Indicating that the RPC terminated with non-OK status. The
  557. raised RpcError will also be a Call for the RPC affording the RPC's
  558. metadata, status code, and details.
  559. """
  560. raise NotImplementedError()
  561. @abc.abstractmethod
  562. def future(self,
  563. request,
  564. timeout=None,
  565. metadata=None,
  566. credentials=None,
  567. wait_for_ready=None,
  568. compression=None):
  569. """Asynchronously invokes the underlying RPC.
  570. Args:
  571. request: The request value for the RPC.
  572. timeout: An optional duration of time in seconds to allow for
  573. the RPC.
  574. metadata: Optional :term:`metadata` to be transmitted to the
  575. service-side of the RPC.
  576. credentials: An optional CallCredentials for the RPC. Only valid for
  577. secure Channel.
  578. wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
  579. compression: An element of grpc.compression, e.g.
  580. grpc.compression.Gzip.
  581. Returns:
  582. An object that is both a Call for the RPC and a Future.
  583. In the event of RPC completion, the return Call-Future's result
  584. value will be the response message of the RPC.
  585. Should the event terminate with non-OK status,
  586. the returned Call-Future's exception value will be an RpcError.
  587. """
  588. raise NotImplementedError()
  589. class UnaryStreamMultiCallable(abc.ABC):
  590. """Affords invoking a unary-stream RPC from client-side."""
  591. @abc.abstractmethod
  592. def __call__(self,
  593. request,
  594. timeout=None,
  595. metadata=None,
  596. credentials=None,
  597. wait_for_ready=None,
  598. compression=None):
  599. """Invokes the underlying RPC.
  600. Args:
  601. request: The request value for the RPC.
  602. timeout: An optional duration of time in seconds to allow for
  603. the RPC. If None, the timeout is considered infinite.
  604. metadata: An optional :term:`metadata` to be transmitted to the
  605. service-side of the RPC.
  606. credentials: An optional CallCredentials for the RPC. Only valid for
  607. secure Channel.
  608. wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
  609. compression: An element of grpc.compression, e.g.
  610. grpc.compression.Gzip.
  611. Returns:
  612. An object that is a Call for the RPC, an iterator of response
  613. values, and a Future for the RPC. Drawing response values from the
  614. returned Call-iterator may raise RpcError indicating termination of
  615. the RPC with non-OK status.
  616. """
  617. raise NotImplementedError()
  618. class StreamUnaryMultiCallable(abc.ABC):
  619. """Affords invoking a stream-unary RPC from client-side."""
  620. @abc.abstractmethod
  621. def __call__(self,
  622. request_iterator,
  623. timeout=None,
  624. metadata=None,
  625. credentials=None,
  626. wait_for_ready=None,
  627. compression=None):
  628. """Synchronously invokes the underlying RPC.
  629. Args:
  630. request_iterator: An iterator that yields request values for
  631. the RPC.
  632. timeout: An optional duration of time in seconds to allow for
  633. the RPC. If None, the timeout is considered infinite.
  634. metadata: Optional :term:`metadata` to be transmitted to the
  635. service-side of the RPC.
  636. credentials: An optional CallCredentials for the RPC. Only valid for
  637. secure Channel.
  638. wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
  639. compression: An element of grpc.compression, e.g.
  640. grpc.compression.Gzip.
  641. Returns:
  642. The response value for the RPC.
  643. Raises:
  644. RpcError: Indicating that the RPC terminated with non-OK status. The
  645. raised RpcError will also implement grpc.Call, affording methods
  646. such as metadata, code, and details.
  647. """
  648. raise NotImplementedError()
  649. @abc.abstractmethod
  650. def with_call(self,
  651. request_iterator,
  652. timeout=None,
  653. metadata=None,
  654. credentials=None,
  655. wait_for_ready=None,
  656. compression=None):
  657. """Synchronously invokes the underlying RPC on the client.
  658. Args:
  659. request_iterator: An iterator that yields request values for
  660. the RPC.
  661. timeout: An optional duration of time in seconds to allow for
  662. the RPC. If None, the timeout is considered infinite.
  663. metadata: Optional :term:`metadata` to be transmitted to the
  664. service-side of the RPC.
  665. credentials: An optional CallCredentials for the RPC. Only valid for
  666. secure Channel.
  667. wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
  668. compression: An element of grpc.compression, e.g.
  669. grpc.compression.Gzip.
  670. Returns:
  671. The response value for the RPC and a Call object for the RPC.
  672. Raises:
  673. RpcError: Indicating that the RPC terminated with non-OK status. The
  674. raised RpcError will also be a Call for the RPC affording the RPC's
  675. metadata, status code, and details.
  676. """
  677. raise NotImplementedError()
  678. @abc.abstractmethod
  679. def future(self,
  680. request_iterator,
  681. timeout=None,
  682. metadata=None,
  683. credentials=None,
  684. wait_for_ready=None,
  685. compression=None):
  686. """Asynchronously invokes the underlying RPC on the client.
  687. Args:
  688. request_iterator: An iterator that yields request values for the RPC.
  689. timeout: An optional duration of time in seconds to allow for
  690. the RPC. If None, the timeout is considered infinite.
  691. metadata: Optional :term:`metadata` to be transmitted to the
  692. service-side of the RPC.
  693. credentials: An optional CallCredentials for the RPC. Only valid for
  694. secure Channel.
  695. wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
  696. compression: An element of grpc.compression, e.g.
  697. grpc.compression.Gzip.
  698. Returns:
  699. An object that is both a Call for the RPC and a Future.
  700. In the event of RPC completion, the return Call-Future's result value
  701. will be the response message of the RPC. Should the event terminate
  702. with non-OK status, the returned Call-Future's exception value will
  703. be an RpcError.
  704. """
  705. raise NotImplementedError()
  706. class StreamStreamMultiCallable(abc.ABC):
  707. """Affords invoking a stream-stream RPC on client-side."""
  708. @abc.abstractmethod
  709. def __call__(self,
  710. request_iterator,
  711. timeout=None,
  712. metadata=None,
  713. credentials=None,
  714. wait_for_ready=None,
  715. compression=None):
  716. """Invokes the underlying RPC on the client.
  717. Args:
  718. request_iterator: An iterator that yields request values for the RPC.
  719. timeout: An optional duration of time in seconds to allow for
  720. the RPC. If not specified, the timeout is considered infinite.
  721. metadata: Optional :term:`metadata` to be transmitted to the
  722. service-side of the RPC.
  723. credentials: An optional CallCredentials for the RPC. Only valid for
  724. secure Channel.
  725. wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
  726. compression: An element of grpc.compression, e.g.
  727. grpc.compression.Gzip.
  728. Returns:
  729. An object that is a Call for the RPC, an iterator of response
  730. values, and a Future for the RPC. Drawing response values from the
  731. returned Call-iterator may raise RpcError indicating termination of
  732. the RPC with non-OK status.
  733. """
  734. raise NotImplementedError()
  735. ############################# Channel Interface ##############################
  736. class Channel(abc.ABC):
  737. """Affords RPC invocation via generic methods on client-side.
  738. Channel objects implement the Context Manager type, although they need not
  739. support being entered and exited multiple times.
  740. """
  741. @abc.abstractmethod
  742. def subscribe(self, callback, try_to_connect=False):
  743. """Subscribe to this Channel's connectivity state machine.
  744. A Channel may be in any of the states described by ChannelConnectivity.
  745. This method allows application to monitor the state transitions.
  746. The typical use case is to debug or gain better visibility into gRPC
  747. runtime's state.
  748. Args:
  749. callback: A callable to be invoked with ChannelConnectivity argument.
  750. ChannelConnectivity describes current state of the channel.
  751. The callable will be invoked immediately upon subscription
  752. and again for every change to ChannelConnectivity until it
  753. is unsubscribed or this Channel object goes out of scope.
  754. try_to_connect: A boolean indicating whether or not this Channel
  755. should attempt to connect immediately. If set to False, gRPC
  756. runtime decides when to connect.
  757. """
  758. raise NotImplementedError()
  759. @abc.abstractmethod
  760. def unsubscribe(self, callback):
  761. """Unsubscribes a subscribed callback from this Channel's connectivity.
  762. Args:
  763. callback: A callable previously registered with this Channel from
  764. having been passed to its "subscribe" method.
  765. """
  766. raise NotImplementedError()
  767. @abc.abstractmethod
  768. def unary_unary(self,
  769. method,
  770. request_serializer=None,
  771. response_deserializer=None):
  772. """Creates a UnaryUnaryMultiCallable for a unary-unary method.
  773. Args:
  774. method: The name of the RPC method.
  775. request_serializer: Optional :term:`serializer` for serializing the request
  776. message. Request goes unserialized in case None is passed.
  777. response_deserializer: Optional :term:`deserializer` for deserializing the
  778. response message. Response goes undeserialized in case None
  779. is passed.
  780. Returns:
  781. A UnaryUnaryMultiCallable value for the named unary-unary method.
  782. """
  783. raise NotImplementedError()
  784. @abc.abstractmethod
  785. def unary_stream(self,
  786. method,
  787. request_serializer=None,
  788. response_deserializer=None):
  789. """Creates a UnaryStreamMultiCallable for a unary-stream method.
  790. Args:
  791. method: The name of the RPC method.
  792. request_serializer: Optional :term:`serializer` for serializing the request
  793. message. Request goes unserialized in case None is passed.
  794. response_deserializer: Optional :term:`deserializer` for deserializing the
  795. response message. Response goes undeserialized in case None is
  796. passed.
  797. Returns:
  798. A UnaryStreamMultiCallable value for the name unary-stream method.
  799. """
  800. raise NotImplementedError()
  801. @abc.abstractmethod
  802. def stream_unary(self,
  803. method,
  804. request_serializer=None,
  805. response_deserializer=None):
  806. """Creates a StreamUnaryMultiCallable for a stream-unary method.
  807. Args:
  808. method: The name of the RPC method.
  809. request_serializer: Optional :term:`serializer` for serializing the request
  810. message. Request goes unserialized in case None is passed.
  811. response_deserializer: Optional :term:`deserializer` for deserializing the
  812. response message. Response goes undeserialized in case None is
  813. passed.
  814. Returns:
  815. A StreamUnaryMultiCallable value for the named stream-unary method.
  816. """
  817. raise NotImplementedError()
  818. @abc.abstractmethod
  819. def stream_stream(self,
  820. method,
  821. request_serializer=None,
  822. response_deserializer=None):
  823. """Creates a StreamStreamMultiCallable for a stream-stream method.
  824. Args:
  825. method: The name of the RPC method.
  826. request_serializer: Optional :term:`serializer` for serializing the request
  827. message. Request goes unserialized in case None is passed.
  828. response_deserializer: Optional :term:`deserializer` for deserializing the
  829. response message. Response goes undeserialized in case None
  830. is passed.
  831. Returns:
  832. A StreamStreamMultiCallable value for the named stream-stream method.
  833. """
  834. raise NotImplementedError()
  835. @abc.abstractmethod
  836. def close(self):
  837. """Closes this Channel and releases all resources held by it.
  838. Closing the Channel will immediately terminate all RPCs active with the
  839. Channel and it is not valid to invoke new RPCs with the Channel.
  840. This method is idempotent.
  841. """
  842. raise NotImplementedError()
  843. def __enter__(self):
  844. """Enters the runtime context related to the channel object."""
  845. raise NotImplementedError()
  846. def __exit__(self, exc_type, exc_val, exc_tb):
  847. """Exits the runtime context related to the channel object."""
  848. raise NotImplementedError()
  849. ########################## Service-Side Context ##############################
  850. class ServicerContext(RpcContext, metaclass=abc.ABCMeta):
  851. """A context object passed to method implementations."""
  852. @abc.abstractmethod
  853. def invocation_metadata(self):
  854. """Accesses the metadata sent by the client.
  855. Returns:
  856. The invocation :term:`metadata`.
  857. """
  858. raise NotImplementedError()
  859. @abc.abstractmethod
  860. def peer(self):
  861. """Identifies the peer that invoked the RPC being serviced.
  862. Returns:
  863. A string identifying the peer that invoked the RPC being serviced.
  864. The string format is determined by gRPC runtime.
  865. """
  866. raise NotImplementedError()
  867. @abc.abstractmethod
  868. def peer_identities(self):
  869. """Gets one or more peer identity(s).
  870. Equivalent to
  871. servicer_context.auth_context().get(servicer_context.peer_identity_key())
  872. Returns:
  873. An iterable of the identities, or None if the call is not
  874. authenticated. Each identity is returned as a raw bytes type.
  875. """
  876. raise NotImplementedError()
  877. @abc.abstractmethod
  878. def peer_identity_key(self):
  879. """The auth property used to identify the peer.
  880. For example, "x509_common_name" or "x509_subject_alternative_name" are
  881. used to identify an SSL peer.
  882. Returns:
  883. The auth property (string) that indicates the
  884. peer identity, or None if the call is not authenticated.
  885. """
  886. raise NotImplementedError()
  887. @abc.abstractmethod
  888. def auth_context(self):
  889. """Gets the auth context for the call.
  890. Returns:
  891. A map of strings to an iterable of bytes for each auth property.
  892. """
  893. raise NotImplementedError()
  894. def set_compression(self, compression):
  895. """Set the compression algorithm to be used for the entire call.
  896. Args:
  897. compression: An element of grpc.compression, e.g.
  898. grpc.compression.Gzip.
  899. """
  900. raise NotImplementedError()
  901. @abc.abstractmethod
  902. def send_initial_metadata(self, initial_metadata):
  903. """Sends the initial metadata value to the client.
  904. This method need not be called by implementations if they have no
  905. metadata to add to what the gRPC runtime will transmit.
  906. Args:
  907. initial_metadata: The initial :term:`metadata`.
  908. """
  909. raise NotImplementedError()
  910. @abc.abstractmethod
  911. def set_trailing_metadata(self, trailing_metadata):
  912. """Sets the trailing metadata for the RPC.
  913. Sets the trailing metadata to be sent upon completion of the RPC.
  914. If this method is invoked multiple times throughout the lifetime of an
  915. RPC, the value supplied in the final invocation will be the value sent
  916. over the wire.
  917. This method need not be called by implementations if they have no
  918. metadata to add to what the gRPC runtime will transmit.
  919. Args:
  920. trailing_metadata: The trailing :term:`metadata`.
  921. """
  922. raise NotImplementedError()
  923. def trailing_metadata(self):
  924. """Access value to be used as trailing metadata upon RPC completion.
  925. This is an EXPERIMENTAL API.
  926. Returns:
  927. The trailing :term:`metadata` for the RPC.
  928. """
  929. raise NotImplementedError()
  930. @abc.abstractmethod
  931. def abort(self, code, details):
  932. """Raises an exception to terminate the RPC with a non-OK status.
  933. The code and details passed as arguments will supercede any existing
  934. ones.
  935. Args:
  936. code: A StatusCode object to be sent to the client.
  937. It must not be StatusCode.OK.
  938. details: A UTF-8-encodable string to be sent to the client upon
  939. termination of the RPC.
  940. Raises:
  941. Exception: An exception is always raised to signal the abortion the
  942. RPC to the gRPC runtime.
  943. """
  944. raise NotImplementedError()
  945. @abc.abstractmethod
  946. def abort_with_status(self, status):
  947. """Raises an exception to terminate the RPC with a non-OK status.
  948. The status passed as argument will supercede any existing status code,
  949. status message and trailing metadata.
  950. This is an EXPERIMENTAL API.
  951. Args:
  952. status: A grpc.Status object. The status code in it must not be
  953. StatusCode.OK.
  954. Raises:
  955. Exception: An exception is always raised to signal the abortion the
  956. RPC to the gRPC runtime.
  957. """
  958. raise NotImplementedError()
  959. @abc.abstractmethod
  960. def set_code(self, code):
  961. """Sets the value to be used as status code upon RPC completion.
  962. This method need not be called by method implementations if they wish
  963. the gRPC runtime to determine the status code of the RPC.
  964. Args:
  965. code: A StatusCode object to be sent to the client.
  966. """
  967. raise NotImplementedError()
  968. @abc.abstractmethod
  969. def set_details(self, details):
  970. """Sets the value to be used as detail string upon RPC completion.
  971. This method need not be called by method implementations if they have
  972. no details to transmit.
  973. Args:
  974. details: A UTF-8-encodable string to be sent to the client upon
  975. termination of the RPC.
  976. """
  977. raise NotImplementedError()
  978. def code(self):
  979. """Accesses the value to be used as status code upon RPC completion.
  980. This is an EXPERIMENTAL API.
  981. Returns:
  982. The StatusCode value for the RPC.
  983. """
  984. raise NotImplementedError()
  985. def details(self):
  986. """Accesses the value to be used as detail string upon RPC completion.
  987. This is an EXPERIMENTAL API.
  988. Returns:
  989. The details string of the RPC.
  990. """
  991. raise NotImplementedError()
  992. def disable_next_message_compression(self):
  993. """Disables compression for the next response message.
  994. This method will override any compression configuration set during
  995. server creation or set on the call.
  996. """
  997. raise NotImplementedError()
  998. ##################### Service-Side Handler Interfaces ########################
  999. class RpcMethodHandler(abc.ABC):
  1000. """An implementation of a single RPC method.
  1001. Attributes:
  1002. request_streaming: Whether the RPC supports exactly one request message
  1003. or any arbitrary number of request messages.
  1004. response_streaming: Whether the RPC supports exactly one response message
  1005. or any arbitrary number of response messages.
  1006. request_deserializer: A callable :term:`deserializer` that accepts a byte string and
  1007. returns an object suitable to be passed to this object's business
  1008. logic, or None to indicate that this object's business logic should be
  1009. passed the raw request bytes.
  1010. response_serializer: A callable :term:`serializer` that accepts an object produced
  1011. by this object's business logic and returns a byte string, or None to
  1012. indicate that the byte strings produced by this object's business logic
  1013. should be transmitted on the wire as they are.
  1014. unary_unary: This object's application-specific business logic as a
  1015. callable value that takes a request value and a ServicerContext object
  1016. and returns a response value. Only non-None if both request_streaming
  1017. and response_streaming are False.
  1018. unary_stream: This object's application-specific business logic as a
  1019. callable value that takes a request value and a ServicerContext object
  1020. and returns an iterator of response values. Only non-None if
  1021. request_streaming is False and response_streaming is True.
  1022. stream_unary: This object's application-specific business logic as a
  1023. callable value that takes an iterator of request values and a
  1024. ServicerContext object and returns a response value. Only non-None if
  1025. request_streaming is True and response_streaming is False.
  1026. stream_stream: This object's application-specific business logic as a
  1027. callable value that takes an iterator of request values and a
  1028. ServicerContext object and returns an iterator of response values.
  1029. Only non-None if request_streaming and response_streaming are both
  1030. True.
  1031. """
  1032. class HandlerCallDetails(abc.ABC):
  1033. """Describes an RPC that has just arrived for service.
  1034. Attributes:
  1035. method: The method name of the RPC.
  1036. invocation_metadata: The :term:`metadata` sent by the client.
  1037. """
  1038. class GenericRpcHandler(abc.ABC):
  1039. """An implementation of arbitrarily many RPC methods."""
  1040. @abc.abstractmethod
  1041. def service(self, handler_call_details):
  1042. """Returns the handler for servicing the RPC.
  1043. Args:
  1044. handler_call_details: A HandlerCallDetails describing the RPC.
  1045. Returns:
  1046. An RpcMethodHandler with which the RPC may be serviced if the
  1047. implementation chooses to service this RPC, or None otherwise.
  1048. """
  1049. raise NotImplementedError()
  1050. class ServiceRpcHandler(GenericRpcHandler, metaclass=abc.ABCMeta):
  1051. """An implementation of RPC methods belonging to a service.
  1052. A service handles RPC methods with structured names of the form
  1053. '/Service.Name/Service.Method', where 'Service.Name' is the value
  1054. returned by service_name(), and 'Service.Method' is the method
  1055. name. A service can have multiple method names, but only a single
  1056. service name.
  1057. """
  1058. @abc.abstractmethod
  1059. def service_name(self):
  1060. """Returns this service's name.
  1061. Returns:
  1062. The service name.
  1063. """
  1064. raise NotImplementedError()
  1065. #################### Service-Side Interceptor Interfaces #####################
  1066. class ServerInterceptor(abc.ABC):
  1067. """Affords intercepting incoming RPCs on the service-side."""
  1068. @abc.abstractmethod
  1069. def intercept_service(self, continuation, handler_call_details):
  1070. """Intercepts incoming RPCs before handing them over to a handler.
  1071. Args:
  1072. continuation: A function that takes a HandlerCallDetails and
  1073. proceeds to invoke the next interceptor in the chain, if any,
  1074. or the RPC handler lookup logic, with the call details passed
  1075. as an argument, and returns an RpcMethodHandler instance if
  1076. the RPC is considered serviced, or None otherwise.
  1077. handler_call_details: A HandlerCallDetails describing the RPC.
  1078. Returns:
  1079. An RpcMethodHandler with which the RPC may be serviced if the
  1080. interceptor chooses to service this RPC, or None otherwise.
  1081. """
  1082. raise NotImplementedError()
  1083. ############################# Server Interface ###############################
  1084. class Server(abc.ABC):
  1085. """Services RPCs."""
  1086. @abc.abstractmethod
  1087. def add_generic_rpc_handlers(self, generic_rpc_handlers):
  1088. """Registers GenericRpcHandlers with this Server.
  1089. This method is only safe to call before the server is started.
  1090. Args:
  1091. generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
  1092. used to service RPCs.
  1093. """
  1094. raise NotImplementedError()
  1095. @abc.abstractmethod
  1096. def add_insecure_port(self, address):
  1097. """Opens an insecure port for accepting RPCs.
  1098. This method may only be called before starting the server.
  1099. Args:
  1100. address: The address for which to open a port. If the port is 0,
  1101. or not specified in the address, then gRPC runtime will choose a port.
  1102. Returns:
  1103. An integer port on which server will accept RPC requests.
  1104. """
  1105. raise NotImplementedError()
  1106. @abc.abstractmethod
  1107. def add_secure_port(self, address, server_credentials):
  1108. """Opens a secure port for accepting RPCs.
  1109. This method may only be called before starting the server.
  1110. Args:
  1111. address: The address for which to open a port.
  1112. if the port is 0, or not specified in the address, then gRPC
  1113. runtime will choose a port.
  1114. server_credentials: A ServerCredentials object.
  1115. Returns:
  1116. An integer port on which server will accept RPC requests.
  1117. """
  1118. raise NotImplementedError()
  1119. @abc.abstractmethod
  1120. def start(self):
  1121. """Starts this Server.
  1122. This method may only be called once. (i.e. it is not idempotent).
  1123. """
  1124. raise NotImplementedError()
  1125. @abc.abstractmethod
  1126. def stop(self, grace):
  1127. """Stops this Server.
  1128. This method immediately stop service of new RPCs in all cases.
  1129. If a grace period is specified, this method returns immediately
  1130. and all RPCs active at the end of the grace period are aborted.
  1131. If a grace period is not specified (by passing None for `grace`),
  1132. all existing RPCs are aborted immediately and this method
  1133. blocks until the last RPC handler terminates.
  1134. This method is idempotent and may be called at any time.
  1135. Passing a smaller grace value in a subsequent call will have
  1136. the effect of stopping the Server sooner (passing None will
  1137. have the effect of stopping the server immediately). Passing
  1138. a larger grace value in a subsequent call *will not* have the
  1139. effect of stopping the server later (i.e. the most restrictive
  1140. grace value is used).
  1141. Args:
  1142. grace: A duration of time in seconds or None.
  1143. Returns:
  1144. A threading.Event that will be set when this Server has completely
  1145. stopped, i.e. when running RPCs either complete or are aborted and
  1146. all handlers have terminated.
  1147. """
  1148. raise NotImplementedError()
  1149. def wait_for_termination(self, timeout=None):
  1150. """Block current thread until the server stops.
  1151. This is an EXPERIMENTAL API.
  1152. The wait will not consume computational resources during blocking, and
  1153. it will block until one of the two following conditions are met:
  1154. 1) The server is stopped or terminated;
  1155. 2) A timeout occurs if timeout is not `None`.
  1156. The timeout argument works in the same way as `threading.Event.wait()`.
  1157. https://docs.python.org/3/library/threading.html#threading.Event.wait
  1158. Args:
  1159. timeout: A floating point number specifying a timeout for the
  1160. operation in seconds.
  1161. Returns:
  1162. A bool indicates if the operation times out.
  1163. """
  1164. raise NotImplementedError()
  1165. ################################# Functions ################################
  1166. def unary_unary_rpc_method_handler(behavior,
  1167. request_deserializer=None,
  1168. response_serializer=None):
  1169. """Creates an RpcMethodHandler for a unary-unary RPC method.
  1170. Args:
  1171. behavior: The implementation of an RPC that accepts one request
  1172. and returns one response.
  1173. request_deserializer: An optional :term:`deserializer` for request deserialization.
  1174. response_serializer: An optional :term:`serializer` for response serialization.
  1175. Returns:
  1176. An RpcMethodHandler object that is typically used by grpc.Server.
  1177. """
  1178. from grpc import _utilities # pylint: disable=cyclic-import
  1179. return _utilities.RpcMethodHandler(False, False, request_deserializer,
  1180. response_serializer, behavior, None,
  1181. None, None)
  1182. def unary_stream_rpc_method_handler(behavior,
  1183. request_deserializer=None,
  1184. response_serializer=None):
  1185. """Creates an RpcMethodHandler for a unary-stream RPC method.
  1186. Args:
  1187. behavior: The implementation of an RPC that accepts one request
  1188. and returns an iterator of response values.
  1189. request_deserializer: An optional :term:`deserializer` for request deserialization.
  1190. response_serializer: An optional :term:`serializer` for response serialization.
  1191. Returns:
  1192. An RpcMethodHandler object that is typically used by grpc.Server.
  1193. """
  1194. from grpc import _utilities # pylint: disable=cyclic-import
  1195. return _utilities.RpcMethodHandler(False, True, request_deserializer,
  1196. response_serializer, None, behavior,
  1197. None, None)
  1198. def stream_unary_rpc_method_handler(behavior,
  1199. request_deserializer=None,
  1200. response_serializer=None):
  1201. """Creates an RpcMethodHandler for a stream-unary RPC method.
  1202. Args:
  1203. behavior: The implementation of an RPC that accepts an iterator of
  1204. request values and returns a single response value.
  1205. request_deserializer: An optional :term:`deserializer` for request deserialization.
  1206. response_serializer: An optional :term:`serializer` for response serialization.
  1207. Returns:
  1208. An RpcMethodHandler object that is typically used by grpc.Server.
  1209. """
  1210. from grpc import _utilities # pylint: disable=cyclic-import
  1211. return _utilities.RpcMethodHandler(True, False, request_deserializer,
  1212. response_serializer, None, None,
  1213. behavior, None)
  1214. def stream_stream_rpc_method_handler(behavior,
  1215. request_deserializer=None,
  1216. response_serializer=None):
  1217. """Creates an RpcMethodHandler for a stream-stream RPC method.
  1218. Args:
  1219. behavior: The implementation of an RPC that accepts an iterator of
  1220. request values and returns an iterator of response values.
  1221. request_deserializer: An optional :term:`deserializer` for request deserialization.
  1222. response_serializer: An optional :term:`serializer` for response serialization.
  1223. Returns:
  1224. An RpcMethodHandler object that is typically used by grpc.Server.
  1225. """
  1226. from grpc import _utilities # pylint: disable=cyclic-import
  1227. return _utilities.RpcMethodHandler(True, True, request_deserializer,
  1228. response_serializer, None, None, None,
  1229. behavior)
  1230. def method_handlers_generic_handler(service, method_handlers):
  1231. """Creates a GenericRpcHandler from RpcMethodHandlers.
  1232. Args:
  1233. service: The name of the service that is implemented by the
  1234. method_handlers.
  1235. method_handlers: A dictionary that maps method names to corresponding
  1236. RpcMethodHandler.
  1237. Returns:
  1238. A GenericRpcHandler. This is typically added to the grpc.Server object
  1239. with add_generic_rpc_handlers() before starting the server.
  1240. """
  1241. from grpc import _utilities # pylint: disable=cyclic-import
  1242. return _utilities.DictionaryGenericHandler(service, method_handlers)
  1243. def ssl_channel_credentials(root_certificates=None,
  1244. private_key=None,
  1245. certificate_chain=None):
  1246. """Creates a ChannelCredentials for use with an SSL-enabled Channel.
  1247. Args:
  1248. root_certificates: The PEM-encoded root certificates as a byte string,
  1249. or None to retrieve them from a default location chosen by gRPC
  1250. runtime.
  1251. private_key: The PEM-encoded private key as a byte string, or None if no
  1252. private key should be used.
  1253. certificate_chain: The PEM-encoded certificate chain as a byte string
  1254. to use or None if no certificate chain should be used.
  1255. Returns:
  1256. A ChannelCredentials for use with an SSL-enabled Channel.
  1257. """
  1258. return ChannelCredentials(
  1259. _cygrpc.SSLChannelCredentials(root_certificates, private_key,
  1260. certificate_chain))
  1261. def xds_channel_credentials(fallback_credentials=None):
  1262. """Creates a ChannelCredentials for use with xDS. This is an EXPERIMENTAL
  1263. API.
  1264. Args:
  1265. fallback_credentials: Credentials to use in case it is not possible to
  1266. establish a secure connection via xDS. If no fallback_credentials
  1267. argument is supplied, a default SSLChannelCredentials is used.
  1268. """
  1269. fallback_credentials = ssl_channel_credentials(
  1270. ) if fallback_credentials is None else fallback_credentials
  1271. return ChannelCredentials(
  1272. _cygrpc.XDSChannelCredentials(fallback_credentials._credentials))
  1273. def metadata_call_credentials(metadata_plugin, name=None):
  1274. """Construct CallCredentials from an AuthMetadataPlugin.
  1275. Args:
  1276. metadata_plugin: An AuthMetadataPlugin to use for authentication.
  1277. name: An optional name for the plugin.
  1278. Returns:
  1279. A CallCredentials.
  1280. """
  1281. from grpc import _plugin_wrapping # pylint: disable=cyclic-import
  1282. return _plugin_wrapping.metadata_plugin_call_credentials(
  1283. metadata_plugin, name)
  1284. def access_token_call_credentials(access_token):
  1285. """Construct CallCredentials from an access token.
  1286. Args:
  1287. access_token: A string to place directly in the http request
  1288. authorization header, for example
  1289. "authorization: Bearer <access_token>".
  1290. Returns:
  1291. A CallCredentials.
  1292. """
  1293. from grpc import _auth # pylint: disable=cyclic-import
  1294. from grpc import _plugin_wrapping # pylint: disable=cyclic-import
  1295. return _plugin_wrapping.metadata_plugin_call_credentials(
  1296. _auth.AccessTokenAuthMetadataPlugin(access_token), None)
  1297. def composite_call_credentials(*call_credentials):
  1298. """Compose multiple CallCredentials to make a new CallCredentials.
  1299. Args:
  1300. *call_credentials: At least two CallCredentials objects.
  1301. Returns:
  1302. A CallCredentials object composed of the given CallCredentials objects.
  1303. """
  1304. return CallCredentials(
  1305. _cygrpc.CompositeCallCredentials(
  1306. tuple(single_call_credentials._credentials
  1307. for single_call_credentials in call_credentials)))
  1308. def composite_channel_credentials(channel_credentials, *call_credentials):
  1309. """Compose a ChannelCredentials and one or more CallCredentials objects.
  1310. Args:
  1311. channel_credentials: A ChannelCredentials object.
  1312. *call_credentials: One or more CallCredentials objects.
  1313. Returns:
  1314. A ChannelCredentials composed of the given ChannelCredentials and
  1315. CallCredentials objects.
  1316. """
  1317. return ChannelCredentials(
  1318. _cygrpc.CompositeChannelCredentials(
  1319. tuple(single_call_credentials._credentials
  1320. for single_call_credentials in call_credentials),
  1321. channel_credentials._credentials))
  1322. def ssl_server_credentials(private_key_certificate_chain_pairs,
  1323. root_certificates=None,
  1324. require_client_auth=False):
  1325. """Creates a ServerCredentials for use with an SSL-enabled Server.
  1326. Args:
  1327. private_key_certificate_chain_pairs: A list of pairs of the form
  1328. [PEM-encoded private key, PEM-encoded certificate chain].
  1329. root_certificates: An optional byte string of PEM-encoded client root
  1330. certificates that the server will use to verify client authentication.
  1331. If omitted, require_client_auth must also be False.
  1332. require_client_auth: A boolean indicating whether or not to require
  1333. clients to be authenticated. May only be True if root_certificates
  1334. is not None.
  1335. Returns:
  1336. A ServerCredentials for use with an SSL-enabled Server. Typically, this
  1337. object is an argument to add_secure_port() method during server setup.
  1338. """
  1339. if not private_key_certificate_chain_pairs:
  1340. raise ValueError(
  1341. 'At least one private key-certificate chain pair is required!')
  1342. elif require_client_auth and root_certificates is None:
  1343. raise ValueError(
  1344. 'Illegal to require client auth without providing root certificates!'
  1345. )
  1346. else:
  1347. return ServerCredentials(
  1348. _cygrpc.server_credentials_ssl(root_certificates, [
  1349. _cygrpc.SslPemKeyCertPair(key, pem)
  1350. for key, pem in private_key_certificate_chain_pairs
  1351. ], require_client_auth))
  1352. def xds_server_credentials(fallback_credentials):
  1353. """Creates a ServerCredentials for use with xDS. This is an EXPERIMENTAL
  1354. API.
  1355. Args:
  1356. fallback_credentials: Credentials to use in case it is not possible to
  1357. establish a secure connection via xDS. No default value is provided.
  1358. """
  1359. return ServerCredentials(
  1360. _cygrpc.xds_server_credentials(fallback_credentials._credentials))
  1361. def insecure_server_credentials():
  1362. """Creates a credentials object directing the server to use no credentials.
  1363. This is an EXPERIMENTAL API.
  1364. This object cannot be used directly in a call to `add_secure_port`.
  1365. Instead, it should be used to construct other credentials objects, e.g.
  1366. with xds_server_credentials.
  1367. """
  1368. return ServerCredentials(_cygrpc.insecure_server_credentials())
  1369. def ssl_server_certificate_configuration(private_key_certificate_chain_pairs,
  1370. root_certificates=None):
  1371. """Creates a ServerCertificateConfiguration for use with a Server.
  1372. Args:
  1373. private_key_certificate_chain_pairs: A collection of pairs of
  1374. the form [PEM-encoded private key, PEM-encoded certificate
  1375. chain].
  1376. root_certificates: An optional byte string of PEM-encoded client root
  1377. certificates that the server will use to verify client authentication.
  1378. Returns:
  1379. A ServerCertificateConfiguration that can be returned in the certificate
  1380. configuration fetching callback.
  1381. """
  1382. if private_key_certificate_chain_pairs:
  1383. return ServerCertificateConfiguration(
  1384. _cygrpc.server_certificate_config_ssl(root_certificates, [
  1385. _cygrpc.SslPemKeyCertPair(key, pem)
  1386. for key, pem in private_key_certificate_chain_pairs
  1387. ]))
  1388. else:
  1389. raise ValueError(
  1390. 'At least one private key-certificate chain pair is required!')
  1391. def dynamic_ssl_server_credentials(initial_certificate_configuration,
  1392. certificate_configuration_fetcher,
  1393. require_client_authentication=False):
  1394. """Creates a ServerCredentials for use with an SSL-enabled Server.
  1395. Args:
  1396. initial_certificate_configuration (ServerCertificateConfiguration): The
  1397. certificate configuration with which the server will be initialized.
  1398. certificate_configuration_fetcher (callable): A callable that takes no
  1399. arguments and should return a ServerCertificateConfiguration to
  1400. replace the server's current certificate, or None for no change
  1401. (i.e., the server will continue its current certificate
  1402. config). The library will call this callback on *every* new
  1403. client connection before starting the TLS handshake with the
  1404. client, thus allowing the user application to optionally
  1405. return a new ServerCertificateConfiguration that the server will then
  1406. use for the handshake.
  1407. require_client_authentication: A boolean indicating whether or not to
  1408. require clients to be authenticated.
  1409. Returns:
  1410. A ServerCredentials.
  1411. """
  1412. return ServerCredentials(
  1413. _cygrpc.server_credentials_ssl_dynamic_cert_config(
  1414. initial_certificate_configuration,
  1415. certificate_configuration_fetcher, require_client_authentication))
  1416. @enum.unique
  1417. class LocalConnectionType(enum.Enum):
  1418. """Types of local connection for local credential creation.
  1419. Attributes:
  1420. UDS: Unix domain socket connections
  1421. LOCAL_TCP: Local TCP connections.
  1422. """
  1423. UDS = _cygrpc.LocalConnectionType.uds
  1424. LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp
  1425. def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
  1426. """Creates a local ChannelCredentials used for local connections.
  1427. This is an EXPERIMENTAL API.
  1428. Local credentials are used by local TCP endpoints (e.g. localhost:10000)
  1429. also UDS connections.
  1430. The connections created by local channel credentials are not
  1431. encrypted, but will be checked if they are local or not.
  1432. The UDS connections are considered secure by providing peer authentication
  1433. and data confidentiality while TCP connections are considered insecure.
  1434. It is allowed to transmit call credentials over connections created by
  1435. local channel credentials.
  1436. Local channel credentials are useful for 1) eliminating insecure_channel usage;
  1437. 2) enable unit testing for call credentials without setting up secrets.
  1438. Args:
  1439. local_connect_type: Local connection type (either
  1440. grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
  1441. Returns:
  1442. A ChannelCredentials for use with a local Channel
  1443. """
  1444. return ChannelCredentials(
  1445. _cygrpc.channel_credentials_local(local_connect_type.value))
  1446. def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
  1447. """Creates a local ServerCredentials used for local connections.
  1448. This is an EXPERIMENTAL API.
  1449. Local credentials are used by local TCP endpoints (e.g. localhost:10000)
  1450. also UDS connections.
  1451. The connections created by local server credentials are not
  1452. encrypted, but will be checked if they are local or not.
  1453. The UDS connections are considered secure by providing peer authentication
  1454. and data confidentiality while TCP connections are considered insecure.
  1455. It is allowed to transmit call credentials over connections created by local
  1456. server credentials.
  1457. Local server credentials are useful for 1) eliminating insecure_channel usage;
  1458. 2) enable unit testing for call credentials without setting up secrets.
  1459. Args:
  1460. local_connect_type: Local connection type (either
  1461. grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
  1462. Returns:
  1463. A ServerCredentials for use with a local Server
  1464. """
  1465. return ServerCredentials(
  1466. _cygrpc.server_credentials_local(local_connect_type.value))
  1467. def alts_channel_credentials(service_accounts=None):
  1468. """Creates a ChannelCredentials for use with an ALTS-enabled Channel.
  1469. This is an EXPERIMENTAL API.
  1470. ALTS credentials API can only be used in GCP environment as it relies on
  1471. handshaker service being available. For more info about ALTS see
  1472. https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
  1473. Args:
  1474. service_accounts: A list of server identities accepted by the client.
  1475. If target service accounts are provided and none of them matches the
  1476. peer identity of the server, handshake will fail. The arg can be empty
  1477. if the client does not have any information about trusted server
  1478. identity.
  1479. Returns:
  1480. A ChannelCredentials for use with an ALTS-enabled Channel
  1481. """
  1482. return ChannelCredentials(
  1483. _cygrpc.channel_credentials_alts(service_accounts or []))
  1484. def alts_server_credentials():
  1485. """Creates a ServerCredentials for use with an ALTS-enabled connection.
  1486. This is an EXPERIMENTAL API.
  1487. ALTS credentials API can only be used in GCP environment as it relies on
  1488. handshaker service being available. For more info about ALTS see
  1489. https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
  1490. Returns:
  1491. A ServerCredentials for use with an ALTS-enabled Server
  1492. """
  1493. return ServerCredentials(_cygrpc.server_credentials_alts())
  1494. def compute_engine_channel_credentials(call_credentials):
  1495. """Creates a compute engine channel credential.
  1496. This credential can only be used in a GCP environment as it relies on
  1497. a handshaker service. For more info about ALTS, see
  1498. https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
  1499. This channel credential is expected to be used as part of a composite
  1500. credential in conjunction with a call credentials that authenticates the
  1501. VM's default service account. If used with any other sort of call
  1502. credential, the connection may suddenly and unexpectedly begin failing RPCs.
  1503. """
  1504. return ChannelCredentials(
  1505. _cygrpc.channel_credentials_compute_engine(
  1506. call_credentials._credentials))
  1507. def channel_ready_future(channel):
  1508. """Creates a Future that tracks when a Channel is ready.
  1509. Cancelling the Future does not affect the channel's state machine.
  1510. It merely decouples the Future from channel state machine.
  1511. Args:
  1512. channel: A Channel object.
  1513. Returns:
  1514. A Future object that matures when the channel connectivity is
  1515. ChannelConnectivity.READY.
  1516. """
  1517. from grpc import _utilities # pylint: disable=cyclic-import
  1518. return _utilities.channel_ready_future(channel)
  1519. def insecure_channel(target, options=None, compression=None):
  1520. """Creates an insecure Channel to a server.
  1521. The returned Channel is thread-safe.
  1522. Args:
  1523. target: The server address
  1524. options: An optional list of key-value pairs (:term:`channel_arguments`
  1525. in gRPC Core runtime) to configure the channel.
  1526. compression: An optional value indicating the compression method to be
  1527. used over the lifetime of the channel.
  1528. Returns:
  1529. A Channel.
  1530. """
  1531. from grpc import _channel # pylint: disable=cyclic-import
  1532. return _channel.Channel(target, () if options is None else options, None,
  1533. compression)
  1534. def secure_channel(target, credentials, options=None, compression=None):
  1535. """Creates a secure Channel to a server.
  1536. The returned Channel is thread-safe.
  1537. Args:
  1538. target: The server address.
  1539. credentials: A ChannelCredentials instance.
  1540. options: An optional list of key-value pairs (:term:`channel_arguments`
  1541. in gRPC Core runtime) to configure the channel.
  1542. compression: An optional value indicating the compression method to be
  1543. used over the lifetime of the channel.
  1544. Returns:
  1545. A Channel.
  1546. """
  1547. from grpc import _channel # pylint: disable=cyclic-import
  1548. from grpc.experimental import _insecure_channel_credentials
  1549. if credentials._credentials is _insecure_channel_credentials:
  1550. raise ValueError(
  1551. "secure_channel cannot be called with insecure credentials." +
  1552. " Call insecure_channel instead.")
  1553. return _channel.Channel(target, () if options is None else options,
  1554. credentials._credentials, compression)
  1555. def intercept_channel(channel, *interceptors):
  1556. """Intercepts a channel through a set of interceptors.
  1557. Args:
  1558. channel: A Channel.
  1559. interceptors: Zero or more objects of type
  1560. UnaryUnaryClientInterceptor,
  1561. UnaryStreamClientInterceptor,
  1562. StreamUnaryClientInterceptor, or
  1563. StreamStreamClientInterceptor.
  1564. Interceptors are given control in the order they are listed.
  1565. Returns:
  1566. A Channel that intercepts each invocation via the provided interceptors.
  1567. Raises:
  1568. TypeError: If interceptor does not derive from any of
  1569. UnaryUnaryClientInterceptor,
  1570. UnaryStreamClientInterceptor,
  1571. StreamUnaryClientInterceptor, or
  1572. StreamStreamClientInterceptor.
  1573. """
  1574. from grpc import _interceptor # pylint: disable=cyclic-import
  1575. return _interceptor.intercept_channel(channel, *interceptors)
  1576. def server(thread_pool,
  1577. handlers=None,
  1578. interceptors=None,
  1579. options=None,
  1580. maximum_concurrent_rpcs=None,
  1581. compression=None,
  1582. xds=False):
  1583. """Creates a Server with which RPCs can be serviced.
  1584. Args:
  1585. thread_pool: A futures.ThreadPoolExecutor to be used by the Server
  1586. to execute RPC handlers.
  1587. handlers: An optional list of GenericRpcHandlers used for executing RPCs.
  1588. More handlers may be added by calling add_generic_rpc_handlers any time
  1589. before the server is started.
  1590. interceptors: An optional list of ServerInterceptor objects that observe
  1591. and optionally manipulate the incoming RPCs before handing them over to
  1592. handlers. The interceptors are given control in the order they are
  1593. specified. This is an EXPERIMENTAL API.
  1594. options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime)
  1595. to configure the channel.
  1596. maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
  1597. will service before returning RESOURCE_EXHAUSTED status, or None to
  1598. indicate no limit.
  1599. compression: An element of grpc.compression, e.g.
  1600. grpc.compression.Gzip. This compression algorithm will be used for the
  1601. lifetime of the server unless overridden.
  1602. xds: If set to true, retrieves server configuration via xDS. This is an
  1603. EXPERIMENTAL option.
  1604. Returns:
  1605. A Server object.
  1606. """
  1607. from grpc import _server # pylint: disable=cyclic-import
  1608. return _server.create_server(thread_pool,
  1609. () if handlers is None else handlers,
  1610. () if interceptors is None else interceptors,
  1611. () if options is None else options,
  1612. maximum_concurrent_rpcs, compression, xds)
  1613. @contextlib.contextmanager
  1614. def _create_servicer_context(rpc_event, state, request_deserializer):
  1615. from grpc import _server # pylint: disable=cyclic-import
  1616. context = _server._Context(rpc_event, state, request_deserializer)
  1617. yield context
  1618. context._finalize_state() # pylint: disable=protected-access
  1619. @enum.unique
  1620. class Compression(enum.IntEnum):
  1621. """Indicates the compression method to be used for an RPC.
  1622. Attributes:
  1623. NoCompression: Do not use compression algorithm.
  1624. Deflate: Use "Deflate" compression algorithm.
  1625. Gzip: Use "Gzip" compression algorithm.
  1626. """
  1627. NoCompression = _compression.NoCompression
  1628. Deflate = _compression.Deflate
  1629. Gzip = _compression.Gzip
  1630. ################################### __all__ #################################
  1631. __all__ = (
  1632. 'FutureTimeoutError',
  1633. 'FutureCancelledError',
  1634. 'Future',
  1635. 'ChannelConnectivity',
  1636. 'StatusCode',
  1637. 'Status',
  1638. 'RpcError',
  1639. 'RpcContext',
  1640. 'Call',
  1641. 'ChannelCredentials',
  1642. 'CallCredentials',
  1643. 'AuthMetadataContext',
  1644. 'AuthMetadataPluginCallback',
  1645. 'AuthMetadataPlugin',
  1646. 'Compression',
  1647. 'ClientCallDetails',
  1648. 'ServerCertificateConfiguration',
  1649. 'ServerCredentials',
  1650. 'LocalConnectionType',
  1651. 'UnaryUnaryMultiCallable',
  1652. 'UnaryStreamMultiCallable',
  1653. 'StreamUnaryMultiCallable',
  1654. 'StreamStreamMultiCallable',
  1655. 'UnaryUnaryClientInterceptor',
  1656. 'UnaryStreamClientInterceptor',
  1657. 'StreamUnaryClientInterceptor',
  1658. 'StreamStreamClientInterceptor',
  1659. 'Channel',
  1660. 'ServicerContext',
  1661. 'RpcMethodHandler',
  1662. 'HandlerCallDetails',
  1663. 'GenericRpcHandler',
  1664. 'ServiceRpcHandler',
  1665. 'Server',
  1666. 'ServerInterceptor',
  1667. 'unary_unary_rpc_method_handler',
  1668. 'unary_stream_rpc_method_handler',
  1669. 'stream_unary_rpc_method_handler',
  1670. 'stream_stream_rpc_method_handler',
  1671. 'method_handlers_generic_handler',
  1672. 'ssl_channel_credentials',
  1673. 'metadata_call_credentials',
  1674. 'access_token_call_credentials',
  1675. 'composite_call_credentials',
  1676. 'composite_channel_credentials',
  1677. 'compute_engine_channel_credentials',
  1678. 'local_channel_credentials',
  1679. 'local_server_credentials',
  1680. 'alts_channel_credentials',
  1681. 'alts_server_credentials',
  1682. 'ssl_server_credentials',
  1683. 'ssl_server_certificate_configuration',
  1684. 'dynamic_ssl_server_credentials',
  1685. 'channel_ready_future',
  1686. 'insecure_channel',
  1687. 'secure_channel',
  1688. 'intercept_channel',
  1689. 'server',
  1690. 'protos',
  1691. 'services',
  1692. 'protos_and_services',
  1693. 'xds_channel_credentials',
  1694. 'xds_server_credentials',
  1695. 'insecure_server_credentials',
  1696. )
  1697. ############################### Extension Shims ################################
  1698. # Here to maintain backwards compatibility; avoid using these in new code!
  1699. try:
  1700. import grpc_tools
  1701. sys.modules.update({'grpc.tools': grpc_tools})
  1702. except ImportError:
  1703. pass
  1704. try:
  1705. import grpc_health
  1706. sys.modules.update({'grpc.health': grpc_health})
  1707. except ImportError:
  1708. pass
  1709. try:
  1710. import grpc_reflection
  1711. sys.modules.update({'grpc.reflection': grpc_reflection})
  1712. except ImportError:
  1713. pass
  1714. # Prevents import order issue in the case of renamed path.
  1715. if sys.version_info >= (3, 6) and __name__ == "grpc":
  1716. from grpc import aio # pylint: disable=ungrouped-imports
  1717. sys.modules.update({'grpc.aio': aio})