mlua_isle/task.rs
1//! Task handle — a cancellable future for a single Lua operation.
2//!
3//! A [`Task`] is returned by [`Isle::spawn_eval`], [`Isle::spawn_call`],
4//! and [`Isle::spawn_exec`].
5//! It provides a [`CancelToken`] for interruption and a blocking
6//! [`wait`](Task::wait) method to collect the result.
7
8use crate::error::IsleError;
9use crate::hook::CancelToken;
10use std::sync::mpsc;
11
12/// Handle to a pending Lua operation.
13///
14/// The operation runs on the Lua thread. The caller can:
15/// - [`wait`](Task::wait) for the result (blocking).
16/// - [`cancel`](Task::cancel) the operation.
17/// - [`try_recv`](Task::try_recv) to poll without blocking.
18///
19/// Dropping a `Task` before its result was received **cancels** the
20/// operation. Call [`detach`](Task::detach) to let it run to completion
21/// without keeping the handle.
22#[must_use = "dropping a Task cancels the operation; use `.detach()` to let it run"]
23pub struct Task<T = String> {
24 rx: mpsc::Receiver<Result<T, IsleError>>,
25 cancel: CancelToken,
26 /// Result received or detached: dropping must not cancel.
27 released: std::cell::Cell<bool>,
28}
29
30impl<T> Task<T> {
31 pub(crate) fn new(rx: mpsc::Receiver<Result<T, IsleError>>, cancel: CancelToken) -> Self {
32 Self {
33 rx,
34 cancel,
35 released: std::cell::Cell::new(false),
36 }
37 }
38
39 /// Block until the result is available.
40 pub fn wait(self) -> Result<T, IsleError> {
41 let result = self.rx.recv();
42 self.released.set(true);
43 result.map_err(|e| IsleError::RecvFailed(e.to_string()))?
44 }
45
46 /// Let the operation run to completion without this handle.
47 ///
48 /// The result is discarded. The operation can still be cancelled
49 /// through a clone of its [`cancel_token`](Self::cancel_token).
50 pub fn detach(self) {
51 self.released.set(true);
52 }
53
54 /// Cancel the operation.
55 ///
56 /// This signals the Lua debug hook to interrupt execution.
57 /// The task will eventually return [`IsleError::Cancelled`].
58 pub fn cancel(&self) {
59 self.cancel.cancel();
60 }
61
62 /// Non-blocking poll for the result.
63 pub fn try_recv(&self) -> Option<Result<T, IsleError>> {
64 let result = self.rx.try_recv().ok();
65 if result.is_some() {
66 self.released.set(true);
67 }
68 result
69 }
70
71 /// Access the cancel token (e.g. to share with other code).
72 pub fn cancel_token(&self) -> &CancelToken {
73 &self.cancel
74 }
75}
76
77impl<T> Drop for Task<T> {
78 fn drop(&mut self) {
79 if !self.released.get() {
80 self.cancel.cancel();
81 }
82 }
83}