recoverable_spawn/thread/
async.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
use super::{r#trait::*, r#type::*};
use once_cell::sync::Lazy;
use runtime::Runtime;
use std::sync::Arc;
use std::thread::{spawn, JoinHandle};
use task::JoinError;
use tokio::*;

static GLOBAL_RUNTIME: Lazy<Runtime> = Lazy::new(|| loop {
    match Runtime::new() {
        Ok(runtime) => return runtime,
        Err(_) => {}
    }
});

/// Executes a recoverable function within a panic-safe context.
///
/// - `func`: A function implementing the `AsyncRecoverableFunction` trait.
/// - Returns: A `AsyncSpawnResult` indicating the success or failure of the function execution.
#[inline]
pub fn run_function<F: AsyncRecoverableFunction>(func: F) -> AsyncSpawnResult {
    let res: Result<(), JoinError> = GLOBAL_RUNTIME.block_on(async move {
        let func = async move {
            func.call().await;
        };
        return tokio::spawn(func).await;
    });
    return res;
}

/// Executes an error-handling function with a given error message within a panic-safe context.
///
/// - `func`: A function implementing the `AsyncErrorHandlerFunction` trait.
/// - `error`: A string slice representing the error message.
/// - Returns: A `AsyncSpawnResult` indicating the success or failure of the error-handling function execution.
#[inline]
pub fn run_error_handle_function<E: AsyncErrorHandlerFunction>(
    func: E,
    error: Arc<String>,
) -> AsyncSpawnResult {
    let res: Result<(), JoinError> = GLOBAL_RUNTIME.block_on(async move {
        let func = async move {
            func.call(error.clone()).await;
        };
        return tokio::spawn(func).await;
    });
    return res;
}

/// Executes a recoverable function within a panic-safe context.
///
/// - `func`: A function implementing the `AsyncRecoverableFunction` trait.
/// - Returns: A `AsyncSpawnResult` indicating the success or failure of the function execution.
#[inline]
pub async fn async_run_function<F: AsyncRecoverableFunction>(func: F) -> AsyncSpawnResult {
    let func = async move {
        func.call().await;
    };
    return tokio::spawn(func).await;
}

/// Executes an error-handling function with a given error message within a panic-safe context.
///
/// - `func`: A function implementing the `AsyncErrorHandlerFunction` trait.
/// - `error`: A string slice representing the error message.
/// - Returns: A `AsyncSpawnResult` indicating the success or failure of the error-handling function execution.
#[inline]
pub async fn async_run_error_handle_function<E: AsyncErrorHandlerFunction>(
    func: E,
    error: Arc<String>,
) -> AsyncSpawnResult {
    let func = async move {
        func.call(error.clone()).await;
    };
    return tokio::spawn(func).await;
}

/// Converts a panic-captured error value into a string.
///
/// - `err`: The captured error value, of type `JoinError `.
/// - Returns: A string representation of the error value.
#[inline]
pub fn tokio_error_to_string(err: JoinError) -> String {
    err.to_string()
}

/// Spawns a new thread to run the provided function `function` in a recoverable manner.
/// If the function `function` panics during execution, the panic will be caught, and the thread
/// will terminate without crashing the entire program.
///
/// # Parameters
/// - `function`: A function of type `function` to be executed in the spawned thread. It must implement `FnOnce()`, `Send`, `Sync`, and `'static` traits.
///     - `FnOnce()`: The function is callable with no arguments and no return value.
///     - `Send`: The function can be safely transferred across thread boundaries.
///     - `Sync`: The function can be shared across threads safely.
///     - `'static`: The function does not contain references to non-static data (i.e., data that lives beyond the function's scope).
///
/// # Returns
/// - A `JoinHandle<()>` representing the spawned thread. The thread can be joined later to wait for its completion.
///
///
/// # Panics
/// - This function itself will not panic, but the function `function` could panic during execution.
///   The panic will be caught, preventing the program from crashing.
#[inline]
pub fn recoverable_spawn<F>(function: F) -> JoinHandle<()>
where
    F: AsyncRecoverableFunction,
{
    spawn(|| {
        let _: AsyncSpawnResult = run_function(function);
    })
}

/// Spawns a new thread to run the provided function `function` in a recoverable manner.
/// If the function `function` panics during execution, the panic will be caught, and the thread
/// will terminate without crashing the entire program.
///
/// # Parameters
/// - `function`: A function of type `function` to be executed in the spawned thread. It must implement `FnOnce()`, `Send`, `Sync`, and `'static` traits.
///     - `FnOnce()`: The function is callable with no arguments and no return value.
///     - `Send`: The function can be safely transferred across thread boundaries.
///     - `Sync`: The function can be shared across threads safely.
///     - `'static`: The function does not contain references to non-static data (i.e., data that lives beyond the function's scope).
///
/// # Returns
/// - A `JoinHandle<()>` representing the spawned thread. The thread can be joined later to wait for its completion.
///
///
/// # Panics
/// - This function itself will not panic, but the function `function` could panic during execution.
///   The panic will be caught, preventing the program from crashing.
#[inline]
pub async fn async_recoverable_spawn<F>(function: F)
where
    F: AsyncRecoverableFunction,
{
    let _ = async_run_function(function).await;
}

/// Spawns a recoverable function with an error-handling function in a new thread.
///
/// - `function`: The primary function to execute, implementing the `AsyncRecoverableFunction` trait.
/// - `error_handle_function`: A function to handle errors, implementing the `AsyncErrorHandlerFunction` trait.
/// - Returns: A `JoinHandle<()>` that can be used to manage the spawned thread.
#[inline]
pub fn recoverable_spawn_catch<F, E>(function: F, error_handle_function: E) -> JoinHandle<()>
where
    F: AsyncRecoverableFunction,
    E: AsyncErrorHandlerFunction,
{
    spawn(|| {
        let run_result: AsyncSpawnResult = run_function(function);
        if let Err(err) = run_result {
            let err_string: String = tokio_error_to_string(err);
            let _: AsyncSpawnResult =
                run_error_handle_function(error_handle_function, Arc::new(err_string));
        }
    })
}

/// Spawns a recoverable function with an error-handling function in a new thread.
///
/// - `function`: The primary function to execute, implementing the `AsyncRecoverableFunction` trait.
/// - `error_handle_function`: A function to handle errors, implementing the `AsyncErrorHandlerFunction` trait.
#[inline]
pub async fn async_recoverable_spawn_catch<F, E>(function: F, error_handle_function: E)
where
    F: AsyncRecoverableFunction,
    E: AsyncErrorHandlerFunction,
{
    let run_result: AsyncSpawnResult = async_run_function(function).await;
    if let Err(err) = run_result {
        let err_string: String = tokio_error_to_string(err);
        let _: AsyncSpawnResult =
            async_run_error_handle_function(error_handle_function, Arc::new(err_string)).await;
    }
}

/// Spawns an asynchronous recoverable function, catches any errors with an error-handling function,
/// and ensures that a final function is always executed, regardless of whether an error occurred.
///
/// This function runs a series of operations in an asynchronous context, where:
/// - `function` is executed first. If it results in an error, the `error_handle_function` is called.
/// - After either the main function or the error handler finishes, the `finally` function is executed.
/// This guarantees that the `finally` function runs regardless of the success or failure of the main operation.
///
/// # Parameters
/// - `function`: The primary function to execute, which must implement the `AsyncRecoverableFunction` trait.
/// - `error_handle_function`: A function that handles errors, which must implement the `AsyncErrorHandlerFunction` trait.
/// - `finally`: A function that will be executed after the main function and error handler, which must implement the `AsyncRecoverableFunction` trait.
///
/// # Returns
/// - A `JoinHandle<()>` that can be used to manage the spawned thread, ensuring that all the functions execute
///   in a recoverable context and the final block always runs.
///
/// # Errors
/// - If the `function` fails, the `error_handle_function` is invoked. If this fails as well, it will not stop the execution
///   of the `finally` block.
/// - The final block (`finally`) is always executed, even if the main function (`function`) or the error handler (`error_handle_function`) fails.
/// Spawns an asynchronous recoverable function, catches any errors with an error-handling function,
/// and ensures that a final function is always executed, regardless of whether an error occurred.
///
/// This function runs a series of operations in an asynchronous context, where:
/// - `function` is executed first. If it results in an error, the `error_handle_function` is called.
/// - After either the main function or the error handler finishes, the `finally` function is executed.
/// This guarantees that the `finally` function runs regardless of the success or failure of the main operation.
///
/// # Parameters
/// - `function`: The primary function to execute, which must implement the `AsyncRecoverableFunction` trait.
/// - `error_handle_function`: A function that handles errors, which must implement the `AsyncErrorHandlerFunction` trait.
/// - `finally`: A function that will be executed after the main function and error handler, which must implement the `AsyncRecoverableFunction` trait.
///
/// # Returns
/// - A `JoinHandle<()>` that can be used to manage the spawned thread, ensuring that all the functions execute
///   in a recoverable context and the final block always runs.
///
/// # Errors
/// - If the `function` fails, the `error_handle_function` is invoked. If this fails as well, it will not stop the execution
///   of the `finally` block.
/// - The final block (`finally`) is always executed, even if the main function (`function`) or the error handler (`error_handle_function`) fails.
#[inline]
pub fn recoverable_spawn_catch_finally<F, E, L>(
    function: F,
    error_handle_function: E,
    finally: L,
) -> JoinHandle<()>
where
    F: AsyncRecoverableFunction,
    E: AsyncErrorHandlerFunction,
    L: AsyncRecoverableFunction,
{
    spawn(|| {
        let run_result: AsyncSpawnResult = run_function(function);
        if let Err(err) = run_result {
            let err_string: String = tokio_error_to_string(err);
            let _: AsyncSpawnResult =
                run_error_handle_function(error_handle_function, Arc::new(err_string));
        }
        let _: AsyncSpawnResult = run_function(finally);
    })
}

/// Spawns an asynchronous recoverable function, catches any errors with an error-handling function,
/// and ensures that a final function is always executed, regardless of whether an error occurred.
///
/// This function runs a series of operations in an asynchronous context, where:
/// - `function` is executed first. If it results in an error, the `error_handle_function` is called.
/// - After either the main function or the error handler finishes, the `finally` function is executed.
/// This guarantees that the `finally` function runs regardless of the success or failure of the main operation.
///
/// # Parameters
/// - `function`: The primary function to execute, which must implement the `AsyncRecoverableFunction` trait.
/// - `error_handle_function`: A function that handles errors, which must implement the `AsyncErrorHandlerFunction` trait.
/// - `finally`: A function that will be executed after the main function and error handler, which must implement the `AsyncRecoverableFunction` trait.
///
/// # Returns
/// - A `JoinHandle<()>` that can be used to manage the spawned thread, ensuring that all the functions execute
///   in a recoverable context and the final block always runs.
///
/// # Errors
/// - If the `function` fails, the `error_handle_function` is invoked. If this fails as well, it will not stop the execution
///   of the `finally` block.
/// - The final block (`finally`) is always executed, even if the main function (`function`) or the error handler (`error_handle_function`) fails.
/// Spawns an asynchronous recoverable function, catches any errors with an error-handling function,
/// and ensures that a final function is always executed, regardless of whether an error occurred.
///
/// This function runs a series of operations in an asynchronous context, where:
/// - `function` is executed first. If it results in an error, the `error_handle_function` is called.
/// - After either the main function or the error handler finishes, the `finally` function is executed.
/// This guarantees that the `finally` function runs regardless of the success or failure of the main operation.
///
/// # Parameters
/// - `function`: The primary function to execute, which must implement the `AsyncRecoverableFunction` trait.
/// - `error_handle_function`: A function that handles errors, which must implement the `AsyncErrorHandlerFunction` trait.
/// - `finally`: A function that will be executed after the main function and error handler, which must implement the `AsyncRecoverableFunction` trait.
///
/// # Returns
/// - A `JoinHandle<()>` that can be used to manage the spawned thread, ensuring that all the functions execute
///   in a recoverable context and the final block always runs.
///
/// # Errors
/// - If the `function` fails, the `error_handle_function` is invoked. If this fails as well, it will not stop the execution
///   of the `finally` block.
/// - The final block (`finally`) is always executed, even if the main function (`function`) or the error handler (`error_handle_function`) fails.
#[inline]
pub async fn async_recoverable_spawn_catch_finally<F, E, L>(
    function: F,
    error_handle_function: E,
    finally: L,
) where
    F: AsyncRecoverableFunction,
    E: AsyncErrorHandlerFunction,
    L: AsyncRecoverableFunction,
{
    let run_result: AsyncSpawnResult = async_run_function(function).await;
    if let Err(err) = run_result {
        let err_string: String = tokio_error_to_string(err);
        let _: AsyncSpawnResult =
            async_run_error_handle_function(error_handle_function, Arc::new(err_string)).await;
    }
    let _: AsyncSpawnResult = async_run_function(finally).await;
}