Skip to content

Commit 391ffb1

Browse files
committed
async persist tryout
1 parent 15d733b commit 391ffb1

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

lightning/src/util/async_persist.rs

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
use ::futures::task::noop_waker;
2+
use futures_timer::Delay;
3+
use tokio::runtime::Runtime;
4+
use std::future::Future;
5+
use std::task::{Context, Poll};
6+
use std::time::Duration;
7+
8+
#[derive(Debug)]
9+
pub enum UpdateStatus {
10+
Completed,
11+
InProgress,
12+
}
13+
14+
async fn store() {
15+
// Remove delay to simulate immediate completion.
16+
Delay::new(Duration::from_secs(1)).await;
17+
18+
println!("Storing data...");
19+
}
20+
21+
struct AsyncKVStoreWrapper {
22+
runtime: Runtime,
23+
}
24+
25+
impl AsyncKVStoreWrapper {
26+
fn store<F>(&self, callback: F) -> UpdateStatus
27+
where
28+
F: FnOnce() + Send + 'static,
29+
{
30+
let mut fut = Box::pin(store());
31+
32+
let waker = noop_waker();
33+
let mut cx = Context::from_waker(&waker);
34+
35+
match fut.as_mut().poll(&mut cx) {
36+
Poll::Ready(_) => {
37+
UpdateStatus::Completed
38+
}
39+
Poll::Pending => {
40+
println!("Future not ready, using tokio runtime");
41+
42+
self.runtime.spawn(async move {
43+
fut.await;
44+
callback();
45+
});
46+
47+
UpdateStatus::InProgress
48+
}
49+
}
50+
}
51+
}
52+
53+
fn main() {
54+
let async_kv_store = AsyncKVStoreWrapper {
55+
runtime: Runtime::new().unwrap(),
56+
};
57+
58+
let status = async_kv_store.store(|| {
59+
println!("Callback: Store operation completed!");
60+
});
61+
62+
println!("Store status: {:?}", status);
63+
64+
// Sleep to give async task time to complete before main exits
65+
std::thread::sleep(Duration::from_secs(2));
66+
}

0 commit comments

Comments
 (0)