open-net 0.3.5

A cross-platform async networking library for Rust with HTTP and WebSocket clients, network status monitoring, configurable retries, WebSocket reconnection and heartbeats, and managed client lifecycles. Reuse common networking infrastructure across applications to avoid repeated implementation and debugging, helping save development time and AI coding tokens.
Documentation
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
use crate::common::common_engine::CommonEngine;
use crate::common::common_error::CommonError;
use crate::common::log::log_def::LogType;
use crate::common::log::log_def::DESC;
use crate::log_e;
use futures_util::FutureExt;
use std::any::Any;
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::pin::Pin;
use std::sync::Arc;
use tokio::runtime::Handle;
use tokio::sync::oneshot;

#[cfg(test)]
#[path = "common_callback_laziness_tests.rs"]
mod callback_laziness_tests;

// Used while constructing log fields; do not log this formatting dependency.
fn panic_payload_message(payload: &Box<dyn Any + Send + 'static>) -> String {
    if let Some(message) = payload.downcast_ref::<&str>() {
        (*message).to_string()
    } else if let Some(message) = payload.downcast_ref::<String>() {
        message.clone()
    } else {
        "unknown panic payload".to_string()
    }
}

pub async fn run_engine_queue_future(
    queue_name: &'static str,
    future: Pin<Box<dyn Future<Output = ()> + Send + 'static>>,
) {
    crate::log_t!(LogType::Common; "run_engine_queue_future", "queue_name|future_type", queue_name, std::any::type_name_of_val(&future));
    if let Err(payload) = AssertUnwindSafe(future).catch_unwind().await {
        log_e!(LogType::Common; "run_engine_queue_future",
            DESC,
            format!(
                "{} queue task panicked: {}",
                queue_name,
                crate::common::log::summary::error(&panic_payload_message(&payload))
            )
        );
    }
}

#[allow(clippy::type_complexity)]
impl CommonEngine {
    /// 在引擎专用 Runtime 上执行会调用 `self.rt.block_on(...)` 的闭包。
    ///
    /// - 无当前 Tokio 上下文(如 `spawn_blocking` 线程):直接执行即可。
    /// - 已在**本引擎**的 worker 上:须 `block_in_place`,否则会死锁/嵌套阻塞。
    /// - 已在**其它** Runtime 上(如 Tauri 命令的 `tokio-rt-worker`):不能在本线程上对引擎
    ///   `block_on`,否则触发 *Cannot start a runtime from within a runtime*;改到独立 OS 线程执行。
    pub fn run_blocking_on_engine_rt<R>(
        &self,
        f: impl FnOnce() -> R + Send + 'static,
    ) -> Result<R, CommonError>
    where
        R: Send + 'static,
    {
        crate::log_t!(LogType::Common; "run_blocking_on_engine_rt", "callback_type", std::any::type_name_of_val(&f));
        let engine_rt_id = self.rt.handle().id();
        match Handle::try_current() {
            Ok(current) if current.id() == engine_rt_id => tokio::task::block_in_place(|| {
                std::panic::catch_unwind(AssertUnwindSafe(f)).map_err(|payload| {
                    log_e!(LogType::Common; "run_blocking_on_engine_rt",
                        DESC,
                        format!(
                            "engine runtime task panicked: {}",
                            crate::common::log::summary::error(&panic_payload_message(&payload))
                        )
                    );
                    CommonError::RuntimeError
                })
            }),
            Ok(_) => {
                let (sent, received) = std::sync::mpsc::channel();
                let handle = self.resource_threads()
                    .spawn_tracked("open-net-runtime-bridge", move || {
                        let _ = sent.send(std::panic::catch_unwind(AssertUnwindSafe(f)));
                    })
                    .map_err(|error| {
                        log_e!(LogType::Common; "run_blocking_on_engine_rt", "error", crate::common::log::summary::error(&error));
                        CommonError::RuntimeError
                    })?;
                match handle
                    .join()
                    .and_then(|()| received.recv().map_err(|_| CommonError::RuntimeError))
                {
                    Ok(Ok(v)) => Ok(v),
                    Ok(Err(payload)) => {
                        log_e!(LogType::Common; "run_blocking_on_engine_rt",
                            DESC,
                            format!(
                                "helper thread task panicked: {}",
                                crate::common::log::summary::error(&panic_payload_message(&payload))
                            )
                        );
                        crate::common::retirement::discard_panic_payload(payload);
                        Err(CommonError::RuntimeError)
                    }
                    Err(error) => {
                        log_e!(LogType::Common; "run_blocking_on_engine_rt",
                            DESC,
                            format!("helper thread panicked: {error:?}")
                        );
                        Err(CommonError::RuntimeError)
                    }
                }
            }
            Err(_) => std::panic::catch_unwind(AssertUnwindSafe(f)).map_err(|payload| {
                log_e!(LogType::Common; "run_blocking_on_engine_rt",
                    DESC,
                    format!(
                        "non-runtime thread task panicked: {}",
                        crate::common::log::summary::error(&panic_payload_message(&payload))
                    )
                );
                CommonError::RuntimeError
            }),
        }
    }

    /// async 转同步请求
    pub fn invoke<T, F>(&self, future: T) -> Result<F, CommonError>
    where
        T: Future<Output = F> + Send + 'static,
        F: Send + 'static,
    {
        if self.management_is_closed() {
            return Err(CommonError::PostError);
        }
        crate::log_t!(LogType::Common; "invoke", "future_type", std::any::type_name_of_val(&future));
        let (result_tx, result_rx) = oneshot::channel();
        crate::log_s!(LogType::Common; "invoke", "stage", "submit_sync_task");
        let invoke_future = async move {
            let result = future.await;
            let _ = result_tx.send(result);
        };

        let rt = Arc::clone(&self.rt);
        let sync_tx = self.sync_tx.clone();
        self.run_blocking_on_engine_rt(move || {
            if rt.block_on(sync_tx.send(Box::pin(invoke_future))).is_err() {
                log_e!(LogType::Common; "invoke", DESC, "rt.block_on error");
                return Err(CommonError::PostError);
            }
            result_rx.blocking_recv().map_err(|e| {
                log_e!(LogType::Common; "invoke", DESC, format!("blocking_recv error {}", e));
                CommonError::RuntimeError
            })
        })?
    }

    /// async 转异步请求
    pub fn post<T>(&self, future: T)
    where
        T: Future<Output = ()> + Send + 'static,
    {
        if self.management_is_closed() {
            return;
        }
        crate::log_t!(LogType::Common; "post", "future_type", std::any::type_name_of_val(&future));
        let rt = Arc::clone(&self.rt);
        let async_tx = self.async_tx.clone();
        crate::log_s!(LogType::Common; "post", "stage", "submit_async_task");
        if let Err(error) = self.run_blocking_on_engine_rt(move || {
            let r = rt.block_on(async_tx.send(Box::pin(future)));
            if let Err(error) = r {
                log_e!(LogType::Common; "post",
                    DESC,
                    format!("{}{}", "send async task error: {:?}", error.to_string())
                );
            }
        }) {
            log_e!(LogType::Common; "post",
                DESC,
                format!("run_blocking_on_engine_rt error: {:?}", error)
            );
        }
    }

    /// 为避免回调中的耗时操作阻塞,以及回调中调用其他接口造成死锁,所有回调必须放入线程池执行
    pub fn cb_pool_once<F, R>(&self, cb: F) -> impl FnOnce(R)
    where
        F: FnOnce(R) + Send + 'static,
        R: Send + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_once", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        move |r1| cb_pool.execute_or_log(move || cb(r1))
    }

    /// cb_pool 重载接口,接受两个回调参数
    pub fn cb_pool_once2<F, R1, R2>(&self, cb: F) -> impl FnOnce(R1, R2)
    where
        F: FnOnce(R1, R2) + Send + 'static,
        R1: Send + 'static,
        R2: Send + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_once2", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        move |r1, r2| cb_pool.execute_or_log(move || cb(r1, r2))
    }

    /// cb_pool 重载接口,接受三个回调参数
    pub fn cb_pool_once3<F, R1, R2, R3>(&self, cb: F) -> impl FnOnce(R1, R2, R3)
    where
        F: FnOnce(R1, R2, R3) + Send + 'static,
        R1: Send + 'static,
        R2: Send + 'static,
        R3: Send + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_once3", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        move |r1, r2, r3| cb_pool.execute_or_log(move || cb(r1, r2, r3))
    }

    /// cb_pool 重载接口,接受三个回调参数
    pub fn cb_pool_once3_boxed<F, R1, R2, R3>(
        &self,
        cb: F,
    ) -> Box<dyn FnOnce(R1, R2, R3) + Send + Sync + 'static>
    where
        F: FnOnce(R1, R2, R3) + Send + Sync + 'static,
        R1: Send + 'static,
        R2: Send + 'static,
        R3: Send + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_once3_boxed", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        Box::new(move |r1, r2, r3| cb_pool.execute_or_log(move || cb(r1, r2, r3)))
    }

    /// cb_pool 重载接口,接受零个回调参数,返回 Fn()
    /// 用于包装 Box<dyn Fn()> 类型的 listener
    pub fn cb_pool_fn0_boxed<F>(&self, cb: F) -> Box<dyn Fn() + Send + Sync + 'static>
    where
        F: Fn() + Send + Sync + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_fn0_boxed", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        let cb = Arc::new(cb);
        Box::new(move || {
            let cb_clone = cb.clone();
            cb_pool.execute_or_log(move || cb_clone())
        })
    }

    /// cb_pool 重载接口,接受单个回调参数,返回 Fn(R)
    /// 用于包装 Box<dyn Fn(R)> 类型的 listener
    pub fn cb_pool_fn1_boxed<F, R>(&self, cb: F) -> Box<dyn Fn(R) + Send + Sync + 'static>
    where
        F: Fn(R) + Send + Sync + 'static,
        R: Send + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_fn1_boxed", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        let cb = Arc::new(cb);
        Box::new(move |r| {
            let cb_clone = cb.clone();
            cb_pool.execute_or_log(move || cb_clone(r))
        })
    }

    /// cb_pool 重载接口,接受两个回调参数,返回 Fn(R1, R2)
    /// 用于包装 Box<dyn Fn(R1, R2)> 类型的 listener
    pub fn cb_pool_fn2_boxed<F, R1, R2>(&self, cb: F) -> Box<dyn Fn(R1, R2) + Send + Sync + 'static>
    where
        F: Fn(R1, R2) + Send + Sync + 'static,
        R1: Send + 'static,
        R2: Send + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_fn2_boxed", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        let cb = Arc::new(cb);
        Box::new(move |r1, r2| {
            let cb_clone = cb.clone();
            cb_pool.execute_or_log(move || cb_clone(r1, r2))
        })
    }

    pub fn cb_pool_process_cloneable<F, R1, R2>(
        &self,
        cb: F,
    ) -> impl Fn(R1, R2) + Clone + Send + Sync + 'static
    where
        F: Fn(R1, R2) + Clone + Send + Sync + 'static,
        R1: Send + 'static,
        R2: Send + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_process_cloneable", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        let cb = Arc::new(cb);
        move |r1, r2| {
            let cb_clone = cb.clone();
            cb_pool.execute_or_log(move || cb_clone(r1, r2))
        }
    }

    pub fn cb_pool_process<F, R1, R2>(&self, cb: F) -> impl Fn(R1, R2) + Send + Sync + 'static
    where
        F: Fn(R1, R2) + Send + Sync + 'static,
        R1: Send + 'static,
        R2: Send + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_process", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        let cb = Arc::new(cb);
        move |r1, r2| {
            let cb_clone = cb.clone();
            cb_pool.execute_or_log(move || cb_clone(r1, r2))
        }
    }

    /// cb_pool 重载接口,接受三个回调参数,返回 Fn(R1, R2, R3)
    /// 用于包装 Box<dyn Fn(R1, R2, R3)> 类型的 listener
    pub fn cb_pool_fn3_boxed<F, R1, R2, R3>(
        &self,
        cb: F,
    ) -> Box<dyn Fn(R1, R2, R3) + Send + Sync + 'static>
    where
        F: Fn(R1, R2, R3) + Send + Sync + 'static,
        R1: Send + 'static,
        R2: Send + 'static,
        R3: Send + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_fn3_boxed", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        let cb = Arc::new(cb);
        Box::new(move |r1, r2, r3| {
            let cb_clone = cb.clone();
            cb_pool.execute_or_log(move || cb_clone(r1, r2, r3))
        })
    }

    /// cb_pool 重载接口,接受四个回调参数,返回 Fn(R1, R2, R3, R4)
    /// 用于包装 Box<dyn Fn(R1, R2, R3, R4)> 类型的 listener
    pub fn cb_pool_fn4_boxed<F, R1, R2, R3, R4>(
        &self,
        cb: F,
    ) -> Box<dyn Fn(R1, R2, R3, R4) + Send + Sync + 'static>
    where
        F: Fn(R1, R2, R3, R4) + Send + Sync + 'static,
        R1: Send + 'static,
        R2: Send + 'static,
        R3: Send + 'static,
        R4: Send + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_fn4_boxed", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        let cb = Arc::new(cb);
        Box::new(move |r1, r2, r3, r4| {
            let cb_clone = cb.clone();
            cb_pool.execute_or_log(move || cb_clone(r1, r2, r3, r4))
        })
    }

    /// cb_pool 重载接口,接受五个回调参数,返回 Fn(R1, R2, R3, R4, R5)
    /// 用于包装 Box<dyn Fn(R1, R2, R3, R4, R5)> 类型的 listener
    pub fn cb_pool_fn5_boxed<F, R1, R2, R3, R4, R5>(
        &self,
        cb: F,
    ) -> Box<dyn Fn(R1, R2, R3, R4, R5) + Send + Sync + 'static>
    where
        F: Fn(R1, R2, R3, R4, R5) + Send + Sync + 'static,
        R1: Send + 'static,
        R2: Send + 'static,
        R3: Send + 'static,
        R4: Send + 'static,
        R5: Send + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_fn5_boxed", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        let cb = Arc::new(cb);
        Box::new(move |r1, r2, r3, r4, r5| {
            let cb_clone = cb.clone();
            cb_pool.execute_or_log(move || cb_clone(r1, r2, r3, r4, r5))
        })
    }

    /// cb_pool 重载接口,接受单个 &R1 回调参数,返回 Fn(&R1,R2)
    /// 用于包装 Box<dyn Fn(&R1,R2)> 类型的 listener
    pub fn cb_pool_fn2_ref_boxed<F, R1, R2>(
        &self,
        cb: F,
    ) -> Box<dyn Fn(&R1, R2) + Send + Sync + 'static>
    where
        F: Fn(&R1, R2) + Send + Sync + 'static,
        R1: Clone + Send + 'static,
        R2: Send + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_fn2_ref_boxed", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        let cb = Arc::new(cb);
        Box::new(move |r1, r2| {
            let r1 = r1.clone();
            let cb_clone = cb.clone();
            cb_pool.execute_or_log(move || cb_clone(&r1, r2))
        })
    }

    /// cb_pool 重载接口,接受单个 &str 回调参数,返回 Fn(&str)
    /// 用于包装 Box<dyn Fn(&str)> 类型的 listener
    pub fn cb_pool_fn_str_boxed<F>(&self, cb: F) -> Box<dyn Fn(&str) + Send + Sync + 'static>
    where
        F: Fn(&str) + Send + Sync + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_fn_str_boxed", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        let cb = Arc::new(cb);
        Box::new(move |s: &str| {
            let s_clone = s.to_string();
            let cb_clone = cb.clone();
            cb_pool.execute_or_log(move || cb_clone(&s_clone))
        })
    }

    /// cb_pool 重载接口,接受两个回调参数(第一个是 &str),返回 Fn(&str, R2)
    /// 用于包装 Box<dyn Fn(&str, R2)> 类型的 listener
    pub fn cb_pool_fn2_str_boxed<F, R2>(
        &self,
        cb: F,
    ) -> Box<dyn Fn(&str, R2) + Send + Sync + 'static>
    where
        F: Fn(&str, R2) + Send + Sync + 'static,
        R2: Send + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_fn2_str_boxed", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        let cb = Arc::new(cb);
        Box::new(move |s: &str, r2: R2| {
            let s_clone = s.to_string();
            let cb_clone = cb.clone();
            cb_pool.execute_or_log(move || cb_clone(&s_clone, r2))
        })
    }

    /// cb_pool 重载接口,接受三个回调参数(第一个是 &str),返回 Fn(&str, R2, R3)
    /// 用于包装 Box<dyn Fn(&str, R2, R3)> 类型的 listener
    pub fn cb_pool_fn3_str_boxed<F, R2, R3>(
        &self,
        cb: F,
    ) -> Box<dyn Fn(&str, R2, R3) + Send + Sync + 'static>
    where
        F: Fn(&str, R2, R3) + Send + Sync + 'static,
        R2: Send + 'static,
        R3: Send + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_fn3_str_boxed", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        let cb = Arc::new(cb);
        Box::new(move |s: &str, r2: R2, r3: R3| {
            let s_clone = s.to_string();
            let cb_clone = cb.clone();
            cb_pool.execute_or_log(move || cb_clone(&s_clone, r2, r3))
        })
    }

    /// cb_pool 重载接口,接受四个回调参数(第一个是 &str),返回 Fn(&str, R2, R3, R4)
    /// 用于包装 Box<dyn Fn(&str, R2, R3, R4)> 类型的 listener
    pub fn cb_pool_fn4_str_boxed<F, R2, R3, R4>(
        &self,
        cb: F,
    ) -> Box<dyn Fn(&str, R2, R3, R4) + Send + Sync + 'static>
    where
        F: Fn(&str, R2, R3, R4) + Send + Sync + 'static,
        R2: Send + 'static,
        R3: Send + 'static,
        R4: Send + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_fn4_str_boxed", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        let cb = Arc::new(cb);
        Box::new(move |s: &str, r2: R2, r3: R3, r4: R4| {
            let s_clone = s.to_string();
            let cb_clone = cb.clone();
            cb_pool.execute_or_log(move || cb_clone(&s_clone, r2, r3, r4))
        })
    }

    /// cb_pool 重载接口,接受四个回调参数(第一个和第四个是 &str),返回 Fn(&str, R2, R3, &str)
    /// 用于包装 Box<dyn Fn(&str, R2, R3, &str)> 类型的 listener
    pub fn cb_pool_fn4_str_str4_boxed<F, R2, R3>(
        &self,
        cb: F,
    ) -> Box<dyn Fn(&str, R2, R3, &str) + Send + Sync + 'static>
    where
        F: Fn(&str, R2, R3, &str) + Send + Sync + 'static,
        R2: Send + 'static,
        R3: Send + 'static,
    {
        crate::log_t!(LogType::Common; "cb_pool_fn4_str_str4_boxed", "callback_type", std::any::type_name_of_val(&cb));
        let cb_pool = self.cb_pool.clone();
        let cb = Arc::new(cb);
        Box::new(move |s1: &str, r2: R2, r3: R3, s2: &str| {
            let s1_clone = s1.to_string();
            let s2_clone = s2.to_string();
            let cb_clone = cb.clone();
            cb_pool.execute_or_log(move || cb_clone(&s1_clone, r2, r3, &s2_clone))
        })
    }
}