socketry / async

An awesome asynchronous event-driven reactor for Ruby.
MIT License
2.04k stars 85 forks source link

Introduce `Async::Task#defer_stop` #310

Closed ioquatix closed 3 months ago

ioquatix commented 3 months ago

Introduce Async::Task#defer_stop{} which can be used to implement graceful shutdown.

In a typical client server architecture, it's common for a server process to handle discrete requests. When it is time to shut down, we should try to terminate after finishing the response.

Async uses Async::Task#stop to request a sub-system to exit. Exiting while writing a response or closing a connection is more likely to cause problems for the client. By deferring stop, we enable services to implement graceful shutdown timeout.

def run_server
  Sync do |task|
    while request = read_request
      task.defer_stop do
        response = generate_response
        write_response(response)
      end
    end
  end
end

See https://github.com/socketry/async-http/pull/153 for proposed usage.

Types of Changes

Contribution