guzba / mummy

An HTTP and WebSocket server for Nim that returns to the ancient ways of threads.
MIT License
281 stars 11 forks source link

q: Any way to detect that client is disconnected in a request handler? #123

Closed armed closed 2 months ago

armed commented 2 months ago

Hi, nim noob here.

I've a simple server which makes long running request to a DB which supports cancellation.

  1. Client calls /report?timeout=10 api with a timeout
  2. Server handler makes request to the DB (in a separate thread).
  3. Client cancels the request at any time within timeout.
  4. Server must detect that and cancel DB request.

At the moment server waits until timeout and then prints error Dropped response to disconnected client and db connection is terminated.

I've been using http server in Clojure, it has builtin abort detection mechanism as a part of request body. I'm testing mummy fork with a proc which basically does this check request.clientSocket in server.selector and returns boolean.

# mummy module
proc connectionAlive*(request: Request): bool =
  request.clientSocket in request.server.selector

Maybe there is a better way?

guzba commented 2 months ago

This is pretty difficult question to answer.

It is not safe to look at the server selector as that is not a locked / thread-safe resource to observe from request threads. Disconnects treated as request cancellation is not something Mummy is built to respect or even consider since that is pretty unusual in my opinion.

This is not a scenario I have examples for nor can I easily explain how to accomplish this since I do not know how the request thread blocking on a DB call could get interrupted, etc. Mummy may not be a good option for this way of implementing things.

guzba commented 2 months ago

If you are open to alternative solutions, I suggest looking at the BigQuery HTTP API: https://cloud.google.com/bigquery/docs/reference/rest

You can have a "start query" call, a "cancel" call, and a "poll results" call. This avoids long-lived connection-state-sensitive stuff, and just has simple light-weight API calls.