1

I have written a small web application using actix-web. As part of starting the application I'm taking a resource and passing it in as part of the app_data for the HttpServer App.

I want to clean up the resource when the application exits (through SIGTERM or SIGINT). The clean-up needs to call an async function, so I cannot do the clean-up by implementing Drop.

Is there a way to add a hook/handler to actix_web, that runs as part of the shutdown?

thomasa88
  • 630
  • 1
  • 4
  • 8
  • Why does a function being `async` prevent you using it in `Drop` every program starts out as a synchronous call to `main` (even if it's sometimes hidden behind some macros)? – cafce25 Aug 07 '23 at 09:10
  • I don't have the compiler error in front of me, but [drop cannot be async](https://stackoverflow.com/questions/59782278/how-do-i-implement-an-async-drop-in-rust). Tried variants of calling to tokio::runtime in `drop()`. At least `tokio::runtime::Handle::current().spawn(self.stop())` complained with `borrowed data escapes outside of method`. The function I'm trying to call is `async fn stop(&mut self)`. – thomasa88 Aug 07 '23 at 09:34
  • 2
    You can add a signal handler, that will stop http server and then you can manually free your resources. – Aleksander Krauze Aug 07 '23 at 09:39
  • Of course you have to `block_on` the future you want completed in `drop` otherwise I don't see why it shouldn't be possible. – cafce25 Aug 07 '23 at 09:44
  • @cafce25 I had forgotten what error I got when I tried that. I reproduced it in the playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021 Error: "thread 'main' panicked at 'Cannot start a runtime from within a runtime. This happens because a function (like `block_on`) attempted to block the current thread while the thread is being used to drive asynchronous tasks.', src/main.rs:17:12" – thomasa88 Aug 07 '23 at 11:57

0 Answers0