In python asyncio grpc server, handling a client-triggered cancellation of an RPC on the server-side

508 views
Skip to first unread message

Brunston

unread,
Jul 22, 2021, 5:51:03 PM7/22/21
to grpc.io
Hi all! I have a question about a Python asyncio gRPC server:

How can I perform some server-side action (eg, cleanup) based on a cancellation of an RPC from the client?

In my microservice, I have an asyncio gRPC server whose main RPCs are bidirectional streams.

On the client side (which is also using asyncio), when I cancel something, it raises an asyncio.CancelledError which is caught and not reraised by the grpc core:

https://github.com/grpc/grpc/blob/master/src/python/grpcio/grpc/_cython/_cygrpc/aio/server.pyx.pxi#L679

except asyncio.CancelledError: _LOGGER.debug('RPC cancelled for servicer method [%s]', _decode(rpc_state.method()))

So I cannot rely on catching the asyncio.CancelledError in my own code, because it's caught beforehand and not reraised.

The shared context is supposed to contain information as to whether the RPC was canceled on the client side, by calling .cancel() from the RPC call and being able to see if it was canceled by calling .cancelled():

https://grpc.github.io/grpc/python/grpc_asyncio.html#shared-context

abstract cancel()

Cancels the RPC. Idempotent and has no effect if the RPC has already terminated. Returns A bool indicates if the cancellation is performed or not. Return type bool

abstract cancelled()

Return True if the RPC is cancelled. The RPC is cancelled when the cancellation was requested with cancel(). Returns A bool indicates whether the RPC is cancelled or not. Return type bool

However, this shared context is not attached to the context variable given to the RPC on the server side by the gRPC generated code. (I cannot run context.cancelled() or context.add_done_callback; they're not present)

Thoughts? Much appreciated!

-Brunston

Brunston

unread,
Jul 22, 2021, 6:41:11 PM7/22/21
to grpc.io
...Turns out you can catch the asyncio.CancelledError raised by grpc core. That should work for my current usecase. Any other suggestions that can shed light on the shared context would still be helpful!
Brunston

Lidi Zheng

unread,
Jul 28, 2021, 6:15:32 PM7/28/21
to grpc.io
Adding the SO link for this question: https://stackoverflow.com/questions/68491834/handle-client-side-cancellation-in-grpc-python-asyncio

In case new discussions happen there.

Message has been deleted
Message has been deleted

Harvey Liu

unread,
Jun 20, 2024, 5:35:36 AM (13 days ago) Jun 20
to grpc.io
is this issue fixed? i used 
grpcio==1.64.0
grpcio-status==1.64.0
grpcio-tools==1.64.0
protobuf==5.27.1

but i can still not get canceled status on the server side....
Reply all
Reply to author
Forward
0 new messages