__init__.py 80 KB

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