Housekeeping when client disconnects

30 views
Skip to first unread message

Eric Chamberlain

unread,
Feb 24, 2022, 10:00:47 AM2/24/22
to grpc.io
I have a Python (3.9) server using grpclib (0.4.2). I need to be able to perform some housekeeping after a client disconnects. I can't seem to find any API (https://grpclib.readthedocs.io/en/latest/server.html) related to this.

I can see that the client sends "cancel". Reading the code (https://github.com/vmagamedov/grpclib/blob/39cc61ad45cd3be15ec464fdefab31b9f4f23918/grpclib/server.py) it looks like it simply logs a message but no additional action takes place.

In theory I'm assuming that gRPC allows for a server to know when a client disconnects. Perhaps I need to add this functionality in this library?

This seems like a very common thing, and yet, all of the questions I have seen related to this say "you can't do it" or "you can do it this way" but there's no corresponding API call in the library I'm using.

I would greatly appreciate any help *bows*

Asheley Shawn Lee

unread,
Feb 28, 2022, 4:51:37 PM2/28/22
to grpc.io

How I handle client disconnects is by using a callback on the RPC method and utilize the context to keep track of which client it is.

class Service(ServiceServicer):
    def context_callback(self, context: grpc.ServicerContext):
        def callback():
            # Cleanup code here
            cleanup_with_context(context)
        return callback
   
    def DoJob(self, work_pb: Work, context: grpc.ServicerContext):
        context.add_callback(self.context_callback(context))
        # Job code here.


Not sure this is the 100% way to do it but this is how I'm able to do it.

Reply all
Reply to author
Forward
0 new messages