__init__.py 81 KB

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