stoppable_task.rs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use async_std::sync::Arc;
  19. use futures::{Future, FutureExt};
  20. use smol::Executor;
  21. pub type StoppableTaskPtr = Arc<StoppableTask>;
  22. pub struct StoppableTask {
  23. stop_send: smol::channel::Sender<()>,
  24. stop_recv: smol::channel::Receiver<()>,
  25. }
  26. impl StoppableTask {
  27. pub fn new() -> Arc<Self> {
  28. let (stop_send, stop_recv) = smol::channel::unbounded();
  29. Arc::new(Self { stop_send, stop_recv })
  30. }
  31. pub async fn stop(&self) {
  32. // Ignore any errors from this send
  33. let _ = self.stop_send.send(()).await;
  34. }
  35. pub fn start<'a, MainFut, StopFut, StopFn, Error>(
  36. self: Arc<Self>,
  37. main: MainFut,
  38. stop_handler: StopFn,
  39. stop_value: Error,
  40. executor: Arc<Executor<'a>>,
  41. ) where
  42. MainFut: Future<Output = std::result::Result<(), Error>> + Send + 'a,
  43. StopFut: Future<Output = ()> + Send,
  44. StopFn: FnOnce(std::result::Result<(), Error>) -> StopFut + Send + 'a,
  45. Error: std::error::Error + Send + 'a,
  46. {
  47. executor
  48. .spawn(async move {
  49. let result = futures::select! {
  50. _ = self.stop_recv.recv().fuse() => Err(stop_value),
  51. result = main.fuse() => result
  52. };
  53. stop_handler(result).await;
  54. })
  55. .detach();
  56. }
  57. }