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
use cyfs_base::bucky_time_now;

use once_cell::sync::OnceCell;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;

#[derive(Clone)]
pub struct ProcessDeadHelper {
    interval_in_secs: u64,

    task_system_last_active: Arc<AtomicU64>,

    exit_on_task_system_dead: Arc<AtomicU64>,
}

impl ProcessDeadHelper {
    fn new(interval_in_secs: u64) -> Self {
        Self {
            interval_in_secs,
            task_system_last_active: Arc::new(AtomicU64::new(bucky_time_now())),
            exit_on_task_system_dead: Arc::new(AtomicU64::new(0)),
        }
    }

    pub fn patch_task_min_thread() {
        let cpu_nums = num_cpus::get();
        if cpu_nums <= 1 {
            const KEY: &str = "ASYNC_STD_THREAD_COUNT";
            if std::env::var(KEY).is_err() {
                std::env::set_var(KEY, "2");
            }
        }
    }

    pub fn instance() -> &'static Self {
        static INSTANCE: OnceCell<ProcessDeadHelper> = OnceCell::new();
        INSTANCE.get_or_init(|| Self::new(60))
    }

    pub fn start_check(&self) {
        static INIT_DONE: AtomicBool = AtomicBool::new(false);
        if !INIT_DONE.swap(true, Ordering::SeqCst) {
            self.start_check_process();
            self.start_check_task_system();
        }
    }

    pub fn enable_exit_on_task_system_dead(&self, timeout_in_secs: Option<u64>) {
        let v = timeout_in_secs.unwrap_or(60 * 5) * 1000 * 1000;
        self.exit_on_task_system_dead.store(v, Ordering::SeqCst);
        if v > 0 {
            info!("enable exit on task system dead: timeout={}", v);
            self.start_check();
        } else {
            info!("disable exit on task system dead");
        }
    }

    fn update_task_alive(&self) {
        let now = bucky_time_now();
        self.task_system_last_active.store(now, Ordering::SeqCst);
    }

    fn check_task_alive(&self) {
        let exit_timeout = self.exit_on_task_system_dead.load(Ordering::SeqCst);
        if exit_timeout == 0 {
            return;
        }

        let now = bucky_time_now();
        let last_active = self.task_system_last_active.load(Ordering::SeqCst);
        if now - last_active >= exit_timeout {
            error!(
                "task system dead timeout, now will exit process! last_active={}, exit_timeout={}s",
                last_active,
                exit_timeout / (1000 * 1000)
            );
            println!("process will exit on task system dead...");
            std::thread::sleep(std::time::Duration::from_secs(5));
            std::process::exit(-1);
        }
    }

    fn start_check_process(&self) {
        let dur = std::time::Duration::from_secs(self.interval_in_secs);

        let this = self.clone();
        std::thread::spawn(move || loop {
            std::thread::sleep(dur);
            info!("process still alive {:?}", std::thread::current().id(),);
            this.check_task_alive();
        });
    }

    fn start_check_task_system(&self) {
        let dur = std::time::Duration::from_secs(self.interval_in_secs);
        let this = self.clone();
        async_std::task::spawn(async move {
            loop {
                this.update_task_alive();
                async_std::task::sleep(dur).await;
                info!(
                    "process task system still alive {:?}",
                    std::thread::current().id(),
                );
            }
        });
    }
}

#[cfg(test)]
mod tests {
    use super::ProcessDeadHelper;
    use std::sync::RwLock;

    struct Test {
        v: Option<u32>,
    }

    impl Test {
        fn new() -> Self {
            Self { v: None }
        }

        fn get(&self) -> Option<&u32> {
            self.v.as_ref()
        }

        fn set(&mut self, v: u32) {
            self.v = Some(v);
        }
    }

    async fn dead_lock() {
        let r: RwLock<Test> = RwLock::new(Test::new());

        if let Some(v) = r.read().unwrap().get().cloned() {
            println!("v={}", v);
        } else {
            println!("enter else");
            r.write().unwrap().set(1);
            println!("v={}", 1);
        };
    }

    #[test]
    fn test_dead_lock() {
        ProcessDeadHelper::instance().start_check();
        ProcessDeadHelper::instance().enable_exit_on_task_system_dead(Some(1000 * 1000 * 2));

        async_std::task::block_on(dead_lock());
        
        // async_std::task::sleep(std::time::Duration::from_secs(60 * 5));
    }

    #[test]
    fn test_safe_lock() {
        let r: RwLock<Test> = RwLock::new(Test::new());

        let v = r.read().unwrap().get().cloned();
        if let Some(v) = v {
            println!("v={}", v);
        } else {
            println!("enter else");
            r.write().unwrap().set(1);
            println!("v={}", 1);
        };
    }
}