secra_plugins 0.1.32

生产级插件系统 - 插件的生命周期
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
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
//! 插件管理器主模块

// 声明子模块
#[path = "manager/constants.rs"]
mod constants;
#[path = "manager/executor.rs"]
mod executor;
#[path = "manager/lifecycle_ops.rs"]
mod lifecycle_ops;
#[path = "manager/loader.rs"]
mod loader;
#[path = "manager/manager_config.rs"]
mod manager_config;
#[path = "manager/query.rs"]
mod query;
#[path = "manager/reloader.rs"]
mod reloader;
#[path = "manager/routes.rs"]
mod routes;
#[path = "manager/types.rs"]
mod types;
#[path = "manager/unloader.rs"]
mod unloader;
#[path = "manager/validation.rs"]
mod validation;

// 功能操作模块
#[path = "manager/execute_ops.rs"]
mod execute_ops;
#[path = "manager/init_ops.rs"]
mod init_ops;
#[path = "manager/load_ops.rs"]
mod load_ops;
#[path = "manager/query_ops.rs"]
mod query_ops;
#[path = "manager/reload_ops.rs"]
mod reload_ops;
#[path = "manager/route_ops.rs"]
mod route_ops;
#[path = "manager/start_ops.rs"]
mod start_ops;
#[path = "manager/stop_ops.rs"]
mod stop_ops;
#[path = "manager/unload_ops.rs"]
mod unload_ops;
#[path = "manager/watch_ops.rs"]
mod watch_ops;

// 重新导出子模块的内容
pub use manager_config::{PluginManagerConfig, PluginManagerConfigBuilder};
pub use types::{CreatePluginFn, PluginInfo, PluginInstance, PluginMap};
pub use crate::factory::PluginFactory;

// 导入必要的依赖
use crate::error::{PluginManagerError, PluginManagerResult};
use crate::status::PluginStatus;
use actix_web::web;
use loader::load_plugin;
use notify::{Event, RecommendedWatcher, RecursiveMode, Watcher};
use query::find_plugin_file_by_id;
use reload_ops::{call_reload_hook, get_reload_info};
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::mpsc::channel;
use std::time::Duration;
use tokio::sync::{RwLock, mpsc};
use tracing::{debug, error, info, trace, warn};
use tracing_shared::SharedLogger;
use unload_ops::{get_unload_info, get_unload_order, perform_unload, remove_child_from_parent};
use validation::sanitize_plugin_name;


/// 插件管理器
pub struct PluginManager {
    /// 插件实例映射
    plugins: PluginMap,
    /// 插件目录路径
    pub plugin_dir: String,
    /// Ed25519 公钥路径(用于验证插件数字签名)
    ed25519_public_key_path: Option<String>,
    /// RSA 私钥路径(用于解密 AES 密钥)
    rsa_private_key_path: Option<String>,
    /// 插件动态库临时目录
    temp_dir: String,
    /// 动态库路径(用于获取插件包下的动态库路径)
    library_path: Option<String>,
    /// 插件操作超时时间(秒)
    timeout_secs: u64,
    /// 目录监听停止信号发送器(可选)
    watch_stop_tx: Option<mpsc::Sender<()>>,
    /// 文件系统监听事件接收器(可选)
    pub watch_rx: Option<Arc<std::sync::Mutex<std::sync::mpsc::Receiver<Result<Event, notify::Error>>>>>,
    /// 文件系统监听器(可选,需要保持 alive 以维持 channel)
    _watch_watcher: Option<Arc<std::sync::Mutex<RecommendedWatcher>>>,
}

impl PluginManager {
    /// 创建新的插件管理器
    ///
    /// 创建插件管理器实例,并确保临时目录存在。
    /// 如果临时目录不存在,会自动创建。
    ///
    /// # 参数
    /// * `config` - 插件管理器配置
    ///
    /// # 返回值
    /// * `PluginManagerResult<Self>` - 成功时返回插件管理器实例
    ///
    /// # 错误
    /// * `PluginManagerError::Io` - 如果创建临时目录失败
    pub async fn new(config: PluginManagerConfig) -> PluginManagerResult<Self> {
        let plugins: PluginMap = Arc::new(RwLock::new(HashMap::new()));
        let temp_dir = config.temp_dir.clone();

        // 确保临时目录存在
        let temp_dir_path = std::path::Path::new(&temp_dir);
        if !temp_dir_path.exists() {
            tracing::info!("创建临时目录: {}", temp_dir);
            tokio::fs::create_dir_all(temp_dir_path)
                .await
                .map_err(|e| {
                    tracing::error!("创建临时目录失败: {} - {}", temp_dir, e);
                    PluginManagerError::Io(e)
                })?;
        }

        let (watch_rx, watch_watcher) = if config.enable_plugin_dir_watch {
            // 1. 创建 channel
            let (tx, rx) = channel();

            // 2. 创建 watcher
            let mut watcher = RecommendedWatcher::new(
                tx,
                notify::Config::default().with_poll_interval(Duration::from_secs(2)), // 轮询间隔(部分平台)
            )
            .map_err(|e| {
                std::io::Error::new(
                    std::io::ErrorKind::Other,
                    format!("创建文件系统监听器失败: {}", e),
                )
            })?;

            // 3. 监听路径
            watcher
                .watch(
                    std::path::Path::new(&config.plugin_dir),
                    RecursiveMode::Recursive,
                )
                .map_err(|e| {
                    std::io::Error::new(
                        std::io::ErrorKind::Other,
                        format!("开始监听目录失败: {}", e),
                    )
                })?;

            // 保存 watcher 以避免被 drop(watcher 被 drop 会导致 channel 关闭)
            let watch_watcher = Arc::new(std::sync::Mutex::new(watcher));
            (
                Some(Arc::new(std::sync::Mutex::new(rx))),
                Some(watch_watcher),
            )
        } else {
            (None, None)
        };

        Ok(Self {
            plugins,
            plugin_dir: config.plugin_dir,
            ed25519_public_key_path: config.ed25519_public_key_path,
            rsa_private_key_path: config.rsa_private_key_path,
            temp_dir: config.temp_dir,
            library_path: config.library_path,
            timeout_secs: config.timeout_secs,
            watch_stop_tx: None,
            watch_rx,
            _watch_watcher: watch_watcher,
        })
    }

    /// 加载所有插件
    ///
    /// 从配置的插件目录中扫描并加载所有插件文件(.spk 格式)。
    /// 加载过程包括签名验证、解包、动态库加载和实例创建。
    /// 子插件会在父插件加载完成后自动挂载到对应的父插件上。
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 行为
    /// * 清空并重新创建临时目录
    /// * 扫描插件目录,查找所有 `.spk` 文件
    /// * 逐个加载插件,主插件直接插入,子插件暂存
    /// * 所有主插件加载完成后,将子插件挂载到对应的父插件
    /// * 如果某个插件加载失败,会记录错误但继续加载其他插件
    ///
    /// # 错误
    /// * 如果插件目录不存在,会记录警告但不会返回错误
    /// * 如果某个插件加载失败,会记录错误但继续处理其他插件
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// manager.load_all_plugins().await?;
    /// # }
    /// ```
    pub async fn load_all_plugins(&self) -> PluginManagerResult<()> {
        load_ops::load_all_plugins(
            self.plugins.clone(),
            &self.plugin_dir,
            &self.temp_dir,
            self.ed25519_public_key_path.clone(),
            self.rsa_private_key_path.clone(),
            self.library_path.as_ref(),
        )
        .await
    }

    /// 将插件实例写入管理器
    ///
    /// 将已创建的插件实例插入到插件管理器的映射表中。
    /// 此方法用于主插件的插入,会记录详细的加载日志。
    ///
    /// # 参数
    /// * `plugin_instance` - 要插入的插件实例
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 行为
    /// * 使用插件的ID作为键插入到映射表
    /// * 记录包含插件ID、名称、版本和指纹的详细日志
    /// * 使用 tracing span 注入上下文信息,便于日志追踪
    ///
    /// # 注意
    /// 此方法只用于主插件。子插件应使用 `insert_child_plugin` 方法。
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// // ... 创建 plugin_instance ...
    /// manager.insert_plugin_instance(plugin_instance).await?;
    /// # }
    /// ```
    pub async fn insert_plugin_instance(
        &self,
        plugin_instance: PluginInstance,
    ) -> PluginManagerResult<()> {
        load_ops::insert_plugin_instance(self.plugins.clone(), plugin_instance).await
    }

    /// 将子插件挂载到对应父插件
    ///
    /// 将子插件实例插入到插件管理器,并同时将其信息添加到父插件的 `child_plugins` 列表中。
    /// 这确保了父子插件关系的正确建立。
    ///
    /// # 参数
    /// * `plugin_instance` - 要插入的子插件实例
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 错误
    /// * `PluginManagerError::Other` - 如果子插件未配置父插件ID
    /// * `PluginManagerError::NotFound` - 如果父插件不存在
    ///
    /// # 行为
    /// * 检查子插件是否配置了父插件ID
    /// * 验证父插件是否存在
    /// * 将子插件信息添加到父插件的 `child_plugins` 列表
    /// * 将子插件实例插入到映射表
    /// * 记录详细的挂载日志
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// // ... 创建子插件实例 ...
    /// manager.insert_child_plugin(child_instance).await?;
    /// # }
    /// ```
    pub async fn insert_child_plugin(
        &self,
        plugin_instance: PluginInstance,
    ) -> PluginManagerResult<()> {
        load_ops::insert_child_plugin(self.plugins.clone(), plugin_instance).await
    }

    /// 初始化所有插件
    ///
    /// 批量初始化所有处于 `Loaded` 状态的插件。
    /// 初始化顺序会优先处理主插件,然后处理子插件,确保依赖关系的正确初始化。
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 行为
    /// * 只初始化状态为 `Loaded` 的插件
    /// * 按照主插件优先、子插件其次的顺序初始化
    /// * 如果某个插件初始化失败,会将其状态设置为 `Error`,但继续初始化其他插件
    /// * 初始化超时也会将插件状态设置为 `Error`
    ///
    /// # 状态转换
    /// * `Loaded` -> `Initialized`: 初始化成功
    /// * `Loaded` -> `Error`: 初始化失败或超时
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// manager.initialize_all_plugins().await?;
    /// # }
    /// ```
    pub async fn initialize_all_plugins(&self) -> PluginManagerResult<()> {
        init_ops::initialize_all_plugins(self.plugins.clone(), self.timeout_secs).await
    }

    /// 初始化单个插件(公开方法)
    ///
    /// 初始化指定的插件。插件必须处于 `Loaded` 状态才能初始化。
    /// 初始化过程会调用插件的 `initialize()` 方法,并设置默认配置。
    ///
    /// # 参数
    /// * `plugin_id` - 要初始化的插件ID
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 错误
    /// * `PluginManagerError::NotFound` - 如果指定的插件不存在
    /// * `PluginManagerError::StateError` - 如果插件状态不正确或状态转换无效
    /// * `PluginManagerError::ExecutionError` - 如果初始化失败或超时
    ///
    /// # 状态转换
    /// * `Loaded` -> `Initialized`: 初始化成功
    /// * `Loaded` -> `Error`: 初始化失败或超时
    ///
    /// # 配置
    /// 初始化时会使用默认配置,并设置 `enabled = true`。
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// manager.initialize_plugin("my-plugin").await?;
    /// # }
    /// ```
    pub async fn initialize_plugin(&self, plugin_id: &str) -> PluginManagerResult<()> {
        init_ops::initialize_plugin(self.plugins.clone(), plugin_id, self.timeout_secs).await
    }

    /// 启动所有插件
    ///
    /// 批量启动所有处于 `Initialized` 状态的插件。
    /// 启动顺序会优先处理主插件,然后处理子插件,确保依赖关系的正确启动。
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 行为
    /// * 只启动状态为 `Initialized` 的插件
    /// * 按照主插件优先、子插件其次的顺序启动
    /// * 如果某个插件启动失败,会将其状态设置为 `Error`,但继续启动其他插件
    /// * 启动超时也会将插件状态设置为 `Error`
    ///
    /// # 状态转换
    /// * `Initialized` -> `Running`: 启动成功
    /// * `Initialized` -> `Error`: 启动失败或超时
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// manager.start_all_plugins().await?;
    /// # }
    /// ```
    pub async fn start_all_plugins(&self) -> PluginManagerResult<()> {
        start_ops::start_all_plugins(self.plugins.clone(), self.timeout_secs).await
    }

    /// 启动单个插件(公开方法)
    ///
    /// 启动指定的插件。插件必须处于 `Initialized` 状态才能启动。
    /// 启动过程会调用插件的 `start()` 方法。
    ///
    /// # 参数
    /// * `plugin_id` - 要启动的插件ID
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 错误
    /// * `PluginManagerError::NotFound` - 如果指定的插件不存在
    /// * `PluginManagerError::StateError` - 如果插件状态不正确或状态转换无效
    /// * `PluginManagerError::ExecutionError` - 如果启动失败或超时
    ///
    /// # 状态转换
    /// * `Initialized` -> `Running`: 启动成功
    /// * `Initialized` -> `Error`: 启动失败或超时
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// manager.start_plugin("my-plugin").await?;
    /// # }
    /// ```
    pub async fn start_plugin(&self, plugin_id: &str) -> PluginManagerResult<()> {
        start_ops::start_plugin(self.plugins.clone(), plugin_id, self.timeout_secs).await
    }

    /// 停止所有插件
    ///
    /// 批量停止所有处于 `Running` 状态的插件。
    /// 停止顺序会优先处理子插件,然后处理主插件,确保依赖关系的正确停止。
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 行为
    /// * 只停止状态为 `Running` 的插件
    /// * 按照子插件优先、主插件其次的顺序停止
    /// * 如果某个插件停止失败,会将其状态设置为 `Error`,但继续停止其他插件
    /// * 停止超时也会将插件状态设置为 `Error`
    ///
    /// # 状态转换
    /// * `Running` -> `Stopped`: 停止成功
    /// * `Running` -> `Error`: 停止失败或超时
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// manager.stop_all_plugins().await?;
    /// # }
    /// ```
    pub async fn stop_all_plugins(&self) -> PluginManagerResult<()> {
        stop_ops::stop_all_plugins(self.plugins.clone(), self.timeout_secs).await
    }

    /// 停止单个插件(公开方法)
    ///
    /// 停止指定的插件。插件必须处于 `Running` 状态才能停止。
    /// 停止过程会调用插件的 `stop()` 方法。
    ///
    /// # 参数
    /// * `plugin_id` - 要停止的插件ID
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 错误
    /// * `PluginManagerError::NotFound` - 如果指定的插件不存在
    /// * `PluginManagerError::StopFailed` - 如果停止失败(插件状态变为 `Error`)
    ///
    /// # 状态转换
    /// * `Running` -> `Stopped`: 停止成功
    /// * `Running` -> `Error`: 停止失败或超时
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// manager.stop_plugin("my-plugin").await?;
    /// # }
    /// ```
    pub async fn stop_plugin(&self, plugin_id: &str) -> PluginManagerResult<()> {
        stop_ops::stop_plugin(self.plugins.clone(), plugin_id, self.timeout_secs).await
    }

    /// 卸载单个插件
    ///
    /// 从插件管理器中卸载指定的插件。卸载过程包括:
    /// 1. 停止插件(如果正在运行)
    /// 2. 检查依赖关系
    /// 3. 递归卸载所有子插件
    /// 4. 从父插件中移除子插件信息(如果是子插件)
    /// 5. 移除插件实例并清理临时文件
    ///
    /// # 参数
    /// * `plugin_id` - 要卸载的插件ID
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 错误
    /// * `PluginManagerError::ValidationFailed` - 如果插件ID为空
    /// * `PluginManagerError::NotFound` - 如果插件不存在
    /// * `PluginManagerError::DependencyError` - 如果有其他插件依赖此插件
    /// * `PluginManagerError::UninstallFailed` - 如果停止插件失败
    ///
    /// # 行为
    /// * 如果插件正在运行,会先停止插件
    /// * 检查是否有其他插件依赖此插件,如果有则拒绝卸载
    /// * 递归卸载所有子插件
    /// * 如果是子插件,从父插件中移除子插件信息
    /// * 移除插件实例并清理临时文件
    ///
    /// # 注意
    /// 卸载会永久删除插件的临时文件,请确保在调用前已保存必要数据。
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// manager.unload_plugin("my-plugin".to_string()).await?;
    /// # }
    /// ```
    pub async fn unload_plugin(&self, plugin_id: String) -> PluginManagerResult<()> {
        if plugin_id.is_empty() {
            return Err(PluginManagerError::ValidationFailed(
                "插件ID不能为空".to_string(),
            ));
        }

        info!("开始卸载插件: {}", plugin_id);

        // 第一步:检查插件状态并停止(如果需要)
        {
            let plugins = self.plugins.read().await;
            let plugin_instance = plugins.get(&plugin_id).ok_or_else(|| {
                error!("插件不存在: {}", plugin_id);
                PluginManagerError::not_found(plugin_id.clone())
            })?;

            if plugin_instance.status == PluginStatus::Running {
                drop(plugins);
                warn!("插件 {} 正在运行,先停止插件", plugin_id);

                if let Err(e) = self.stop_plugin(&plugin_id).await {
                    error!("停止插件失败 {}: {}", plugin_id, e);
                    return Err(PluginManagerError::UninstallFailed(format!(
                        "停止插件失败: {}",
                        e
                    )));
                }
            } else if plugin_instance.status == PluginStatus::Initialized {
                info!("插件 {} 已初始化但未启动,可以直接卸载", plugin_id);
            }
        }

        // 第二步:检查依赖关系和获取子插件列表
        let (child_plugin_ids, is_sub_plugin, parent_id) = {
            let plugins = self.plugins.read().await;
            get_unload_info(&plugins, &plugin_id)?
        };

        // 递归卸载所有子插件
        let mut child_unload_errors = Vec::new();
        for child_id in child_plugin_ids {
            match Box::pin(self.unload_plugin(child_id.clone())).await {
                Ok(_) => {
                    info!("子插件 {} 卸载成功", child_id);
                }
                Err(e) => {
                    error!("卸载子插件失败 {}: {}", child_id, e);
                    child_unload_errors.push((child_id, e));
                }
            }
        }

        // 如果当前插件是子插件,从父插件中移除子插件信息
        if is_sub_plugin {
            if let Some(ref parent_id) = parent_id {
                remove_child_from_parent(self.plugins.clone(), &plugin_id, parent_id).await;
            } else {
                warn!("子插件 {} 没有父插件ID,无法清理父插件列表", plugin_id);
            }
        }

        if !child_unload_errors.is_empty() {
            warn!(
                "卸载父插件 {} 时,有 {} 个子插件卸载失败,但将继续卸载父插件",
                plugin_id,
                child_unload_errors.len()
            );
        }

        // 执行实际的卸载操作
        perform_unload(self.plugins.clone(), &plugin_id).await?;

        Ok(())
    }

    /// 卸载所有插件
    ///
    /// 卸载插件管理器中所有已加载的插件。
    /// 卸载顺序会优先处理子插件,然后处理主插件,确保依赖关系的正确卸载。
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 行为
    /// * 获取所有插件的ID列表
    /// * 计算卸载顺序(子插件在前,父插件在后)
    /// * 按顺序逐个卸载插件
    /// * 如果某个插件卸载失败,会记录错误但继续卸载其他插件
    ///
    /// # 注意
    /// 卸载会永久删除所有插件的临时文件,请确保在调用前已保存必要数据。
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// manager.unload_all_plugins().await?;
    /// # }
    /// ```
    pub async fn unload_all_plugins(&self) -> PluginManagerResult<()> {
        info!("开始卸载所有插件...");

        let plugin_ids: Vec<String> = {
            let plugins = self.plugins.read().await;
            plugins.keys().cloned().collect()
        };

        if plugin_ids.is_empty() {
            info!("没有需要卸载的插件");
            return Ok(());
        }

        info!("发现 {} 个插件需要卸载", plugin_ids.len());

        let unload_order = {
            let plugins = self.plugins.read().await;
            get_unload_order(&plugins)
        };

        for plugin_id in unload_order {
            if let Err(e) = self.unload_plugin(plugin_id.clone()).await {
                error!("卸载插件失败 {}: {}", plugin_id, e);
            }
        }

        info!("所有插件卸载完成");
        Ok(())
    }

    /// 重新加载插件目录
    ///
    /// 卸载所有当前已加载的插件,然后重新扫描插件目录并加载所有插件。
    /// 这是一个便捷方法,用于刷新整个插件目录的状态。
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 行为
    /// 1. 卸载所有当前已加载的插件(如果存在)
    /// 2. 重新扫描插件目录,查找所有 `.spk` 文件
    /// 3. 加载所有找到的插件
    /// 4. 子插件会自动挂载到对应的父插件
    ///
    /// # 错误
    /// * `PluginManagerError::Io` - 如果插件目录操作失败
    /// * `PluginManagerError::LoadFailed` - 如果加载插件时发生错误
    /// * 卸载过程中的错误会被记录但不会中断流程
    ///
    /// # 注意
    /// * 此方法会卸载所有插件,包括正在运行的插件
    /// * 重新加载后,插件状态为 `Loaded`,需要手动调用 `initialize_all_plugins()` 和 `start_all_plugins()` 来初始化和启动
    /// * 如果某个插件加载失败,会记录错误但继续加载其他插件
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// // 重新加载插件目录
    /// manager.reload_plugin_directory().await?;
    /// // 初始化和启动所有插件
    /// manager.initialize_all_plugins().await?;
    /// manager.start_all_plugins().await?;
    /// # }
    /// ```
    pub async fn reload_plugin_directory(&self) -> PluginManagerResult<()> {
        info!("开始重新加载插件目录: {}", self.plugin_dir);

        // 第一步:卸载所有当前已加载的插件
        if let Err(e) = self.unload_all_plugins().await {
            warn!("卸载所有插件时发生错误(将继续重新加载): {}", e);
            // 继续执行,即使卸载失败也要尝试重新加载
        }

        // 第二步:重新加载所有插件
        self.load_all_plugins().await?;

        info!("插件目录重新加载完成: {}", self.plugin_dir);
        Ok(())
    }

    /// 执行插件功能
    ///
    /// 调用指定插件的 `execute` 方法来执行特定的功能操作。
    /// 插件必须处于运行状态才能执行。
    ///
    /// # 参数
    /// * `plugin_id` - 要执行功能的插件ID
    /// * `action` - 要执行的动作名称,会被验证长度和格式
    /// * `params` - 传递给插件执行的参数,使用 JSON 格式
    ///
    /// # 返回值
    /// * `PluginManagerResult<serde_json::Value>` - 成功时返回插件执行的结果(JSON 格式)
    ///
    /// # 错误
    /// * `PluginManagerError::NotFound` - 如果指定的插件不存在
    /// * `PluginManagerError::StateError` - 如果插件未处于运行状态
    /// * `PluginManagerError::ValidationFailed` - 如果动作名称验证失败
    /// * `PluginManagerError::ExecutionError` - 如果插件执行失败或超时
    ///
    /// # 执行流程
    /// 1. 验证并清理插件ID
    /// 2. 验证动作名称参数
    /// 3. 检查插件是否存在且处于运行状态
    /// 4. 调用插件的 `execute` 方法(带超时保护)
    /// 5. 返回执行结果或错误信息
    ///
    /// # 示例
    /// ```no_run
    /// use serde_json::json;
    ///
    /// # async fn example() {
    /// let params = json!({"key": "value"});
    /// let result = manager.execute_plugin("my-plugin", "my_action", params).await?;
    /// println!("执行结果: {}", result);
    /// # }
    /// ```
    pub async fn execute_plugin(
        &self,
        plugin_id: &str,
        action: &str,
        params: serde_json::Value,
    ) -> PluginManagerResult<serde_json::Value> {
        execute_ops::execute_plugin(
            self.plugins.clone(),
            plugin_id,
            action,
            params,
            self.timeout_secs,
        )
        .await
    }

    /// 注册所有插件的路由
    ///
    /// 为所有处于运行状态且配置了路由的插件注册 HTTP 路由。
    /// 注册顺序会优先处理主插件,然后处理子插件,确保路由注册的正确顺序。
    ///
    /// # 参数
    /// * `cfg` - Actix Web 的服务配置对象,用于注册路由
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 行为
    /// * 只注册状态为 `Running` 且配置了路由的插件
    /// * 按照主插件优先、子插件其次的顺序注册
    /// * 如果某个插件路由注册失败,会记录错误但继续注册其他插件
    /// * 注册完成后会输出统计信息(成功数、失败数、总数)
    ///
    /// # 错误
    /// * 通常不会返回错误,即使部分插件注册失败也会继续执行
    ///
    /// # 示例
    /// ```no_run
    /// use actix_web::web;
    ///
    /// # async fn example() {
    /// let mut cfg = web::ServiceConfig::default();
    /// manager.register_all_plugin_routes(&mut cfg).await?;
    /// # }
    /// ```
    pub async fn register_all_plugin_routes(
        &self,
        cfg: &mut web::ServiceConfig,
    ) -> PluginManagerResult<()> {
        route_ops::register_all_plugin_routes(self.plugins.clone(), cfg).await
    }

    /// 注册所有插件的路由(同步版本)
    ///
    /// 这是 `register_all_plugin_routes` 的同步版本,可以在非异步上下文中调用。
    /// 内部会尝试使用当前的 Tokio 运行时句柄,如果不存在则创建新的运行时。
    ///
    /// # 参数
    /// * `cfg` - Actix Web 的服务配置对象,用于注册路由
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 示例
    /// ```no_run
    /// use actix_web::web;
    ///
    /// let mut cfg = web::ServiceConfig::default();
    /// manager.register_all_plugin_routes_sync(&mut cfg)?;
    /// ```
    pub fn register_all_plugin_routes_sync(
        &self,
        cfg: &mut web::ServiceConfig,
    ) -> PluginManagerResult<()> {
        route_ops::register_all_plugin_routes_sync(self.plugins.clone(), cfg)
    }

    /// 查询所有插件信息
    ///
    /// 获取插件管理器中所有已加载插件的详细信息,包括元数据、状态、指纹和子插件列表。
    /// 返回的信息是只读的,不包含插件实例的内部实现细节。
    ///
    /// # 返回值
    /// * `PluginManagerResult<Vec<PluginInfo>>` - 成功时返回所有插件的 `PluginInfo` 列表
    ///
    /// # 错误
    /// * 通常不会返回错误,除非发生内部系统错误
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// let plugin_infos = manager.get_all_plugins().await?;
    /// for info in plugin_infos {
    ///     println!("插件: {}, 状态: {:?}", info.metadata.name, info.status);
    /// }
    /// # }
    /// ```
    pub async fn get_all_plugins(&self) -> PluginManagerResult<Vec<PluginInfo>> {
        query_ops::get_all_plugins(self.plugins.clone()).await
    }

    /// 查询单个插件信息
    ///
    /// 根据插件ID获取指定插件的详细信息,包括元数据、状态、指纹和子插件列表。
    /// 插件ID会被自动清理和验证,防止注入攻击。
    ///
    /// # 参数
    /// * `plugin_id` - 要查询的插件ID
    ///
    /// # 返回值
    /// * `PluginManagerResult<PluginInfo>` - 成功时返回插件的 `PluginInfo`
    ///
    /// # 错误
    /// * `PluginManagerError::NotFound` - 如果指定的插件不存在
    /// * `PluginManagerError::ValidationFailed` - 如果插件ID验证失败
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// let plugin_info = manager.get_plugin("my-plugin").await?;
    /// println!("插件名称: {}", plugin_info.metadata.name);
    /// println!("插件状态: {:?}", plugin_info.status);
    /// # }
    /// ```
    pub async fn get_plugin(&self, plugin_id: &str) -> PluginManagerResult<PluginInfo> {
        query_ops::get_plugin(self.plugins.clone(), plugin_id).await
    }

    /// 设置插件状态(内部方法)
    ///
    /// 内部使用的状态设置方法,用于直接修改插件的状态。
    /// 此方法会验证状态转换的有效性,并记录状态变更日志。
    ///
    /// # 参数
    /// * `plugin_id` - 要设置状态的插件ID
    /// * `new_status` - 新的插件状态
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 错误
    /// * `PluginManagerError::NotFound` - 如果指定的插件不存在
    /// * `PluginManagerError::StateError` - 如果状态转换无效
    ///
    /// # 行为
    /// * 验证插件是否存在
    /// * 验证状态转换是否有效
    /// * 更新插件状态
    /// * 记录状态变更日志
    ///
    /// # 注意
    /// 此方法为内部方法(`pub(crate)`),仅供插件管理器内部使用。
    /// 外部代码应使用公开的状态管理方法(如 `disable_plugin`)。
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// manager.set_plugin_status("my-plugin", PluginStatus::Disabled).await?;
    /// # }
    /// ```
    pub(crate) async fn set_plugin_status(
        &self,
        plugin_id: &str,
        new_status: PluginStatus,
    ) -> PluginManagerResult<()> {
        let sanitized_plugin_id = sanitize_plugin_name(plugin_id)?;

        let mut plugins = self.plugins.write().await;
        let plugin_instance = plugins.get_mut(&sanitized_plugin_id).ok_or_else(|| {
            error!("插件不存在: {}", sanitized_plugin_id);
            PluginManagerError::not_found(sanitized_plugin_id.clone())
        })?;

        let old_status = plugin_instance.status.clone();

        // 验证状态转换
        if let Err(e) = old_status.validate_transition(&new_status) {
            error!(
                "插件 {} 状态转换无效: {} -> {}",
                sanitized_plugin_id, old_status, new_status
            );
            return Err(PluginManagerError::StateError(e));
        }

        // 更新状态
        plugin_instance.status = new_status.clone();

        info!(
            plugin_id = %sanitized_plugin_id,
            old_status = %old_status,
            new_status = %new_status,
            "插件状态已更新: {} ({} -> {})",
            sanitized_plugin_id,
            old_status,
            new_status
        );

        Ok(())
    }

    /// 禁用插件
    ///
    /// 将指定插件设置为禁用状态。禁用后的插件不会处理请求,但保持已加载状态。
    /// 插件必须处于 `Loaded`、`Initialized`、`Running` 或 `Stopped` 状态才能被禁用。
    ///
    /// # 参数
    /// * `plugin_id` - 要禁用的插件ID
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 错误
    /// * `PluginManagerError::NotFound` - 如果指定的插件不存在
    /// * `PluginManagerError::StateError` - 如果插件状态不允许禁用
    ///
    /// # 行为
    /// * 如果插件正在运行,会先停止插件
    /// * 将插件状态设置为 `Disabled`
    /// * 禁用后的插件不会处理任何请求
    ///
    /// # 状态转换
    /// * `Running` -> `Stopped` -> `Disabled`: 如果插件正在运行
    /// * `Initialized` -> `Disabled`: 如果插件已初始化
    /// * `Stopped` -> `Disabled`: 如果插件已停止
    /// * `Loaded` -> `Disabled`: 如果插件已加载但未初始化
    ///
    /// # 注意
    /// * 禁用插件不会卸载插件,插件仍然占用资源
    /// * 禁用后的插件可以通过重新启动来恢复运行
    /// * 如果插件正在运行,禁用前会先停止插件
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// manager.disable_plugin("my-plugin").await?;
    /// # }
    /// ```
    pub async fn disable_plugin(&self, plugin_id: &str) -> PluginManagerResult<()> {
        let sanitized_plugin_id = sanitize_plugin_name(plugin_id)?;

        info!("开始禁用插件: {}", sanitized_plugin_id);

        // 检查插件是否存在并获取当前状态
        let current_status = {
            let plugins = self.plugins.read().await;
            let plugin_instance = plugins.get(&sanitized_plugin_id).ok_or_else(|| {
                error!("插件不存在: {}", sanitized_plugin_id);
                PluginManagerError::not_found(sanitized_plugin_id.clone())
            })?;
            plugin_instance.status.clone()
        };

        // 如果插件正在运行,先停止插件
        if current_status == PluginStatus::Running {
            info!("插件 {} 正在运行,先停止插件", sanitized_plugin_id);
            self.stop_plugin(&sanitized_plugin_id).await.map_err(|e| {
                error!("停止插件失败 {}: {}", sanitized_plugin_id, e);
                PluginManagerError::StateError(format!(
                    "无法禁用正在运行的插件,停止失败: {}",
                    e
                ))
            })?;
        }

        // 设置插件状态为禁用
        self.set_plugin_status(&sanitized_plugin_id, PluginStatus::Disabled)
            .await?;

        info!("插件 {} 已禁用", sanitized_plugin_id);
        Ok(())
    }

    /// 重载单个插件
    ///
    /// 重新加载指定的插件。重载过程包括:
    /// 1. 检查插件是否存在并获取基本信息
    /// 2. 查找插件文件路径
    /// 3. 停止插件(如果正在运行)
    /// 4. 卸载插件
    /// 5. 重新加载插件
    /// 6. 插入插件实例
    /// 7. 初始化插件
    /// 8. 启动插件
    /// 9. 调用插件的 `on_reload` 生命周期钩子
    ///
    /// # 参数
    /// * `plugin_id` - 要重载的插件ID
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 错误
    /// * `PluginManagerError::NotFound` - 如果插件不存在或插件文件未找到
    /// * `PluginManagerError::ValidationFailed` - 如果插件ID验证失败
    /// * `PluginManagerError::UninstallFailed` - 如果停止或卸载插件失败
    /// * `PluginManagerError::LoadFailed` - 如果重新加载插件失败
    /// * `PluginManagerError::InitializationFailed` - 如果插件初始化失败
    /// * `PluginManagerError::StartFailed` - 如果插件启动失败
    ///
    /// # 行为
    /// * 如果插件正在运行,会先停止插件
    /// * 重载后会恢复插件的运行状态(如果之前是运行状态)
    /// * 重载过程中会调用插件的 `on_reload` 生命周期钩子
    ///
    /// # 注意
    /// 重载会重新加载插件的动态库,可能会丢失插件内部的状态。
    /// 插件可以通过 `on_reload` 钩子保存和恢复状态。
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// manager.reload_plugin("my-plugin").await?;
    /// # }
    /// ```
    pub async fn reload_plugin(&self, plugin_id: &str) -> PluginManagerResult<()> {
        let sanitized_plugin_id = sanitize_plugin_name(plugin_id)?;

        info!("开始重载插件: {}", sanitized_plugin_id);

        // 第一步:检查插件是否存在并获取基本信息
        let (plugin_name, was_running) =
            get_reload_info(self.plugins.clone(), &sanitized_plugin_id).await?;

        // 第二步:查找插件文件路径
        let plugin_file =
            find_plugin_file_by_id(&self.plugin_dir, &sanitized_plugin_id, &plugin_name).await?;
        info!("找到插件文件: {}", plugin_file);

        // 第三步:如果插件正在运行,先停止插件
        if was_running {
            info!("插件 {} 正在运行,先停止插件", sanitized_plugin_id);
            self.stop_plugin(&sanitized_plugin_id).await.map_err(|e| {
                error!("停止插件失败 {}: {}", sanitized_plugin_id, e);
                PluginManagerError::UninstallFailed(format!("停止插件失败: {}", e))
            })?;
        }

        // 第四步:卸载插件
        info!("卸载插件: {}", sanitized_plugin_id);
        self.unload_plugin(sanitized_plugin_id.clone())
            .await
            .map_err(|e| {
                error!("卸载插件失败 {}: {}", sanitized_plugin_id, e);
                PluginManagerError::UninstallFailed(format!("卸载插件失败: {}", e))
            })?;

        // 第五步:重新加载插件
        info!("重新加载插件: {}", sanitized_plugin_id);
        let logger = SharedLogger::new();
        let plugin_instance = load_plugin(
            &plugin_file,
            self.ed25519_public_key_path.clone(),
            self.rsa_private_key_path.clone(),
            &self.temp_dir,
            self.library_path.as_ref(),
            logger,
        )
        .await
        .map_err(|e| {
            error!("重新加载插件失败 {}: {}", sanitized_plugin_id, e);
            PluginManagerError::LoadFailed(format!("重新加载插件失败: {}", e))
        })?;

        // 第六步:插入插件实例
        if plugin_instance.metadata.is_sub_plugin {
            self.insert_child_plugin(plugin_instance)
                .await
                .map_err(|e| {
                    error!("挂载子插件失败 {}: {}", sanitized_plugin_id, e);
                    PluginManagerError::LoadFailed(format!("挂载子插件失败: {}", e))
                })?;
        } else {
            self.insert_plugin_instance(plugin_instance)
                .await
                .map_err(|e| {
                    error!("插入插件实例失败 {}: {}", sanitized_plugin_id, e);
                    PluginManagerError::LoadFailed(format!("插入插件实例失败: {}", e))
                })?;
        }

        // 第七步:初始化插件
        self.initialize_plugin(&sanitized_plugin_id)
            .await
            .map_err(|e| {
                error!("插件初始化失败 {}: {}", sanitized_plugin_id, e);
                e
            })?;

        // 第八步:启动插件
        self.start_plugin(&sanitized_plugin_id).await.map_err(|e| {
            error!("插件启动失败 {}: {}", sanitized_plugin_id, e);
            e
        })?;

        // 第九步:调用插件的 on_reload 生命周期钩子
        call_reload_hook(
            self.plugins.clone(),
            &sanitized_plugin_id,
            self.timeout_secs,
        )
        .await;

        info!(
            plugin_id = %sanitized_plugin_id,
            plugin_name = %plugin_name,
            "插件重载完成: {} ({})",
            plugin_name,
            sanitized_plugin_id
        );

        Ok(())
    }

    /// 启动插件目录监听
    ///
    /// 监听插件目录的变化,当检测到新的 `.spk` 文件时自动加载,删除时自动卸载。
    /// 监听器在后台异步运行,不会阻塞调用线程。
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 行为
    /// * 监听插件目录的文件系统事件
    /// * 当检测到新的 `.spk` 文件时,自动加载插件
    /// * 当检测到 `.spk` 文件删除时,自动卸载对应插件
    /// * 当检测到 `.spk` 文件修改时,重新加载插件
    /// * 使用防抖机制,避免频繁触发(默认延迟 500ms)
    ///
    /// # 错误
    /// * `PluginManagerError::Io` - 如果创建监听器失败
    /// * `PluginManagerError::ConfigError` - 如果插件目录不存在
    /// * `PluginManagerError::Other` - 如果已经在监听中
    ///
    /// # 注意
    /// * 如果已经在监听,调用此方法会返回错误
    /// * 使用 `stop_watching()` 方法可以停止监听
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// manager.watch_plugin_directory().await?;
    /// // 监听器在后台运行
    /// // ...
    /// manager.stop_watching().await?;
    /// # }
    /// ```
    pub async fn watch_plugin_directory(&mut self) -> PluginManagerResult<()> {
        // 检查是否已经在监听
        if self.watch_stop_tx.is_some() {
            return Err(PluginManagerError::Other(
                "插件目录监听已在运行中".to_string(),
            ));
        }

        // 创建停止信号通道
        let (stop_tx, stop_rx) = mpsc::channel(1);

        // 克隆必要的字段
        let plugins = self.plugins.clone();
        let plugin_dir = self.plugin_dir.clone();
        let temp_dir = self.temp_dir.clone();
        let ed25519_key = self.ed25519_public_key_path.clone();
        let rsa_key = self.rsa_private_key_path.clone();
        let library_path = self.library_path.clone();
        let timeout_secs = self.timeout_secs;

        // 启动监听任务
        tokio::spawn(async move {
            watch_ops::watch_plugin_directory(
                plugins,
                &plugin_dir,
                &temp_dir,
                ed25519_key,
                rsa_key,
                library_path.as_ref(),
                timeout_secs,
                stop_rx,
            )
            .await
            .unwrap_or_else(|e| {
                error!("插件目录监听错误: {}", e);
            });
        });

        // 保存停止信号发送器
        self.watch_stop_tx = Some(stop_tx);

        info!("插件目录监听已启动: {}", self.plugin_dir);
        Ok(())
    }

    /// 停止插件目录监听
    ///
    /// 停止正在运行的插件目录监听器。
    ///
    /// # 返回值
    /// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
    ///
    /// # 错误
    /// * `PluginManagerError::Other` - 如果监听器未运行
    ///
    /// # 示例
    /// ```no_run
    /// # async fn example() {
    /// manager.stop_watching().await?;
    /// # }
    /// ```
    pub async fn stop_watching(&mut self) -> PluginManagerResult<()> {
        if let Some(stop_tx) = self.watch_stop_tx.take() {
            stop_tx
                .send(())
                .await
                .map_err(|_| PluginManagerError::Other("发送停止信号失败".to_string()))?;
            info!("已发送停止信号,插件目录监听将停止");
            Ok(())
        } else {
            Err(PluginManagerError::Other("插件目录监听未运行".to_string()))
        }
    }
}