From 69d71d65885e1e31efca17930cd4058e07ec5456 Mon Sep 17 00:00:00 2001 From: jank Date: Wed, 21 Aug 2024 15:55:25 +0200 Subject: [PATCH] Add ability to run async functions in blocking mode --- examples/hello_world.rs | 8 ++++++-- src/utilities/async_block.rs | 12 ++++++++++++ src/utilities/mod.rs | 1 + 3 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 src/utilities/async_block.rs diff --git a/examples/hello_world.rs b/examples/hello_world.rs index 8227d0c..6ae4643 100644 --- a/examples/hello_world.rs +++ b/examples/hello_world.rs @@ -1,9 +1,12 @@ -use std::{collections::HashMap, sync::Arc}; +use std::{collections::HashMap, sync::Arc, thread::sleep, time::Duration}; -use loadstar::{controller::Controller, entities::request::Url, router::Router, template::Template, utilities::responses::{respond_not_found, respond_template}}; +use loadstar::{controller::Controller, entities::request::Url, router::Router, template::Template, utilities::{async_block::run_async, responses::{respond_not_found, respond_template}}}; use maud::html; use tiny_http::Request; +async fn example_async() { + sleep(Duration::from_secs(1)); +} struct MainRouter { routes: HashMap @@ -42,6 +45,7 @@ struct MainController; impl MainController { fn index_route(request: Request) { + run_async(example_async()); respond_template(request, MainTemplate {}) } } diff --git a/src/utilities/async_block.rs b/src/utilities/async_block.rs new file mode 100644 index 0000000..1c6b305 --- /dev/null +++ b/src/utilities/async_block.rs @@ -0,0 +1,12 @@ +use std::future::Future; + + +pub fn run_async(async_operation: impl Future) -> T { + // Use `block_in_place` to ensure runtime is dropped in a blocking context + tokio::task::block_in_place(|| { + // Get the current Tokio runtime handle + let handle = tokio::runtime::Handle::current(); + // Run the async operation using the handle and wait for it to complete + handle.block_on(async_operation) + }) +} diff --git a/src/utilities/mod.rs b/src/utilities/mod.rs index b396b03..ac00999 100644 --- a/src/utilities/mod.rs +++ b/src/utilities/mod.rs @@ -1 +1,2 @@ pub mod responses; +pub mod async_block;