open-net 0.3.2

A cross-platform async networking library with WebSocket clients and network status monitoring.
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
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;

use crate::common::log::log_def::LogType;
use crate::common::CommonEngine;
use n0_watcher::Watcher as _;
use tokio::sync::{oneshot, watch};
use tokio::time::{self, MissedTickBehavior};

use super::monitor_runtime::{MonitorCompletion, MonitorInitialization, MonitorRuntime};
use super::monitor_state::MonitorState;
use super::network_status_snapshot::{
    NetworkPublication, NetworkStatusPublisher, NetworkStatusSnapshot, NetworkStatusSource,
};
use super::platform::PlatformNetworkMonitor;
use super::refresh_trigger::{request_refresh_or_stop, RefreshWorkOutcome};
use crate::error::NetError;
use crate::module::net_status::logging::{Fault, FaultCycle};
use crate::module::net_status::{IpStack, NetworkStatus};
use crate::net_status::{MonitorState as PublicMonitorState, NetworkSnapshot};
use crate::subscription::common_executor::CommonCallbackExecutor;
use crate::subscription::StateReceiver;

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

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

#[derive(Default)]
// 客户端生命周期状态;短时同步锁串行化启动、停止和永久销毁。
struct Lifecycle {
    // 当前可接受更新的监控代;停止时先移出,再异步等待其完成。
    monitor: Option<MonitorRuntime>,
    /// Keep completion receivers after signaling stop, including when a caller
    /// cancels shutdown. A later destroy must still await these native resources.
    // 已请求停止或自行退休但尚未完成内部资源清理的监控代,供后续 shutdown/destroy 等待。
    stopping: Vec<watch::Receiver<bool>>,
    // 永久销毁标志;一旦置位,后续 start 不再允许创建监控任务。
    destroyed: bool,
}

// 在首次轮询之前即持有的一代退出守卫;清理不依赖 start 的等待者仍然存在。
struct MonitorTaskCompletion {
    // 弱引用避免后台任务与客户端形成所有权环,仅退休身份匹配的当前监控代。
    lifecycle: Weak<Mutex<Lifecycle>>,
    // 该代唯一有效性标志,其 Arc 身份同时用于防止旧代清理误删新代。
    active: Arc<AtomicBool>,
    // 监控代的退休屏障;退出时完成内部状态清理后再通知等待者。
    state: Arc<Mutex<MonitorState>>,
    // 失败或取消时在资源清理完成后唤醒所有同代初始化等待者。
    initial_state: watch::Sender<MonitorInitialization>,
    // 正常构造或首轮发布返回的初始化错误,取消未轮询任务时使用 RuntimeError。
    initialization_error: Option<NetError>,
    // 退出时重置本代内部观测;旧发布器不会覆盖新代观测。
    observation: NetworkStatusPublisher,
    // 内部资源清理后发布完成;任意用户捕获析构不包含在等待范围内,避免重入销毁自等。
    completion: Option<MonitorCompletion>,
}

impl Drop for MonitorTaskCompletion {
    // 原子地退休句柄并保留完成接收端;内部资源就绪后发布结果,再锁外释放用户捕获。
    fn drop(&mut self) {
        let stopped = !self.active.swap(false, Ordering::AcqRel);
        let retired = self.lifecycle.upgrade().and_then(|lifecycle| {
            let mut lifecycle = match lifecycle.lock() {
                Ok(lifecycle) => lifecycle,
                Err(poisoned) => {
                    crate::log_e!(LogType::Engine; "network_status_monitor_exit", "error", "lifecycle_lock_poisoned_recovered");
                    poisoned.into_inner()
                }
            };
            if lifecycle
                .monitor
                .as_ref()
                .is_some_and(|monitor| Arc::ptr_eq(&monitor.active, &self.active))
            {
                let monitor = lifecycle.monitor.take();
                if let Some(monitor) = &monitor {
                    lifecycle.stopping.push(monitor.finished.clone());
                }
                monitor
            } else {
                None
            }
        });
        // Preserve the original retirement barrier before signalling native completion.
        {
            let _state = match self.state.lock() {
                Ok(state) => state,
                Err(poisoned) => {
                    crate::log_e!(LogType::Engine; "network_status_monitor_exit", "error", "state_lock_poisoned_recovered");
                    poisoned.into_inner()
                }
            };
        }
        let failure = self.initialization_error.clone().or_else(|| {
            (!stopped).then(|| NetError::from(crate::error::ErrorKind::RuntimeUnavailable))
        });
        let terminal = failure
            .clone()
            .map_or(PublicMonitorState::Stopped, PublicMonitorState::Failed);
        let publication = self.observation.prepare_finish(terminal);
        drop(retired);
        drop(self.completion.take());
        self.initial_state.send_if_modified(|initial| {
            if !matches!(initial, MonitorInitialization::Pending) {
                return false;
            }
            *initial = match failure {
                Some(error) => MonitorInitialization::Failed(error),
                None if stopped => MonitorInitialization::Stopped,
                None => MonitorInitialization::Failed(NetError::from(
                    crate::error::ErrorKind::RuntimeUnavailable,
                )),
            };
            true
        });
        // User wakes and captures may synchronously wait for destroy. Signal completion first.
        if let Err(error) = publication.and_then(NetworkPublication::dispatch) {
            crate::log_e!(LogType::Engine; "net_status.drop", "event|kind|stage", "network_status_monitor_exit", format!("{:?}", error.kind()), format!("{:?}", error.context().stage));
        }
    }
}

// 网络状态客户端内部实现,连接引擎运行时、单代监控生命周期与跨代观测源。
pub(crate) struct InnerNetStatusClient {
    // 提供 Tokio 运行时与公开监听器回调线程池的共享引擎。
    engine: Arc<CommonEngine>,
    // 保护监控任务及销毁状态;异步等待完成信号时不持有该锁。
    lifecycle: Arc<Mutex<Lifecycle>>,
    // 统一快照源;公开订阅复用引擎回调池,私有 watch 维持 WS 的网络门控时序。
    observations: NetworkStatusSource,
    #[cfg(any(target_os = "windows", test))]
    windows_sampler: Arc<super::refresh::WindowsSampler>,
    #[cfg(any(target_os = "windows", test))]
    windows_reachability_sampler: Arc<super::refresh::WindowsSampler>,
    // 测试专用的安全初始化工厂,用于精确控制失败与并发时机,不改变生产构建。
    #[cfg(test)]
    monitor_factory: Mutex<Option<initialization_tests::MonitorFactory>>,
    #[cfg(test)]
    monitor_task: Mutex<Option<tokio::task::AbortHandle>>,
}

impl InnerNetStatusClient {
    // 创建未启动的客户端,持有共享引擎并将内部观测初始化为未知。
    pub(crate) fn new(engine: Arc<CommonEngine>) -> Result<Self, NetError> {
        let executor = Arc::new(CommonCallbackExecutor::new(&engine));
        let observations =
            NetworkStatusSource::new(executor, 1024)?.with_retirement(engine.retirement_work());
        #[cfg(any(target_os = "windows", test))]
        let (windows_sampler, windows_reachability_sampler) =
            super::refresh::WindowsSampler::pair(engine.resource_threads());
        Ok(Self {
            engine,
            lifecycle: Arc::new(Mutex::new(Lifecycle::default())),
            observations,
            #[cfg(any(target_os = "windows", test))]
            windows_sampler,
            #[cfg(any(target_os = "windows", test))]
            windows_reachability_sampler,
            #[cfg(test)]
            monitor_factory: Mutex::new(None),
            #[cfg(test)]
            monitor_task: Mutex::new(None),
        })
    }

    /// Observe ordered network facts without involving the public callback pool.
    /// Before initialization and after monitoring stops, the status is Unknown.
    #[cfg_attr(not(any(feature = "ws-client", test)), allow(dead_code))]
    // 订阅内部快照而不启动监控;尚无观测或停止后的状态为 None,表示未知。
    pub(crate) fn subscribe(&self) -> watch::Receiver<NetworkStatusSnapshot> {
        self.observations.subscribe()
    }

    pub(crate) fn subscribe_facts(&self) -> watch::Receiver<NetworkSnapshot> {
        self.observations.subscribe_facts()
    }

    pub(super) fn observation_source(&self) -> NetworkStatusSource {
        self.observations.clone()
    }

    #[cfg(any(target_os = "windows", test))]
    pub(super) fn windows_sampler(&self) -> Arc<super::refresh::WindowsSampler> {
        self.windows_sampler.clone()
    }

    #[cfg(any(target_os = "windows", test))]
    pub(super) fn windows_reachability_sampler(&self) -> Arc<super::refresh::WindowsSampler> {
        self.windows_reachability_sampler.clone()
    }

    pub(crate) fn subscribe_failure(&self) -> watch::Receiver<Option<NetError>> {
        self.observations.subscribe_failure()
    }

    #[cfg(test)]
    pub(crate) fn set_monitor_factory_for_test(
        &self,
        factory: initialization_tests::MonitorFactory,
    ) -> Result<(), NetError> {
        *self.monitor_factory.lock().map_err(NetError::from_poison)? = Some(factory);
        Ok(())
    }

    #[cfg(test)]
    pub(crate) fn abort_monitor_task_for_test(&self) -> Result<(), NetError> {
        let task = self.monitor_task.lock().map_err(NetError::from_poison)?;
        match task.as_ref() {
            Some(task) => {
                task.abort();
                Ok(())
            }
            None => Err(NetError::from(crate::error::ErrorKind::Internal)),
        }
    }

    #[cfg(test)]
    pub(crate) fn exhaust_source_revision_for_test(&self) -> Result<(), NetError> {
        self.observations.exhaust_revision_for_test()
    }

    #[cfg(test)]
    pub(crate) fn publish_observation_for_test(
        &self,
        status: NetworkStatus,
        ip: IpStack,
        name: Option<String>,
    ) -> Result<(), NetError> {
        let state = self
            .current_state()?
            .ok_or_else(|| NetError::from(crate::error::ErrorKind::Internal))?;
        let publication = {
            let state = state.lock().map_err(NetError::from_poison)?;
            let publisher = state
                .observation
                .as_ref()
                .ok_or_else(|| NetError::from(crate::error::ErrorKind::Internal))?;
            publisher.prepare_observation(status, Some(ip), name)?
        };
        publication.dispatch()
    }

    // 幂等启动并等待同代初始化结果;失败代先完成退休,再将错误交付所有等待者。
    // stop 取消初始化时返回当前快照;永久销毁优先返回 Closed。
    pub(crate) async fn start(&self) -> Result<NetworkSnapshot, NetError> {
        let (mut initial_state, task, publication) = loop {
            let retiring = {
                let mut lifecycle = self.lifecycle.lock().map_err(NetError::from_poison)?;
                if lifecycle.destroyed {
                    return Err(NetError::from(crate::error::ErrorKind::Closed));
                }
                lifecycle
                    .stopping
                    .retain(|finished| !*::tokio::sync::watch::Receiver::borrow(finished));
                if lifecycle.stopping.is_empty() {
                    let (task, publication) = if lifecycle.monitor.is_none() {
                        match self.prepare_monitor_task() {
                            Ok((monitor, task, publication)) => {
                                lifecycle.monitor = Some(monitor);
                                (Some(task), Some(publication))
                            }
                            Err(error) => {
                                // The source must remember an infrastructure
                                // preparation failure before another lease can
                                // retry it. Commit the failure only after the
                                // lifecycle lock is released so no notification
                                // can re-enter this lock.
                                drop(lifecycle);
                                match self.observations.fail(error.clone()) {
                                    Ok(publication) => {
                                        if let Err(dispatch_error) = publication.dispatch() {
                                            crate::log_e!(LogType::Engine; "net_status.start", "event|kind|stage", "network_status_start_failure", format!("{:?}", dispatch_error.kind()), format!("{:?}", dispatch_error.context().stage));
                                        }
                                    }
                                    Err(failure_error) => {
                                        crate::log_e!(LogType::Engine; "net_status.start", "event|kind|stage", "network_status_start_failure", format!("{:?}", failure_error.kind()), format!("{:?}", failure_error.context().stage));
                                    }
                                }
                                return Err(error);
                            }
                        }
                    } else {
                        (None, None)
                    };
                    let monitor = lifecycle
                        .monitor
                        .as_ref()
                        .ok_or(NetError::from(crate::error::ErrorKind::Internal))?;
                    break (monitor.initial_state.clone(), task, publication);
                }
                lifecycle.stopping.clone()
            };
            // A retired outer future can finish before netwatch's actor and
            // platform tasks do. Recheck under the lock only after all of that
            // generation's provider resources have left their private runtime.
            Self::wait_until_finished(retiring).await?;
        };
        // A failed preparation owns deferred cleanup. Retire its unpolled task first;
        // normal notifications must follow submission because a user waker may await shutdown.
        if let Err(error) = publication
            .as_ref()
            .map(NetworkPublication::result)
            .transpose()
        {
            drop(task);
            if let Some(publication) = publication {
                if let Err(dispatch_error) = publication.dispatch() {
                    crate::log_e!(LogType::Engine; "net_status.start", "event|kind|stage", "network_status_start", format!("{:?}", dispatch_error.kind()), format!("{:?}", dispatch_error.context().stage));
                }
            }
            return Err(error);
        }
        // 退出守卫也会获取生命周期锁;在锁外提交,覆盖运行时拒绝未轮询任务的路径。
        if let Some(task) = task {
            let submitted = self.engine.runtime_handle().spawn(task);
            #[cfg(test)]
            {
                *self.monitor_task.lock().map_err(NetError::from_poison)? =
                    Some(submitted.abort_handle());
            }
            #[cfg(not(test))]
            drop(submitted);
        }
        if let Some(publication) = publication {
            publication.dispatch()?;
        }
        while matches!(
            *initial_state.borrow_and_update(),
            MonitorInitialization::Pending
        ) {
            if initial_state.changed().await.is_err() {
                break;
            }
        }
        if self
            .lifecycle
            .lock()
            .map_err(NetError::from_poison)?
            .destroyed
        {
            return Err(NetError::from(crate::error::ErrorKind::Closed));
        }
        let result = ::tokio::sync::watch::Receiver::borrow(&initial_state).clone();
        match result {
            MonitorInitialization::Ready | MonitorInitialization::Stopped => self.snapshot(),
            MonitorInitialization::Failed(error) => Err(error),
            MonitorInitialization::Pending => {
                Err(NetError::from(crate::error::ErrorKind::RuntimeUnavailable))
            }
        }
    }

    // 创建独立监控代、信号与尚未提交的 Future,由 start 安装句柄后在生命周期锁外启动。
    // 退出守卫在首次轮询前就由 Future 持有,覆盖取消等待、未轮询释放及异常退出。
    fn prepare_monitor_task(
        &self,
    ) -> Result<
        (
            MonitorRuntime,
            impl std::future::Future<Output = ()> + Send + 'static,
            NetworkPublication,
        ),
        NetError,
    > {
        #[cfg(test)]
        let factory = self
            .monitor_factory
            .lock()
            .map_err(NetError::from_poison)?
            .clone();
        let (stop_sender, stop_receiver) = oneshot::channel();
        let (initial_sender, initial_state) = watch::channel(MonitorInitialization::Pending);
        let (finished_sender, finished) = watch::channel(false);
        let (publisher, publication) = self.observations.begin_generation()?;
        let state = MonitorState {
            observation: Some(publisher.clone()),
            ..MonitorState::default()
        };
        let active = Arc::clone(&state.active);
        let state = Arc::new(Mutex::new(state));
        let shared_state = Arc::clone(&state);
        let completion = MonitorTaskCompletion {
            lifecycle: Arc::downgrade(&self.lifecycle),
            active: Arc::clone(&active),
            state: Arc::clone(&state),
            initial_state: initial_sender.clone(),
            initialization_error: publication.result().err(),
            observation: publisher,
            completion: Some(MonitorCompletion(finished_sender)),
        };
        // CommonEngine coordinates submission; each provider generation owns a
        // dedicated runtime because netwatch detaches nested platform tasks and
        // exposes no join API. Dropping that runtime on its ordinary thread
        // drains async tasks and blocking work before the completion guard runs.
        #[cfg(target_os = "windows")]
        let windows_sampler = self.windows_sampler.clone();
        #[cfg(target_os = "windows")]
        let windows_reachability_sampler = self.windows_reachability_sampler.clone();
        let threads = self.engine.resource_threads();
        let task = async move {
            let (submission_alive, submission_cancelled) = oneshot::channel::<()>();
            let (thread_finished, thread_wait) = oneshot::channel();
            let spawned = threads.spawn("open-net-network-monitor", move || {
                    // Declared before runtime: unwinding also destroys runtime
                    // resources before publishing this generation's completion.
                    let mut completion = completion;
                    let runtime = match tokio::runtime::Builder::new_current_thread()
                        .enable_all()
                        .build()
                    {
                        Ok(runtime) => runtime,
                        Err(error) => {
                            completion.initialization_error = Some(NetError::with_source(
                                crate::error::ErrorKind::RuntimeUnavailable,
                                error,
                            ));
                            return;
                        }
                    };
                    let outcome = runtime.block_on(async move {
                        tokio::select! {
                            biased;
                            _ = submission_cancelled => Err(NetError::from(crate::error::ErrorKind::RuntimeUnavailable)),
                            result = Self::monitor_until_stopped(
                                shared_state,
                                stop_receiver,
                                initial_sender,
                                #[cfg(target_os = "windows")]
                                windows_sampler,
                                #[cfg(target_os = "windows")]
                                windows_reachability_sampler,
                                #[cfg(test)]
                                factory,
                            ) => result,
                        }
                    });
                    drop(runtime);
                    if let Err(error) = outcome {
                        completion.initialization_error = Some(error);
                    }
                    drop(completion);
                    let _ = thread_finished.send(());
                });
            if let Err(error) = spawned {
                // The rejected closure already dropped its unpolled guard;
                // initialization waiters receive RuntimeUnavailable.
                crate::log_e!(LogType::Engine; "net_status.prepare_monitor_task", "kind|stage", format!("{:?}", error.kind()), "NetworkMonitor");
            }
            // Cancelling CommonEngine's task cancels the provider future, but
            // the independent thread retains ownership of its real exit guard.
            let _ = thread_wait.await;
            drop(submission_alive);
        };
        let monitor = MonitorRuntime {
            stop_sender: Some(stop_sender),
            initial_state,
            finished,
            state,
            active,
        };
        Ok((monitor, task, publication))
    }

    // Commit the stop while holding the lifecycle lock; notify public observers afterwards.
    pub(crate) fn request_stop(
        &self,
        permanent: bool,
    ) -> (Vec<watch::Receiver<bool>>, Option<NetError>) {
        #[cfg(any(target_os = "windows", test))]
        if permanent {
            // Explicit engine shutdown must release the sampling lanes even
            // while applications retain clients or read-only contexts.
            self.windows_sampler.close();
            self.windows_reachability_sampler.close();
        }
        let mut error = None;
        let (finished, retired, publication) = {
            let mut lifecycle = match self.lifecycle.lock() {
                Ok(lifecycle) => lifecycle,
                Err(poisoned) => {
                    error = Some(NetError::from(crate::error::ErrorKind::Internal));
                    poisoned.into_inner()
                }
            };
            lifecycle.destroyed |= permanent;
            let mut retired = lifecycle.monitor.take();
            if let Some(monitor) = &mut retired {
                monitor.active.store(false, Ordering::Release);
                if let Some(stop) = monitor.stop_sender.take() {
                    let _ = stop.send(());
                }
                lifecycle.stopping.push(monitor.finished.clone());
            }
            let publication = if permanent {
                self.observations.prepare_closed()
            } else {
                self.observations.prepare_stopped()
            };
            lifecycle
                .stopping
                .retain(|finished| !*::tokio::sync::watch::Receiver::borrow(finished));
            (lifecycle.stopping.clone(), retired, publication)
        };
        drop(retired);
        if let Err(publication_error) = publication.and_then(NetworkPublication::dispatch) {
            crate::log_e!(LogType::Engine; "net_status.request_stop", "permanent|kind|stage", permanent, format!("{:?}", publication_error.kind()), format!("{:?}", publication_error.context().stage));
            error = Some(publication_error);
        }
        (finished, error)
    }

    // 逐一等待真实退出;丢失完成发送端不等于资源已退出,不允许据此重启。
    pub(crate) async fn wait_until_finished(
        finished: Vec<watch::Receiver<bool>>,
    ) -> Result<(), NetError> {
        for mut receiver in finished {
            while !*receiver.borrow_and_update() {
                if receiver.changed().await.is_err() {
                    return Err(NetError::from(crate::error::ErrorKind::RuntimeUnavailable));
                }
            }
        }
        Ok(())
    }

    // 停止当前监控并等待所有退役监控释放资源,之后允许重新启动;透传同步清理阶段的错误。
    pub(crate) async fn stop(&self) -> Result<(), NetError> {
        let (finished, error) = self.request_stop(false);
        Self::wait_until_finished(finished).await?;
        error.map_or(Ok(()), Err)
    }

    // 发出永久销毁请求并禁止后续启动;此同步入口不等待异步监控资源清理完成。
    pub(crate) fn request_destroy(&self) {
        self.request_stop(true);
    }

    // 永久销毁客户端并等待已有监控清理完成,返回停止过程中记录的错误。
    pub(crate) async fn destroy(&self) -> Result<(), NetError> {
        let (finished, error) = self.request_stop(true);
        Self::wait_until_finished(finished).await?;
        error.map_or(Ok(()), Err)
    }

    pub(crate) async fn shutdown(&self) -> Result<(), NetError> {
        self.destroy().await
    }

    pub(crate) fn snapshot(&self) -> Result<NetworkSnapshot, NetError> {
        self.observations.snapshot()
    }

    pub(crate) fn subscribe_state(&self) -> Result<StateReceiver<NetworkSnapshot>, NetError> {
        self.observations.observe()
    }

    #[cfg(test)]
    fn current_state(&self) -> Result<Option<Arc<Mutex<MonitorState>>>, NetError> {
        Ok(self
            .lifecycle
            .lock()
            .map_err(NetError::from_poison)?
            .monitor
            .as_ref()
            .map(|monitor| Arc::clone(&monitor.state)))
    }

    #[cfg(test)]
    fn is_started(&self) -> bool {
        matches!(self.snapshot(), Ok(snapshot) if matches!(snapshot.state, PublicMonitorState::Running))
    }

    // 按默认路由与 IP 能力推导可达性:同时具备默认路由及至少一种 IP 能力时为 Available。
    #[cfg(any(not(any(target_os = "linux", target_os = "windows")), test))]
    fn reachability_from_flags(
        has_default_route: bool,
        have_v4: bool,
        have_v6: bool,
    ) -> NetworkStatus {
        if has_default_route && (have_v4 || have_v6) {
            NetworkStatus::Available
        } else {
            NetworkStatus::Unavailable
        }
    }

    // 从 netwatch 接口快照提取默认路由与 IPv4/IPv6 标志,转换为本库的可达性枚举。
    #[cfg(not(any(target_os = "linux", target_os = "windows")))]
    fn reachability_from_state(state: &netwatch::netmon::State) -> NetworkStatus {
        Self::reachability_from_flags(
            state.default_route_interface.is_some(),
            state.have_v4,
            state.have_v6,
        )
    }

    /// Derive the IP-stack capability from the `netwatch` interface state. This
    /// uses the same `have_v4` / `have_v6` flags on every platform, so the
    /// reported value has consistent cross-platform semantics.
    // 将 netwatch 的 IPv4/IPv6 能力标志映射为 IP 栈枚举,各平台使用同一套映射规则。
    fn ip_stack_from_state(state: &netwatch::netmon::State) -> IpStack {
        IpStack::from_flags(state.have_v4, state.have_v6)
    }

    // Linux additionally checks operational links and IPv6 on-link defaults.
    // Cancel slow platform reads on stop; the read-only worker cannot publish
    // into this or a later generation. Other platforms retain their exact query.
    #[cfg(not(target_os = "windows"))]
    async fn reachability_or_stop(
        snapshot: &netwatch::netmon::State,
        _stop_receiver: &mut oneshot::Receiver<()>,
    ) -> Result<Option<NetworkStatus>, NetError> {
        #[cfg(target_os = "linux")]
        {
            tokio::select! {
                biased;
                _ = &mut *_stop_receiver => Ok(None),
                result = super::platform::linux::current_reachability(snapshot) => result.map(Some),
            }
        }
        #[cfg(not(target_os = "linux"))]
        {
            Ok(Some(Self::reachability_from_state(snapshot)))
        }
    }

    // One authoritative snapshot contains reachability and IP capability. Public wakeups,
    // user captures and callback scheduling are all released outside the monitor lock.
    #[cfg(any(not(target_os = "windows"), test))]
    fn update_state_inner(
        state: &Arc<Mutex<MonitorState>>,
        reachability: NetworkStatus,
        ip_stack: IpStack,
    ) -> Result<(), NetError> {
        let network_name = None;
        let publication = {
            let guard = state.lock().map_err(NetError::from_poison)?;
            if !guard.active.load(Ordering::Acquire) {
                return Ok(());
            }
            match &guard.observation {
                Some(observation) => Some(observation.prepare_observation(
                    reachability,
                    Some(ip_stack),
                    network_name,
                )?),
                None => None,
            }
        };
        if let Some(publication) = publication {
            publication.dispatch()?;
        }
        Ok(())
    }

    /// Monitor task body: ported from the reference project's
    /// `monitor_until_stopped`, but the state comes from the instance rather
    /// than a global.
    ///
    /// Initialization errors reach every caller waiting on this generation's
    /// start result. Later observation failures end the task; its completion
    /// guard retires the generation and resets its state.
    // 初始化 netwatch 并发布首轮观测,然后处理接口更新、原生刷新提示、定时复查与优先停止信号。
    // 原生事件仅请求 netwatch 刷新,不能直接作为可达性事实;初始化失败保留内部未知状态。
    // 退出时释放平台监控并重置公开状态,内部未知状态及完成通知由任务所持守卫负责发布。
    async fn monitor_until_stopped(
        state: Arc<Mutex<MonitorState>>,
        mut stop_receiver: oneshot::Receiver<()>,
        initial_state: watch::Sender<MonitorInitialization>,
        #[cfg(target_os = "windows")] windows_sampler: Arc<super::refresh::WindowsSampler>,
        #[cfg(target_os = "windows")] windows_reachability_sampler: Arc<
            super::refresh::WindowsSampler,
        >,
        #[cfg(test)] factory: Option<initialization_tests::MonitorFactory>,
    ) -> Result<(), NetError> {
        let monitor = tokio::select! {
            biased;
            _ = &mut stop_receiver => return Ok(()),
            result = Self::create_monitor(
                #[cfg(test)]
                factory,
            ) => result,
        };
        let monitor = match monitor {
            Ok(monitor) => monitor,
            Err(error) => {
                // Detector failure is not evidence of an unavailable network.
                // Completion publishes Failed with no current observation.
                return Err(error);
            }
        };
        let mut interface_state = monitor.interface_state();

        let mut refresh_faults = FaultCycle::default();
        #[cfg(target_os = "windows")]
        let mut reachability_faults = FaultCycle::default();
        let initial = interface_state.get();
        if !Self::observe_or_stop(
            &state,
            &initial,
            &mut stop_receiver,
            #[cfg(target_os = "windows")]
            &windows_reachability_sampler,
            #[cfg(target_os = "windows")]
            &mut reachability_faults,
        )
        .await?
        {
            return Ok(());
        }
        initial_state.send_replace(MonitorInitialization::Ready);

        // The native macOS source is an optional post-initialization hint. A
        // yield after publishing the authoritative netwatch state ensures its
        // creation is not part of `NetStatusClient::start`'s initial-state barrier.
        #[cfg(target_os = "macos")]
        tokio::task::yield_now().await;
        let mut platform_monitor = PlatformNetworkMonitor::start();

        let mut refresh_interval = time::interval(Duration::from_secs(2));
        refresh_interval.set_missed_tick_behavior(MissedTickBehavior::Skip);

        let observations = async {
            loop {
                tokio::select! {
                    biased;
                    _ = &mut stop_receiver => break,
                    update = interface_state.updated() => {
                        match update {
                            Ok(new_state) => {
                                if !Self::resample_or_stop(&state, &new_state, &mut stop_receiver,
                                    #[cfg(target_os = "windows")] &windows_reachability_sampler,
                                    #[cfg(target_os = "windows")] &mut reachability_faults,
                                ).await? {
                                    break;
                                }
                            }
                            Err(_) => break,
                        }
                    }
                    native_changed = platform_monitor.changed() => {
                        if native_changed {
                            match request_refresh_or_stop(
                                &mut stop_receiver,
                                || monitor.network_change(),
                            ).await {
                                RefreshWorkOutcome::Stopped => break,
                                RefreshWorkOutcome::Requested => refresh_faults.recovered("refresh_request"),
                                RefreshWorkOutcome::RequestFailed => refresh_faults.failure("refresh_request", Fault::RefreshRequest),
                            }
                        }
                    }
                    _ = refresh_interval.tick() => {
                        // netwatch 0.18 does not subscribe to Linux link changes.
                        // Re-sample instead of only re-reading its cached state;
                        // the request is asynchronous and updates arrive above.
                        #[cfg(target_os = "linux")]
                        match request_refresh_or_stop(
                            &mut stop_receiver,
                            || monitor.network_change(),
                        ).await {
                            RefreshWorkOutcome::Stopped => break,
                            RefreshWorkOutcome::Requested => refresh_faults.recovered("refresh_request"),
                            RefreshWorkOutcome::RequestFailed => refresh_faults.failure("refresh_request", Fault::RefreshRequest),
                        }
                        let snapshot = interface_state.get();
                        if !Self::resample_or_stop(&state, &snapshot, &mut stop_receiver,
                            #[cfg(target_os = "windows")] &windows_reachability_sampler,
                            #[cfg(target_os = "windows")] &mut reachability_faults,
                        ).await? {
                            break;
                        }
                    }
                }
            }

            Ok::<(), NetError>(())
        };
        #[cfg(target_os = "windows")]
        {
            // Both futures belong to this monitor generation. Stop/drop of the
            // main loop drops the name future and its Cancellation guard; native
            // work has no publisher and cannot commit a late result.
            tokio::select! {
                biased;
                result = observations => result?,
                result = Self::monitor_windows_names(&state, &windows_sampler) => result?,
            }
        }
        #[cfg(not(target_os = "windows"))]
        observations.await?;

        // On macOS the native source waits for cancellation completion and
        // drains the serial callback queue before releasing the
        // callback sender, preventing a late native hint from reaching state
        // reset or a later client generation.
        #[cfg(target_os = "macos")]
        drop(platform_monitor);

        Ok(())
    }

    // 创建真实检测器并保留底层诊断;测试可替换构造 Future,以安全方式注入错误与时序。
    async fn create_monitor(
        #[cfg(test)] factory: Option<initialization_tests::MonitorFactory>,
    ) -> Result<netwatch::netmon::Monitor, NetError> {
        #[cfg(test)]
        if let Some(factory) = factory {
            return factory().await;
        }
        netwatch::netmon::Monitor::new().await.map_err(|error| {
            crate::log_e!(LogType::Engine; "net_status.create_monitor", "reason", "monitor_creation_failed");
            NetError::with_source(crate::error::ErrorKind::RuntimeUnavailable, error)
                .with_stage(crate::error::ErrorStage::NetworkMonitor)
        })
    }

    // Background reachability and explicit reachability queries share a bounded
    // lane; name queries use another lane and a separate commit watermark.
    // Native work never owns the commit capability and cannot publish after stop.
    async fn observe_or_stop(
        state: &Arc<Mutex<MonitorState>>,
        snapshot: &netwatch::netmon::State,
        stop: &mut oneshot::Receiver<()>,
        #[cfg(target_os = "windows")] sampler: &super::refresh::WindowsSampler,
        #[cfg(target_os = "windows")] faults: &mut FaultCycle,
    ) -> Result<bool, NetError> {
        Self::observe_with_policy(
            state,
            snapshot,
            stop,
            false,
            #[cfg(target_os = "windows")]
            sampler,
            #[cfg(target_os = "windows")]
            faults,
        )
        .await
    }

    // An initialized monitor can retry a saturated or slow sampling worker.
    // Initial observation still has to succeed before start reports Running.
    async fn resample_or_stop(
        state: &Arc<Mutex<MonitorState>>,
        snapshot: &netwatch::netmon::State,
        stop: &mut oneshot::Receiver<()>,
        #[cfg(target_os = "windows")] sampler: &super::refresh::WindowsSampler,
        #[cfg(target_os = "windows")] faults: &mut FaultCycle,
    ) -> Result<bool, NetError> {
        Self::observe_with_policy(
            state,
            snapshot,
            stop,
            true,
            #[cfg(target_os = "windows")]
            sampler,
            #[cfg(target_os = "windows")]
            faults,
        )
        .await
    }

    async fn observe_with_policy(
        state: &Arc<Mutex<MonitorState>>,
        snapshot: &netwatch::netmon::State,
        stop: &mut oneshot::Receiver<()>,
        _retry_transient: bool,
        #[cfg(target_os = "windows")] sampler: &super::refresh::WindowsSampler,
        #[cfg(target_os = "windows")] faults: &mut FaultCycle,
    ) -> Result<bool, NetError> {
        #[cfg(not(target_os = "windows"))]
        {
            let Some(reachability) = Self::reachability_or_stop(snapshot, stop).await? else {
                return Ok(false);
            };
            Self::update_state_inner(state, reachability, Self::ip_stack_from_state(snapshot))?;
        }
        #[cfg(target_os = "windows")]
        {
            let cancel = super::refresh::Cancellation::new();
            let deadline = std::time::Instant::now() + Duration::from_secs(10);
            let sampled = tokio::select! {
                biased;
                _ = &mut *stop => return Ok(false),
                result = async {
                    tokio::time::timeout_at(
                        tokio::time::Instant::from_std(deadline),
                        sampler.sample_background(deadline, cancel.flag.clone()),
                    ).await.map_err(|_| NetError::from(crate::error::ErrorKind::TimedOut))?
                } => result,
            };
            let failure = sampled.as_ref().err().map(Fault::from_error);
            let sampled = Self::classify_windows_sample(sampled, _retry_transient)?;
            let Some(sampled) = sampled else {
                if let Some(failure) = failure {
                    faults.failure("reachability_sample", failure);
                }
                // No observation was collected or committed. The existing
                // Running snapshot and its timestamp remain unchanged.
                return Ok(true);
            };
            let mut commit_fault = None;
            let (keep_running, publication) = Self::prepare_windows_sample(
                state,
                &cancel,
                deadline,
                _retry_transient,
                sampled,
                Self::ip_stack_from_state(snapshot),
                &mut commit_fault,
            )?;
            if !keep_running {
                return Ok(false);
            }
            if let Some(failure) = commit_fault {
                faults.failure("reachability_sample", failure);
            }
            if let Some(publication) = publication {
                publication.dispatch()?;
                if commit_fault.is_none() {
                    faults.recovered("reachability_sample");
                }
            }
        }
        Ok(true)
    }

    #[cfg(test)]
    async fn complete_windows_sample<T>(
        sample: impl std::future::Future<Output = Result<T, NetError>>,
        retry_transient: bool,
    ) -> Result<Option<T>, NetError> {
        Self::classify_windows_sample(sample.await, retry_transient)
    }

    #[cfg(any(target_os = "windows", test))]
    fn prepare_windows_sample(
        state: &Arc<Mutex<MonitorState>>,
        cancel: &super::refresh::Cancellation,
        deadline: std::time::Instant,
        retry_transient: bool,
        sampled: super::refresh::CompletedSample,
        ip_stack: IpStack,
        fault: &mut Option<Fault>,
    ) -> Result<(bool, Option<NetworkPublication>), NetError> {
        let monitor = state.lock().map_err(NetError::from_poison)?;
        if !monitor.active.load(Ordering::Acquire) {
            return Ok((false, None));
        }
        // Waiting for the monitor lock is part of the sample's deadline. An
        // established monitor retries an expired sample without committing it.
        let validity = cancel.check(deadline);
        let failure = validity.as_ref().err().map(Fault::from_error);
        if Self::classify_windows_sample(validity, retry_transient)?.is_none() {
            *fault = failure;
            return Ok((true, None));
        }
        let publication = match &monitor.observation {
            Some(publisher) => publisher.prepare_sampled_observation(
                sampled.id,
                sampled.observation.reachability,
                Some(ip_stack),
                if matches!(
                    sampled.observation.name_source,
                    crate::net_status::NetworkNameSource::CachedObservation
                ) {
                    super::network_status_snapshot::NetworkNameUpdate::Preserve
                } else {
                    sampled.observation.network_name.into()
                },
                sampled.sampled_at,
                || {
                    let validity = cancel.check(deadline);
                    let failure = validity.as_ref().err().map(Fault::from_error);
                    let valid = Self::classify_windows_sample(validity, retry_transient)?.is_some();
                    if !valid {
                        *fault = failure;
                    }
                    Ok(valid)
                },
            )?,
            None => None,
        };
        Ok((true, publication))
    }

    #[cfg(any(target_os = "windows", test))]
    async fn monitor_windows_names(
        state: &Arc<Mutex<MonitorState>>,
        sampler: &super::refresh::WindowsSampler,
    ) -> Result<(), NetError> {
        let mut interval = time::interval(Duration::from_secs(2));
        interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
        let mut faults = FaultCycle::default();
        let mut fallback_faults = FaultCycle::default();
        loop {
            interval.tick().await;
            if !state
                .lock()
                .map_err(NetError::from_poison)?
                .active
                .load(Ordering::Acquire)
            {
                return Ok(());
            }
            let cancel = super::refresh::Cancellation::new();
            let deadline = std::time::Instant::now() + Duration::from_secs(10);
            let result = time::timeout_at(
                time::Instant::from_std(deadline),
                sampler.sample_background(deadline, cancel.flag.clone()),
            )
            .await;
            let sampled = match result {
                Ok(Ok(sampled)) => sampled,
                Ok(Err(error)) => {
                    // A name-query fault does not invalidate successful Internet
                    // reachability; retain the last name and retry next period.
                    faults.failure("name_sample", Fault::from_error(&error));
                    continue;
                }
                Err(_) => {
                    faults.failure("name_sample", Fault::Timeout);
                    continue;
                }
            };
            if sampled.observation.name_diagnostics.is_empty() {
                fallback_faults.recovered("name_fallback");
            } else {
                fallback_faults.failure("name_fallback", Fault::NameFallback);
            }
            let mut commit_fault = None;
            let publication = {
                let monitor = state.lock().map_err(NetError::from_poison)?;
                if !monitor.active.load(Ordering::Acquire) {
                    return Ok(());
                }
                match &monitor.observation {
                    Some(publisher) => publisher.prepare_sampled_name_observation(
                        sampled.id,
                        sampled.observation.network_name,
                        sampled.sampled_at,
                        || match cancel.check(deadline) {
                            Ok(()) => Ok(true),
                            Err(error)
                                if matches!(
                                    error.kind(),
                                    crate::error::ErrorKind::TimedOut
                                        | crate::error::ErrorKind::Cancelled
                                ) =>
                            {
                                commit_fault = Some(Fault::from_error(&error));
                                Ok(false)
                            }
                            Err(error) => Err(error),
                        },
                    )?,
                    None => None,
                }
            };
            if let Some(failure) = commit_fault {
                faults.failure("name_sample", failure);
            }
            if let Some(publication) = publication {
                publication.dispatch()?;
                if commit_fault.is_none() {
                    faults.recovered("name_sample");
                }
            }
        }
    }

    #[cfg(any(target_os = "windows", test))]
    fn classify_windows_sample<T>(
        sample: Result<T, NetError>,
        retry_transient: bool,
    ) -> Result<Option<T>, NetError> {
        match sample {
            Err(error)
                if retry_transient
                    && matches!(
                        error.kind(),
                        crate::error::ErrorKind::QueueFull
                            | crate::error::ErrorKind::TimedOut
                            | crate::error::ErrorKind::ResourceExhausted
                    ) =>
            {
                Ok(None)
            }
            result => result.map(Some),
        }
    }
}

impl Drop for InnerNetStatusClient {
    // 客户端析构时发出永久停止请求;Drop 不执行异步等待,资源回收由监控任务自行完成。
    fn drop(&mut self) {
        self.request_destroy();
    }
}

#[cfg(test)]
#[path = "lifecycle_tests.rs"]
mod tests;

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

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