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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
#![deny(unsafe_code)]
use core::{
    clone::Clone,
    marker::PhantomData,
    sync::atomic::{AtomicBool, AtomicUsize, Ordering},
};
use std::{
    borrow::Cow,
    sync::{Arc, Condvar, Mutex},
    thread,
};

const ZER: usize = 0;
const TRU: bool = true;
const FAL: bool = false;

/// Result for Futurized task,
///
/// where C: type of ITaskHandle sync sender value, T: type of Completed value,
#[derive(Clone, Debug)]
pub enum Progress<'a, C, T> {
    /// Current progress of the task
    Current(Option<C>),
    /// Indicates if the task is canceled
    Canceled,
    Completed(T),
    Error(Cow<'a, str>),
}

/// Runtime handle of the task.
#[derive(Clone)]
pub struct RuntimeHandle {
    _id: usize,
    rt_states: Arc<(AtomicBool, AtomicBool, AtomicBool, AtomicBool)>,
}

impl RuntimeHandle {
    /// Get the id of the task
    pub fn id(&self) -> usize {
        self._id
    }

    /// Send signal to the inner task handle that the task should be suspended,
    ///
    /// this won't do anything if not explicitly configured inside the task.
    pub fn suspend(&self) {
        self.rt_states.3.store(TRU, Ordering::Relaxed)
    }

    /// Resume the suspended task.
    pub fn resume(&self) {
        self.rt_states.3.store(FAL, Ordering::Relaxed)
    }

    /// Check if progress of the task is resumed.
    pub fn is_resumed(&self) -> bool {
        !self.rt_states.3.load(Ordering::Relaxed)
    }

    /// Check if progress of the task is suspended.
    pub fn is_suspended(&self) -> bool {
        self.rt_states.3.load(Ordering::Relaxed)
    }

    /// Send signal to the inner task handle that the task should be canceled.
    ///
    /// this won't do anything if not explicitly configured inside the task.
    pub fn cancel(&self) {
        self.rt_states.2.store(TRU, Ordering::Relaxed)
    }

    /// Check if progress of the task is canceled.
    pub fn is_canceled(&self) -> bool {
        self.rt_states.2.load(Ordering::Relaxed)
    }

    /// Check if the task is in progress.
    pub fn is_in_progress(&self) -> bool {
        self.rt_states.0.load(Ordering::Relaxed)
    }

    /// Check if the task isn't in progress anymore (done).
    pub fn is_done(&self) -> bool {
        !self.rt_states.0.load(Ordering::Relaxed)
    }
}

/// Inner handle of the task,
///
/// where C: type of sync sender value.
#[derive(Clone)]
pub struct ITaskHandle<C> {
    _id: usize,
    rt_states: Arc<(AtomicBool, AtomicBool, AtomicBool, AtomicBool)>,
    sync_s: Arc<(AtomicBool, Mutex<Option<C>>, Condvar)>,
}

impl<C: Clone + Send + 'static> ITaskHandle<C> {
    /// Send current progress of the task.
    ///
    pub fn send(&self, t: C) {
        let (ready, mtx, cvar) = &*self.sync_s;
        if let Ok(mut mtx) = mtx.lock() {
            *mtx = Some(t);
            ready.store(TRU, Ordering::Relaxed);
            let _ = cvar.wait(mtx);
        }
    }

    /// Get the id of the task
    pub fn id(&self) -> usize {
        self._id
    }

    /// Suspend the task (it's quite rare that suspending task from inside itself, unless in a particular case).
    pub fn suspend(&self) {
        self.rt_states.3.store(TRU, Ordering::Relaxed)
    }

    /// Resume the task (it's quite rare that resuming task from inside itself, unless in a particular case).
    pub fn resume(&self) {
        self.rt_states.3.store(FAL, Ordering::Relaxed)
    }

    /// Check if progress of the task should be suspended,
    ///
    /// usually applied for a specific task with event loop in it.
    ///
    /// do other things (switch) while the task is suspended.
    pub fn is_suspended(&self) -> bool {
        self.rt_states.3.load(Ordering::Relaxed)
    }

    /// Check if progress of the task is resumed.
    pub fn is_resumed(&self) -> bool {
        !self.rt_states.3.load(Ordering::Relaxed)
    }

    /// Cancel the task (it's quite rare that canceling task from inside itself, unless in a particular case).
    pub fn cancel(&self) {
        self.rt_states.2.store(TRU, Ordering::Relaxed)
    }

    /// Check if progress of the task should be canceled.
    pub fn is_canceled(&self) -> bool {
        self.rt_states.2.load(Ordering::Relaxed)
    }
}

impl<C> Drop for ITaskHandle<C> {
    fn drop(&mut self) {
        if thread::panicking() {
            self.rt_states.1.store(TRU, Ordering::Relaxed)
        }
    }
}

/// Type name of ITaskHandle,
///
/// Use this if there's no needed for sending current value through channel and if type of ITaskHandle sync sender value not necessary to be known.
pub type InnerTaskHandle = ITaskHandle<()>;

/// Handle of the task.
#[derive(Clone)]
pub struct TaskHandle<C, T> {
    _id: usize,
    states: Arc<(
        Box<dyn Send + Sync + Fn(ITaskHandle<C>) -> Progress<'static, C, T>>,
        Mutex<Progress<'static, C, T>>,
        AtomicBool,
        AtomicUsize,
    )>,
    task_handle: ITaskHandle<C>,
}

impl<C, T> TaskHandle<C, T>
where
    C: Clone + Send + 'static,
    T: Clone + Send + 'static,
{
    /// Get the id of the task
    pub fn id(&self) -> usize {
        self._id
    }

    /// Set stack size (in bytes) of the thread for spawning Futurized task,
    ///
    /// Rust's official doc: https://doc.rust-lang.org/std/thread/struct.Builder.html#method.stack_size
    ///
    /// if the given value is zero or default, it will use Rust's standard stack size.
    pub fn stack_size(&self, size: usize) {
        self.states.3.store(size, Ordering::Relaxed)
    }

    /// Try (it won't block the current thread) to do the task now,
    ///
    /// and then try to resolve later.
    pub fn try_do(&self) {
        let waiting = &self.task_handle.rt_states.0;
        if !waiting.load(Ordering::SeqCst) {
            waiting.store(TRU, Ordering::SeqCst);
            self.task_handle.rt_states.2.store(FAL, Ordering::Relaxed);
            let _stack_size = self.states.3.load(Ordering::Relaxed);
            let states = Arc::clone(&self.states);
            let inner_task_handle = self.task_handle.clone();
            let task = move || {
                let (closure, mtx, ready, _) = &*states;
                let result = closure(inner_task_handle);
                if let Ok(mut mtx) = mtx.lock() {
                    *mtx = result;
                }
                ready.store(TRU, Ordering::Relaxed)
            };
            if _stack_size == ZER {
                thread::spawn(task);
            } else {
                // Should panic if the given stack size value is incorrect, so it's better to unwrap() here.
                thread::Builder::new()
                    .stack_size(_stack_size)
                    .spawn(task)
                    .unwrap();
            }
        }
    }

    /// Send signal to the inner task handle that the task should be suspended.
    ///
    /// this won't do anything if not explicitly configured inside the task.
    pub fn suspend(&self) {
        self.task_handle.rt_states.3.store(TRU, Ordering::Relaxed)
    }

    /// Resume the suspended task.
    pub fn resume(&self) {
        self.task_handle.rt_states.3.store(FAL, Ordering::Relaxed)
    }

    /// Check if progress of the task is suspended.
    pub fn is_suspended(&self) -> bool {
        self.task_handle.rt_states.3.load(Ordering::Relaxed)
    }

    /// Check if progress of the task is resumed.
    pub fn is_resumed(&self) -> bool {
        !self.task_handle.rt_states.3.load(Ordering::Relaxed)
    }

    /// Send signal to the inner task handle that the task should be canceled.
    ///
    /// this won't do anything if not explicitly configured inside the task.
    pub fn cancel(&self) {
        self.task_handle.rt_states.2.store(TRU, Ordering::Relaxed)
    }

    /// Check if progress of the task is canceled.
    pub fn is_canceled(&self) -> bool {
        self.task_handle.rt_states.2.load(Ordering::Relaxed)
    }

    /// Check if the task is in progress.
    pub fn is_in_progress(&self) -> bool {
        self.task_handle.rt_states.0.load(Ordering::Relaxed)
    }

    /// Check if the task isn't in progress anymore (done).
    pub fn is_done(&self) -> bool {
        !self.task_handle.rt_states.0.load(Ordering::Relaxed)
    }
}

/// Futurize task asynchronously.
/// # Example:
///
///```
///use asynchron::{Futurize, Futurized, ITaskHandle, Progress};
///use std::{
///    io::Error,
///    time::{Duration, Instant},
///};
///
///fn main() {
///    let instant: Instant = Instant::now();
///    let task: Futurized<String, u32> = Futurize::task(
///        0,
///        move |_task: ITaskHandle<String>| -> Progress<String, u32> {
///            // // Panic if need to.
///            // // will return Error with a message:
///            // // "the task with id: (specific task id) panicked!"
///            // std::panic::panic_any("loudness");
///            let sleep_dur = Duration::from_millis(10);
///            std::thread::sleep(sleep_dur);
///            let result = Ok::<String, Error>(
///                format!("The task with id: {} wake up from sleep", _task.id()).into(),
///            );
///            match result {
///                Ok(value) => {
///                    // Send current task progress.
///                    _task.send(value)
///                }
///                Err(e) => {
///                    // Return error immediately if something not right, for example:
///                    return Progress::Error(e.to_string().into());
///                }
///            }
///
///            if _task.is_canceled() {
///                _task.send("Canceling the task".into());
///                return Progress::Canceled;
///            }
///            Progress::Completed(instant.elapsed().subsec_millis())
///        },
///    );
///
///    // Try do the task now.
///    task.try_do();
///
///    let mut exit = false;
///    loop {
///        task.try_resolve(|progress, done| {
///            match progress {
///                Progress::Current(task_receiver) => {
///                    if let Some(value) = task_receiver {
///                        println!("{}\n", value)
///                    }
///                    // // Cancel if need to.
///                    // task.cancel()
///                }
///                Progress::Canceled => {
///                    println!("The task was canceled\n")
///                }
///                Progress::Completed(elapsed) => {
///                    println!("The task finished in: {:?} milliseconds\n", elapsed)
///                }
///                Progress::Error(e) => {
///                    println!("{}\n", e)
///                }
///            }
///
///            if done {
///                // This scope act like "finally block", do final things here.
///                exit = true
///            }
///        });
///
///        if exit {
///            break;
///        }
///    }
///}
///```
pub struct Futurize<C, T> {
    _data: PhantomData<(C, T)>,
}

impl<C: Clone + Send + 'static, T> Futurize<C, T> {
    /// Create new task.
    pub fn task<F>(id: usize, f: F) -> Futurized<C, T>
    where
        F: Send + Sync + Fn(ITaskHandle<C>) -> Progress<'static, C, T> + 'static,
    {
        let _channel = Arc::new((AtomicBool::new(FAL), Mutex::new(None), Condvar::new()));
        Futurized {
            _id: id,
            states: Arc::new((
                Box::new(f),
                Mutex::new(Progress::Current(None)),
                AtomicBool::new(FAL),
                AtomicUsize::new(ZER),
            )),
            receiver: Arc::clone(&_channel),
            task_handle: ITaskHandle {
                _id: id,
                rt_states: Arc::new((
                    AtomicBool::new(FAL),
                    AtomicBool::new(FAL),
                    AtomicBool::new(FAL),
                    AtomicBool::new(FAL),
                )),
                sync_s: _channel,
            },
        }
    }
}

/// Futurized task.
#[derive(Clone)]
pub struct Futurized<C, T> {
    _id: usize,
    states: Arc<(
        Box<dyn Send + Sync + Fn(ITaskHandle<C>) -> Progress<'static, C, T>>,
        Mutex<Progress<'static, C, T>>,
        AtomicBool,
        AtomicUsize,
    )>,
    receiver: Arc<(AtomicBool, Mutex<Option<C>>, Condvar)>,
    task_handle: ITaskHandle<C>,
}

impl<C, T> Futurized<C, T>
where
    C: Clone + Send + 'static,
    T: Clone + Send + 'static,
{
    /// Set stack size (in bytes) of the thread for spawning Futurized task,
    ///
    /// Rust's official doc: https://doc.rust-lang.org/std/thread/struct.Builder.html#method.stack_size
    ///
    /// if the given value is zero or default, it will use Rust's standard stack size.
    pub fn stack_size(&self, size: usize) {
        self.states.3.store(size, Ordering::Relaxed)
    }

    /// Try (it won't block the current thread) to do the task now,
    ///
    /// and then try to resolve later.
    pub fn try_do(&self) {
        let waiting = &self.task_handle.rt_states.0;
        if !waiting.load(Ordering::SeqCst) {
            waiting.store(TRU, Ordering::SeqCst);
            self.task_handle.rt_states.3.store(FAL, Ordering::Relaxed);
            let _stack_size = self.states.3.load(Ordering::Relaxed);
            let states = Arc::clone(&self.states);
            let inner_task_handle = Clone::clone(&self.task_handle);
            let task = move || {
                let (closure, mtx, ready, _) = &*states;
                let result = closure(inner_task_handle);
                if let Ok(mut mtx) = mtx.lock() {
                    *mtx = result;
                }
                ready.store(TRU, Ordering::Relaxed)
            };
            if _stack_size == ZER {
                thread::spawn(task);
            } else {
                // Should panic if the given stack size value is incorrect, so it's better to unwrap() here.
                thread::Builder::new()
                    .stack_size(_stack_size)
                    .spawn(task)
                    .unwrap();
            }
        }
    }

    /// Send signal to the inner task handle that the task should be suspended.
    ///
    /// this won't do anything if not explicitly configured inside the task.
    pub fn suspend(&self) {
        self.task_handle.rt_states.3.store(TRU, Ordering::Relaxed)
    }

    /// Resume the suspended task.
    pub fn resume(&self) {
        self.task_handle.rt_states.3.store(FAL, Ordering::Relaxed)
    }

    /// Check if progress of the task is suspended.
    pub fn is_suspended(&self) -> bool {
        self.task_handle.rt_states.3.load(Ordering::Relaxed)
    }

    /// Check if progress of the task is resumed.
    pub fn is_resumed(&self) -> bool {
        !self.task_handle.rt_states.3.load(Ordering::Relaxed)
    }

    /// Send signal to the inner task handle that the task should be canceled.
    ///
    /// this won't do anything if not explicitly configured inside the task.
    pub fn cancel(&self) {
        self.task_handle.rt_states.2.store(TRU, Ordering::Relaxed)
    }

    /// Check if progress of the task is canceled.
    pub fn is_canceled(&self) -> bool {
        self.task_handle.rt_states.2.load(Ordering::Relaxed)
    }

    /// Get the task handle, if only intended to try to do,
    ///
    /// check progress, cancel, suspend or resume the task, from inside moving closures,
    ///
    /// or from other threads to avoid (channel) synchronous Sender data races.
    pub fn handle(&self) -> TaskHandle<C, T> {
        TaskHandle {
            _id: self._id,
            states: Arc::clone(&self.states),
            task_handle: Clone::clone(&self.task_handle),
        }
    }

    /// Get the runtime handle, if only intended to cancel,
    ///
    /// suspend or resume the task from inside moving closures or from other threads.
    ///
    /// use this to avoid unnecessary cloning unused task values.
    pub fn rt_handle(&self) -> RuntimeHandle {
        RuntimeHandle {
            _id: self._id,
            rt_states: Arc::clone(&self.task_handle.rt_states),
        }
    }

    /// Get the id of the task
    pub fn id(&self) -> usize {
        self._id
    }

    /// Try resolve the progress of the task,
    ///
    /// WARNING! to prevent from data races this fn should be called once at a time.
    pub fn try_resolve<F: FnOnce(Progress<C, T>, bool) -> ()>(&self, f: F) {
        let _self = self;
        if _self.task_handle.rt_states.0.load(Ordering::Relaxed) {
            let result = || {
                let _self = _self;
                let (awaiting, task_panicked, _, suspended) = &*_self.task_handle.rt_states;
                {
                    if task_panicked.load(Ordering::Relaxed) {
                        suspended.store(FAL, Ordering::Relaxed);
                        task_panicked.store(FAL, Ordering::Relaxed);
                        awaiting.store(FAL, Ordering::Relaxed);
                        // fixes unsound problem, return error immediately if the task is panicked.
                        return (
                            Progress::Error(Cow::Owned(format!(
                                "the task with id: {} panicked!",
                                _self._id
                            ))),
                            TRU,
                        );
                    }
                }

                if awaiting.load(Ordering::Relaxed) {
                    let _self = _self;
                    {
                        if _self.receiver.0.load(Ordering::Relaxed) {
                            let (ready, mtx, cvar) = &*_self.receiver;
                            let result = if let Ok(mut mtx) = mtx.lock() {
                                let result = Clone::clone(&*mtx);
                                *mtx = None;
                                result
                            } else {
                                None
                            };
                            ready.store(FAL, Ordering::Relaxed);
                            cvar.notify_all();
                            return (Progress::Current(result), FAL);
                        }
                    }

                    let ready = &_self.states.2;
                    if ready.load(Ordering::Relaxed) {
                        suspended.store(FAL, Ordering::Relaxed);
                        let mtx = &_self.states.1;
                        // there's almost zero chance to deadlock,
                        // already guarded + with 2 atomicbools (awaiting and ready), so it's safe to unwrap here.
                        let mut mtx = mtx.lock().unwrap();
                        let result = Clone::clone(&*mtx);
                        *mtx = Progress::Current(None);
                        ready.store(FAL, Ordering::Relaxed);
                        awaiting.store(FAL, Ordering::Relaxed);
                        return (result, TRU);
                    }
                    return (Progress::Current(None), FAL);
                }
                (Progress::Current(None), FAL)
            };
            let (result, done) = result();
            f(result, done)
        }
    }

    /// Check if the task is in progress.
    pub fn is_in_progress(&self) -> bool {
        self.task_handle.rt_states.0.load(Ordering::Relaxed)
    }

    /// Check if the task isn't in progress anymore (done).
    pub fn is_done(&self) -> bool {
        !self.task_handle.rt_states.0.load(Ordering::Relaxed)
    }
}

use std::sync::{LockResult, MutexGuard};
/// Simple helper thread safe state management,
///
/// using std::sync::Arc and std::sync::Mutex under the hood.
///
/// # Example:
///
///```
///use asynchron::SyncState;
///
///fn main() -> core::result::Result<(), Box<dyn std::error::Error>> {
///    let state: SyncState<i32> = SyncState::new(0);
///    let _state = state.clone();
///
///    if let Err(_) = std::thread::spawn(move||{
///        _state.set(20);
///    })
///     .join()
///    {
///        let e = std::io::Error::new(std::io::ErrorKind::Other, "Unable to join thread.");
///        return Err(Box::new(e));
///    }
///
///    if let Ok(value) = state.get() {
///       println!("{:?}", *value);
///    } else {
///       let e = std::io::Error::new(std::io::ErrorKind::Other, "Mutex poisonous!");
///       return Err(Box::new(e));
///    }
///    Ok(())
///}
///```
#[derive(Clone)]
pub struct SyncState<T> {
    item: Arc<Mutex<T>>,
}

impl<T: Clone + Send + Sync + ?Sized> SyncState<T> {
    /// Create new state.
    pub fn new(t: T) -> SyncState<T> {
        SyncState {
            item: Arc::new(Mutex::new(t)),
        }
    }

    /// Get state.
    pub fn get(&self) -> LockResult<MutexGuard<'_, T>> {
        let rwx = &*self.item;
        rwx.lock()
    }

    /// Set state.
    pub fn set(&self, t: T) {
        let rwx = &*self.item;
        if let Ok(mut rwx) = rwx.lock() {
            *rwx = t
        }
    }
}