Skip to content

Commit 373d339

Browse files
committed
add ctrl+c support for long running fn
1 parent 749fea1 commit 373d339

1 file changed

Lines changed: 45 additions & 5 deletions

File tree

src/lib.rs

Lines changed: 45 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ fn is_remote_path(path: &str) -> bool {
2121
#[pyfunction]
2222
#[pyo3(signature = (database, isolation_level="DEFERRED".to_string(), check_same_thread=true, uri=false, sync_url=None, auth_token=""))]
2323
fn connect(
24+
py: Python<'_>,
2425
database: String,
2526
isolation_level: Option<String>,
2627
check_same_thread: bool,
@@ -46,7 +47,23 @@ fn connect(
4647
None,
4748
None,
4849
);
49-
let result = rt.block_on(fut);
50+
println!("connecting");
51+
tokio::pin!(fut);
52+
let result = rt.block_on(check_signals(py, fut));
53+
// let result = rt.block_on(async {
54+
// loop {
55+
// tokio::select! {
56+
// out = &mut fut => {
57+
// break out;
58+
// }
59+
60+
// _ = tokio::time::sleep(std::time::Duration::from_millis(300)) => {
61+
// py.check_signals().unwrap();
62+
// }
63+
// }
64+
// }
65+
// });
66+
println!("done connecting");
5067
result.map_err(to_py_err)?
5168
}
5269
None => libsql_core::Database::open(database).map_err(to_py_err)?,
@@ -64,6 +81,23 @@ fn connect(
6481
})
6582
}
6683

84+
async fn check_signals<F, R>(py: Python<'_>, mut fut: std::pin::Pin<&mut F>) -> R
85+
where
86+
F: std::future::Future<Output = R>,
87+
{
88+
loop {
89+
tokio::select! {
90+
out = &mut fut => {
91+
break out;
92+
}
93+
94+
_ = tokio::time::sleep(std::time::Duration::from_millis(300)) => {
95+
py.check_signals().unwrap();
96+
}
97+
}
98+
}
99+
}
100+
67101
#[pyclass]
68102
pub struct Connection {
69103
db: libsql_core::Database,
@@ -91,8 +125,14 @@ impl Connection {
91125
})
92126
}
93127

94-
fn sync(self_: PyRef<'_, Self>) -> PyResult<()> {
95-
self_.rt.block_on(self_.db.sync()).map_err(to_py_err)?;
128+
fn sync(self_: PyRef<'_, Self>, py: Python<'_>) -> PyResult<()> {
129+
let fut = self_.db.sync();
130+
tokio::pin!(fut);
131+
132+
self_
133+
.rt
134+
.block_on(check_signals(py, fut))
135+
.map_err(to_py_err)?;
96136
Ok(())
97137
}
98138

@@ -254,11 +294,11 @@ impl Cursor {
254294
}
255295
None => {
256296
self_.done.replace(true);
257-
break
297+
break;
258298
}
259299
}
260300
}
261-
}
301+
}
262302
Ok(Some(PyList::new(self_.py(), elements)))
263303
}
264304
None => Ok(None),

0 commit comments

Comments
 (0)