_call.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. # Copyright 2019 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. """Invocation-side implementation of gRPC Asyncio Python."""
  15. import asyncio
  16. import enum
  17. from functools import partial
  18. import inspect
  19. import logging
  20. import traceback
  21. from typing import AsyncIterator, Optional, Tuple
  22. import grpc
  23. from grpc import _common
  24. from grpc._cython import cygrpc
  25. from . import _base_call
  26. from ._metadata import Metadata
  27. from ._typing import DeserializingFunction
  28. from ._typing import DoneCallbackType
  29. from ._typing import MetadatumType
  30. from ._typing import RequestIterableType
  31. from ._typing import RequestType
  32. from ._typing import ResponseType
  33. from ._typing import SerializingFunction
  34. __all__ = 'AioRpcError', 'Call', 'UnaryUnaryCall', 'UnaryStreamCall'
  35. _LOCAL_CANCELLATION_DETAILS = 'Locally cancelled by application!'
  36. _GC_CANCELLATION_DETAILS = 'Cancelled upon garbage collection!'
  37. _RPC_ALREADY_FINISHED_DETAILS = 'RPC already finished.'
  38. _RPC_HALF_CLOSED_DETAILS = 'RPC is half closed after calling "done_writing".'
  39. _API_STYLE_ERROR = 'The iterator and read/write APIs may not be mixed on a single RPC.'
  40. _OK_CALL_REPRESENTATION = ('<{} of RPC that terminated with:\n'
  41. '\tstatus = {}\n'
  42. '\tdetails = "{}"\n'
  43. '>')
  44. _NON_OK_CALL_REPRESENTATION = ('<{} of RPC that terminated with:\n'
  45. '\tstatus = {}\n'
  46. '\tdetails = "{}"\n'
  47. '\tdebug_error_string = "{}"\n'
  48. '>')
  49. _LOGGER = logging.getLogger(__name__)
  50. class AioRpcError(grpc.RpcError):
  51. """An implementation of RpcError to be used by the asynchronous API.
  52. Raised RpcError is a snapshot of the final status of the RPC, values are
  53. determined. Hence, its methods no longer needs to be coroutines.
  54. """
  55. _code: grpc.StatusCode
  56. _details: Optional[str]
  57. _initial_metadata: Optional[Metadata]
  58. _trailing_metadata: Optional[Metadata]
  59. _debug_error_string: Optional[str]
  60. def __init__(self,
  61. code: grpc.StatusCode,
  62. initial_metadata: Metadata,
  63. trailing_metadata: Metadata,
  64. details: Optional[str] = None,
  65. debug_error_string: Optional[str] = None) -> None:
  66. """Constructor.
  67. Args:
  68. code: The status code with which the RPC has been finalized.
  69. details: Optional details explaining the reason of the error.
  70. initial_metadata: Optional initial metadata that could be sent by the
  71. Server.
  72. trailing_metadata: Optional metadata that could be sent by the Server.
  73. """
  74. super().__init__()
  75. self._code = code
  76. self._details = details
  77. self._initial_metadata = initial_metadata
  78. self._trailing_metadata = trailing_metadata
  79. self._debug_error_string = debug_error_string
  80. def code(self) -> grpc.StatusCode:
  81. """Accesses the status code sent by the server.
  82. Returns:
  83. The `grpc.StatusCode` status code.
  84. """
  85. return self._code
  86. def details(self) -> Optional[str]:
  87. """Accesses the details sent by the server.
  88. Returns:
  89. The description of the error.
  90. """
  91. return self._details
  92. def initial_metadata(self) -> Metadata:
  93. """Accesses the initial metadata sent by the server.
  94. Returns:
  95. The initial metadata received.
  96. """
  97. return self._initial_metadata
  98. def trailing_metadata(self) -> Metadata:
  99. """Accesses the trailing metadata sent by the server.
  100. Returns:
  101. The trailing metadata received.
  102. """
  103. return self._trailing_metadata
  104. def debug_error_string(self) -> str:
  105. """Accesses the debug error string sent by the server.
  106. Returns:
  107. The debug error string received.
  108. """
  109. return self._debug_error_string
  110. def _repr(self) -> str:
  111. """Assembles the error string for the RPC error."""
  112. return _NON_OK_CALL_REPRESENTATION.format(self.__class__.__name__,
  113. self._code, self._details,
  114. self._debug_error_string)
  115. def __repr__(self) -> str:
  116. return self._repr()
  117. def __str__(self) -> str:
  118. return self._repr()
  119. def _create_rpc_error(initial_metadata: Metadata,
  120. status: cygrpc.AioRpcStatus) -> AioRpcError:
  121. return AioRpcError(
  122. _common.CYGRPC_STATUS_CODE_TO_STATUS_CODE[status.code()],
  123. Metadata.from_tuple(initial_metadata),
  124. Metadata.from_tuple(status.trailing_metadata()),
  125. details=status.details(),
  126. debug_error_string=status.debug_error_string(),
  127. )
  128. class Call:
  129. """Base implementation of client RPC Call object.
  130. Implements logic around final status, metadata and cancellation.
  131. """
  132. _loop: asyncio.AbstractEventLoop
  133. _code: grpc.StatusCode
  134. _cython_call: cygrpc._AioCall
  135. _metadata: Tuple[MetadatumType, ...]
  136. _request_serializer: SerializingFunction
  137. _response_deserializer: DeserializingFunction
  138. def __init__(self, cython_call: cygrpc._AioCall, metadata: Metadata,
  139. request_serializer: SerializingFunction,
  140. response_deserializer: DeserializingFunction,
  141. loop: asyncio.AbstractEventLoop) -> None:
  142. self._loop = loop
  143. self._cython_call = cython_call
  144. self._metadata = tuple(metadata)
  145. self._request_serializer = request_serializer
  146. self._response_deserializer = response_deserializer
  147. def __del__(self) -> None:
  148. # The '_cython_call' object might be destructed before Call object
  149. if hasattr(self, '_cython_call'):
  150. if not self._cython_call.done():
  151. self._cancel(_GC_CANCELLATION_DETAILS)
  152. def cancelled(self) -> bool:
  153. return self._cython_call.cancelled()
  154. def _cancel(self, details: str) -> bool:
  155. """Forwards the application cancellation reasoning."""
  156. if not self._cython_call.done():
  157. self._cython_call.cancel(details)
  158. return True
  159. else:
  160. return False
  161. def cancel(self) -> bool:
  162. return self._cancel(_LOCAL_CANCELLATION_DETAILS)
  163. def done(self) -> bool:
  164. return self._cython_call.done()
  165. def add_done_callback(self, callback: DoneCallbackType) -> None:
  166. cb = partial(callback, self)
  167. self._cython_call.add_done_callback(cb)
  168. def time_remaining(self) -> Optional[float]:
  169. return self._cython_call.time_remaining()
  170. async def initial_metadata(self) -> Metadata:
  171. raw_metadata_tuple = await self._cython_call.initial_metadata()
  172. return Metadata.from_tuple(raw_metadata_tuple)
  173. async def trailing_metadata(self) -> Metadata:
  174. raw_metadata_tuple = (await
  175. self._cython_call.status()).trailing_metadata()
  176. return Metadata.from_tuple(raw_metadata_tuple)
  177. async def code(self) -> grpc.StatusCode:
  178. cygrpc_code = (await self._cython_call.status()).code()
  179. return _common.CYGRPC_STATUS_CODE_TO_STATUS_CODE[cygrpc_code]
  180. async def details(self) -> str:
  181. return (await self._cython_call.status()).details()
  182. async def debug_error_string(self) -> str:
  183. return (await self._cython_call.status()).debug_error_string()
  184. async def _raise_for_status(self) -> None:
  185. if self._cython_call.is_locally_cancelled():
  186. raise asyncio.CancelledError()
  187. code = await self.code()
  188. if code != grpc.StatusCode.OK:
  189. raise _create_rpc_error(await self.initial_metadata(), await
  190. self._cython_call.status())
  191. def _repr(self) -> str:
  192. return repr(self._cython_call)
  193. def __repr__(self) -> str:
  194. return self._repr()
  195. def __str__(self) -> str:
  196. return self._repr()
  197. class _APIStyle(enum.IntEnum):
  198. UNKNOWN = 0
  199. ASYNC_GENERATOR = 1
  200. READER_WRITER = 2
  201. class _UnaryResponseMixin(Call):
  202. _call_response: asyncio.Task
  203. def _init_unary_response_mixin(self, response_task: asyncio.Task):
  204. self._call_response = response_task
  205. def cancel(self) -> bool:
  206. if super().cancel():
  207. self._call_response.cancel()
  208. return True
  209. else:
  210. return False
  211. def __await__(self) -> ResponseType:
  212. """Wait till the ongoing RPC request finishes."""
  213. try:
  214. response = yield from self._call_response
  215. except asyncio.CancelledError:
  216. # Even if we caught all other CancelledError, there is still
  217. # this corner case. If the application cancels immediately after
  218. # the Call object is created, we will observe this
  219. # `CancelledError`.
  220. if not self.cancelled():
  221. self.cancel()
  222. raise
  223. # NOTE(lidiz) If we raise RpcError in the task, and users doesn't
  224. # 'await' on it. AsyncIO will log 'Task exception was never retrieved'.
  225. # Instead, if we move the exception raising here, the spam stops.
  226. # Unfortunately, there can only be one 'yield from' in '__await__'. So,
  227. # we need to access the private instance variable.
  228. if response is cygrpc.EOF:
  229. if self._cython_call.is_locally_cancelled():
  230. raise asyncio.CancelledError()
  231. else:
  232. raise _create_rpc_error(self._cython_call._initial_metadata,
  233. self._cython_call._status)
  234. else:
  235. return response
  236. class _StreamResponseMixin(Call):
  237. _message_aiter: AsyncIterator[ResponseType]
  238. _preparation: asyncio.Task
  239. _response_style: _APIStyle
  240. def _init_stream_response_mixin(self, preparation: asyncio.Task):
  241. self._message_aiter = None
  242. self._preparation = preparation
  243. self._response_style = _APIStyle.UNKNOWN
  244. def _update_response_style(self, style: _APIStyle):
  245. if self._response_style is _APIStyle.UNKNOWN:
  246. self._response_style = style
  247. elif self._response_style is not style:
  248. raise cygrpc.UsageError(_API_STYLE_ERROR)
  249. def cancel(self) -> bool:
  250. if super().cancel():
  251. self._preparation.cancel()
  252. return True
  253. else:
  254. return False
  255. async def _fetch_stream_responses(self) -> ResponseType:
  256. message = await self._read()
  257. while message is not cygrpc.EOF:
  258. yield message
  259. message = await self._read()
  260. # If the read operation failed, Core should explain why.
  261. await self._raise_for_status()
  262. def __aiter__(self) -> AsyncIterator[ResponseType]:
  263. self._update_response_style(_APIStyle.ASYNC_GENERATOR)
  264. if self._message_aiter is None:
  265. self._message_aiter = self._fetch_stream_responses()
  266. return self._message_aiter
  267. async def _read(self) -> ResponseType:
  268. # Wait for the request being sent
  269. await self._preparation
  270. # Reads response message from Core
  271. try:
  272. raw_response = await self._cython_call.receive_serialized_message()
  273. except asyncio.CancelledError:
  274. if not self.cancelled():
  275. self.cancel()
  276. raise
  277. if raw_response is cygrpc.EOF:
  278. return cygrpc.EOF
  279. else:
  280. return _common.deserialize(raw_response,
  281. self._response_deserializer)
  282. async def read(self) -> ResponseType:
  283. if self.done():
  284. await self._raise_for_status()
  285. return cygrpc.EOF
  286. self._update_response_style(_APIStyle.READER_WRITER)
  287. response_message = await self._read()
  288. if response_message is cygrpc.EOF:
  289. # If the read operation failed, Core should explain why.
  290. await self._raise_for_status()
  291. return response_message
  292. class _StreamRequestMixin(Call):
  293. _metadata_sent: asyncio.Event
  294. _done_writing_flag: bool
  295. _async_request_poller: Optional[asyncio.Task]
  296. _request_style: _APIStyle
  297. def _init_stream_request_mixin(
  298. self, request_iterator: Optional[RequestIterableType]):
  299. self._metadata_sent = asyncio.Event()
  300. self._done_writing_flag = False
  301. # If user passes in an async iterator, create a consumer Task.
  302. if request_iterator is not None:
  303. self._async_request_poller = self._loop.create_task(
  304. self._consume_request_iterator(request_iterator))
  305. self._request_style = _APIStyle.ASYNC_GENERATOR
  306. else:
  307. self._async_request_poller = None
  308. self._request_style = _APIStyle.READER_WRITER
  309. def _raise_for_different_style(self, style: _APIStyle):
  310. if self._request_style is not style:
  311. raise cygrpc.UsageError(_API_STYLE_ERROR)
  312. def cancel(self) -> bool:
  313. if super().cancel():
  314. if self._async_request_poller is not None:
  315. self._async_request_poller.cancel()
  316. return True
  317. else:
  318. return False
  319. def _metadata_sent_observer(self):
  320. self._metadata_sent.set()
  321. async def _consume_request_iterator(
  322. self, request_iterator: RequestIterableType) -> None:
  323. try:
  324. if inspect.isasyncgen(request_iterator) or hasattr(
  325. request_iterator, '__aiter__'):
  326. async for request in request_iterator:
  327. try:
  328. await self._write(request)
  329. except AioRpcError as rpc_error:
  330. _LOGGER.debug(
  331. 'Exception while consuming the request_iterator: %s',
  332. rpc_error)
  333. return
  334. else:
  335. for request in request_iterator:
  336. try:
  337. await self._write(request)
  338. except AioRpcError as rpc_error:
  339. _LOGGER.debug(
  340. 'Exception while consuming the request_iterator: %s',
  341. rpc_error)
  342. return
  343. await self._done_writing()
  344. except: # pylint: disable=bare-except
  345. # Client iterators can raise exceptions, which we should handle by
  346. # cancelling the RPC and logging the client's error. No exceptions
  347. # should escape this function.
  348. _LOGGER.debug('Client request_iterator raised exception:\n%s',
  349. traceback.format_exc())
  350. self.cancel()
  351. async def _write(self, request: RequestType) -> None:
  352. if self.done():
  353. raise asyncio.InvalidStateError(_RPC_ALREADY_FINISHED_DETAILS)
  354. if self._done_writing_flag:
  355. raise asyncio.InvalidStateError(_RPC_HALF_CLOSED_DETAILS)
  356. if not self._metadata_sent.is_set():
  357. await self._metadata_sent.wait()
  358. if self.done():
  359. await self._raise_for_status()
  360. serialized_request = _common.serialize(request,
  361. self._request_serializer)
  362. try:
  363. await self._cython_call.send_serialized_message(serialized_request)
  364. except cygrpc.InternalError:
  365. await self._raise_for_status()
  366. except asyncio.CancelledError:
  367. if not self.cancelled():
  368. self.cancel()
  369. raise
  370. async def _done_writing(self) -> None:
  371. if self.done():
  372. # If the RPC is finished, do nothing.
  373. return
  374. if not self._done_writing_flag:
  375. # If the done writing is not sent before, try to send it.
  376. self._done_writing_flag = True
  377. try:
  378. await self._cython_call.send_receive_close()
  379. except asyncio.CancelledError:
  380. if not self.cancelled():
  381. self.cancel()
  382. raise
  383. async def write(self, request: RequestType) -> None:
  384. self._raise_for_different_style(_APIStyle.READER_WRITER)
  385. await self._write(request)
  386. async def done_writing(self) -> None:
  387. """Signal peer that client is done writing.
  388. This method is idempotent.
  389. """
  390. self._raise_for_different_style(_APIStyle.READER_WRITER)
  391. await self._done_writing()
  392. async def wait_for_connection(self) -> None:
  393. await self._metadata_sent.wait()
  394. if self.done():
  395. await self._raise_for_status()
  396. class UnaryUnaryCall(_UnaryResponseMixin, Call, _base_call.UnaryUnaryCall):
  397. """Object for managing unary-unary RPC calls.
  398. Returned when an instance of `UnaryUnaryMultiCallable` object is called.
  399. """
  400. _request: RequestType
  401. _invocation_task: asyncio.Task
  402. # pylint: disable=too-many-arguments
  403. def __init__(self, request: RequestType, deadline: Optional[float],
  404. metadata: Metadata,
  405. credentials: Optional[grpc.CallCredentials],
  406. wait_for_ready: Optional[bool], channel: cygrpc.AioChannel,
  407. method: bytes, request_serializer: SerializingFunction,
  408. response_deserializer: DeserializingFunction,
  409. loop: asyncio.AbstractEventLoop) -> None:
  410. super().__init__(
  411. channel.call(method, deadline, credentials, wait_for_ready),
  412. metadata, request_serializer, response_deserializer, loop)
  413. self._request = request
  414. self._invocation_task = loop.create_task(self._invoke())
  415. self._init_unary_response_mixin(self._invocation_task)
  416. async def _invoke(self) -> ResponseType:
  417. serialized_request = _common.serialize(self._request,
  418. self._request_serializer)
  419. # NOTE(lidiz) asyncio.CancelledError is not a good transport for status,
  420. # because the asyncio.Task class do not cache the exception object.
  421. # https://github.com/python/cpython/blob/edad4d89e357c92f70c0324b937845d652b20afd/Lib/asyncio/tasks.py#L785
  422. try:
  423. serialized_response = await self._cython_call.unary_unary(
  424. serialized_request, self._metadata)
  425. except asyncio.CancelledError:
  426. if not self.cancelled():
  427. self.cancel()
  428. if self._cython_call.is_ok():
  429. return _common.deserialize(serialized_response,
  430. self._response_deserializer)
  431. else:
  432. return cygrpc.EOF
  433. async def wait_for_connection(self) -> None:
  434. await self._invocation_task
  435. if self.done():
  436. await self._raise_for_status()
  437. class UnaryStreamCall(_StreamResponseMixin, Call, _base_call.UnaryStreamCall):
  438. """Object for managing unary-stream RPC calls.
  439. Returned when an instance of `UnaryStreamMultiCallable` object is called.
  440. """
  441. _request: RequestType
  442. _send_unary_request_task: asyncio.Task
  443. # pylint: disable=too-many-arguments
  444. def __init__(self, request: RequestType, deadline: Optional[float],
  445. metadata: Metadata,
  446. credentials: Optional[grpc.CallCredentials],
  447. wait_for_ready: Optional[bool], channel: cygrpc.AioChannel,
  448. method: bytes, request_serializer: SerializingFunction,
  449. response_deserializer: DeserializingFunction,
  450. loop: asyncio.AbstractEventLoop) -> None:
  451. super().__init__(
  452. channel.call(method, deadline, credentials, wait_for_ready),
  453. metadata, request_serializer, response_deserializer, loop)
  454. self._request = request
  455. self._send_unary_request_task = loop.create_task(
  456. self._send_unary_request())
  457. self._init_stream_response_mixin(self._send_unary_request_task)
  458. async def _send_unary_request(self) -> ResponseType:
  459. serialized_request = _common.serialize(self._request,
  460. self._request_serializer)
  461. try:
  462. await self._cython_call.initiate_unary_stream(
  463. serialized_request, self._metadata)
  464. except asyncio.CancelledError:
  465. if not self.cancelled():
  466. self.cancel()
  467. raise
  468. async def wait_for_connection(self) -> None:
  469. await self._send_unary_request_task
  470. if self.done():
  471. await self._raise_for_status()
  472. class StreamUnaryCall(_StreamRequestMixin, _UnaryResponseMixin, Call,
  473. _base_call.StreamUnaryCall):
  474. """Object for managing stream-unary RPC calls.
  475. Returned when an instance of `StreamUnaryMultiCallable` object is called.
  476. """
  477. # pylint: disable=too-many-arguments
  478. def __init__(self, request_iterator: Optional[RequestIterableType],
  479. deadline: Optional[float], metadata: Metadata,
  480. credentials: Optional[grpc.CallCredentials],
  481. wait_for_ready: Optional[bool], channel: cygrpc.AioChannel,
  482. method: bytes, request_serializer: SerializingFunction,
  483. response_deserializer: DeserializingFunction,
  484. loop: asyncio.AbstractEventLoop) -> None:
  485. super().__init__(
  486. channel.call(method, deadline, credentials, wait_for_ready),
  487. metadata, request_serializer, response_deserializer, loop)
  488. self._init_stream_request_mixin(request_iterator)
  489. self._init_unary_response_mixin(loop.create_task(self._conduct_rpc()))
  490. async def _conduct_rpc(self) -> ResponseType:
  491. try:
  492. serialized_response = await self._cython_call.stream_unary(
  493. self._metadata, self._metadata_sent_observer)
  494. except asyncio.CancelledError:
  495. if not self.cancelled():
  496. self.cancel()
  497. raise
  498. if self._cython_call.is_ok():
  499. return _common.deserialize(serialized_response,
  500. self._response_deserializer)
  501. else:
  502. return cygrpc.EOF
  503. class StreamStreamCall(_StreamRequestMixin, _StreamResponseMixin, Call,
  504. _base_call.StreamStreamCall):
  505. """Object for managing stream-stream RPC calls.
  506. Returned when an instance of `StreamStreamMultiCallable` object is called.
  507. """
  508. _initializer: asyncio.Task
  509. # pylint: disable=too-many-arguments
  510. def __init__(self, request_iterator: Optional[RequestIterableType],
  511. deadline: Optional[float], metadata: Metadata,
  512. credentials: Optional[grpc.CallCredentials],
  513. wait_for_ready: Optional[bool], channel: cygrpc.AioChannel,
  514. method: bytes, request_serializer: SerializingFunction,
  515. response_deserializer: DeserializingFunction,
  516. loop: asyncio.AbstractEventLoop) -> None:
  517. super().__init__(
  518. channel.call(method, deadline, credentials, wait_for_ready),
  519. metadata, request_serializer, response_deserializer, loop)
  520. self._initializer = self._loop.create_task(self._prepare_rpc())
  521. self._init_stream_request_mixin(request_iterator)
  522. self._init_stream_response_mixin(self._initializer)
  523. async def _prepare_rpc(self):
  524. """This method prepares the RPC for receiving/sending messages.
  525. All other operations around the stream should only happen after the
  526. completion of this method.
  527. """
  528. try:
  529. await self._cython_call.initiate_stream_stream(
  530. self._metadata, self._metadata_sent_observer)
  531. except asyncio.CancelledError:
  532. if not self.cancelled():
  533. self.cancel()
  534. # No need to raise RpcError here, because no one will `await` this task.