Skip to content

Commit faa071d

Browse files
committed
async persist tryout
1 parent 15d733b commit faa071d

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

lightning/src/util/async_persist.rs

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
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+
// Use this boolean to control whether the store operation is async or sync.
15+
const ASYNC_STORE: bool = true;
16+
17+
// Simulate an async store operation.
18+
async fn store() {
19+
if ASYNC_STORE {
20+
Delay::new(Duration::from_secs(1)).await;
21+
} else {
22+
std::thread::sleep(Duration::from_secs(1));
23+
}
24+
25+
println!("Stored data...");
26+
}
27+
28+
struct AsyncKVStoreWrapper {
29+
runtime: Runtime,
30+
}
31+
32+
impl AsyncKVStoreWrapper {
33+
fn store<F>(&self, callback: F) -> UpdateStatus
34+
where
35+
F: FnOnce() + Send + 'static,
36+
{
37+
let mut fut = Box::pin(store());
38+
39+
let waker = noop_waker();
40+
let mut cx = Context::from_waker(&waker);
41+
42+
match fut.as_mut().poll(&mut cx) {
43+
Poll::Ready(_) => {
44+
UpdateStatus::Completed
45+
}
46+
Poll::Pending => {
47+
println!("Future not ready, using tokio runtime");
48+
49+
self.runtime.spawn(async move {
50+
fut.await;
51+
callback();
52+
});
53+
54+
UpdateStatus::InProgress
55+
}
56+
}
57+
}
58+
}
59+
60+
fn main() {
61+
let async_kv_store = AsyncKVStoreWrapper {
62+
runtime: Runtime::new().unwrap(),
63+
};
64+
65+
let status = async_kv_store.store(|| {
66+
println!("Callback: Store operation completed!");
67+
68+
// Call channel_monitor_updated here.
69+
});
70+
71+
println!("Store status: {:?}", status);
72+
73+
// Sleep to give async task time to complete before main exits
74+
std::thread::sleep(Duration::from_secs(2));
75+
}

0 commit comments

Comments
 (0)