stoppable_task.rs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. #[derive(Debug)]
  23. pub struct StoppableTask {
  24. stop_send: smol::channel::Sender<()>,
  25. stop_recv: smol::channel::Receiver<()>,
  26. }
  27. impl StoppableTask {
  28. pub fn new() -> Arc<Self> {
  29. let (stop_send, stop_recv) = smol::channel::unbounded();
  30. Arc::new(Self { stop_send, stop_recv })
  31. }
  32. pub async fn stop(&self) {
  33. // Ignore any errors from this send
  34. let _ = self.stop_send.send(()).await;
  35. }
  36. pub fn start<'a, MainFut, StopFut, StopFn, Error>(
  37. self: Arc<Self>,
  38. main: MainFut,
  39. stop_handler: StopFn,
  40. stop_value: Error,
  41. executor: Arc<Executor<'a>>,
  42. ) where
  43. MainFut: Future<Output = std::result::Result<(), Error>> + Send + 'a,
  44. StopFut: Future<Output = ()> + Send,
  45. StopFn: FnOnce(std::result::Result<(), Error>) -> StopFut + Send + 'a,
  46. Error: std::error::Error + Send + 'a,
  47. {
  48. executor
  49. .spawn(async move {
  50. let result = futures::select! {
  51. _ = self.stop_recv.recv().fuse() => Err(stop_value),
  52. result = main.fuse() => result
  53. };
  54. stop_handler(result).await;
  55. })
  56. .detach();
  57. }
  58. }