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
//! 插件目录监听相关操作

use crate::error::{PluginManagerError, PluginManagerResult};
use crate::manager::loader::load_plugin;
use crate::manager::load_ops::insert_child_plugin;
use crate::manager::load_ops::insert_plugin_instance;
use crate::manager::types::PluginMap;
use crate::manager::unload_ops::perform_unload;
use notify::{Config, Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tokio::sync::mpsc;
use tokio::time::{sleep, Duration, Instant};
use tracing::{debug, error, info, trace, warn};
use tracing_shared::SharedLogger;

/// 启动插件目录监听
///
/// 监听指定的插件目录,当检测到 `.spk` 文件的变化时,自动加载或卸载插件。
/// 监听器在后台异步运行,不会阻塞调用线程。
///
/// # 参数
/// * `plugins` - 插件实例的共享映射表
/// * `plugin_dir` - 要监听的插件目录路径
/// * `temp_dir` - 插件解包的临时目录路径
/// * `ed25519_public_key_path` - Ed25519 公钥文件路径
/// * `rsa_private_key_path` - RSA 私钥文件路径
/// * `library_path` - 可选的动态库子路径
/// * `timeout_secs` - 插件操作超时时间(秒)
/// * `stop_rx` - 停止信号接收器,用于停止监听
///
/// # 返回值
/// * `PluginManagerResult<()>` - 成功时返回 `Ok(())`
///
/// # 行为
/// * 监听插件目录的文件系统事件
/// * 当检测到新的 `.spk` 文件时,自动加载插件
/// * 当检测到 `.spk` 文件删除时,自动卸载对应插件
/// * 当检测到 `.spk` 文件修改时,重新加载插件
/// * 使用防抖机制,避免频繁触发(默认延迟 500ms)
///
/// # 错误
/// * `PluginManagerError::Io` - 如果创建监听器失败
/// * `PluginManagerError::ConfigError` - 如果插件目录不存在
///
/// # 示例
/// ```no_run
/// use std::sync::Arc;
/// use tokio::sync::{mpsc, RwLock};
/// use std::collections::HashMap;
///
/// # async fn example() {
/// let plugins = Arc::new(RwLock::new(HashMap::new()));
/// let (stop_tx, stop_rx) = mpsc::channel(1);
///
/// tokio::spawn(async move {
///     watch_plugin_directory(
///         plugins,
///         "/opt/secra/plugins",
///         "/opt/secra/plugins/temp",
///         Some("/path/to/ed25519.pub".to_string()),
///         Some("/path/to/rsa.key".to_string()),
///         None,
///         30,
///         stop_rx,
///     ).await;
/// });
///
/// // 稍后停止监听
/// stop_tx.send(()).await.ok();
/// # }
/// ```
pub async fn watch_plugin_directory(
    plugins: PluginMap,
    plugin_dir: &str,
    temp_dir: &str,
    ed25519_public_key_path: Option<String>,
    rsa_private_key_path: Option<String>,
    library_path: Option<&String>,
    _timeout_secs: u64,
    mut stop_rx: mpsc::Receiver<()>,
) -> PluginManagerResult<()> {
    trace!("开始监听插件目录: {}", plugin_dir);
    info!("开始监听插件目录: {}", plugin_dir);

    // 检查插件目录是否存在
    let plugin_dir_path = Path::new(plugin_dir);
    if !plugin_dir_path.exists() {
        error!("插件目录不存在: {}", plugin_dir);
        return Err(PluginManagerError::ConfigError(format!(
            "插件目录不存在: {}",
            plugin_dir
        )));
    }
    debug!("插件目录存在: {}", plugin_dir);

    // 创建文件系统事件通道
    let (tx, mut rx) = mpsc::channel::<Result<Event, notify::Error>>(100);
    trace!("文件系统事件通道已创建");

    // 创建 notify watcher
    let mut watcher = RecommendedWatcher::new(
        move |res| {
            // 使用 blocking_send 因为这是在同步上下文中
            if let Err(_) = tx.blocking_send(res) {
                warn!("文件系统事件通道已关闭");
            }
        },
        Config::default(),
    )
    .map_err(|e| {
        error!("创建文件系统监听器失败: {}", e);
        PluginManagerError::Io(std::io::Error::new(
            std::io::ErrorKind::Other,
            format!("创建文件系统监听器失败: {}", e),
        ))
    })?;
    debug!("文件系统监听器创建成功");

    // 开始监听目录
    watcher
        .watch(plugin_dir_path, RecursiveMode::NonRecursive)
        .map_err(|e| {
            error!("开始监听目录失败: {} - {}", plugin_dir, e);
            PluginManagerError::Io(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("开始监听目录失败: {}", e),
            ))
        })?;

    info!("插件目录监听已启动: {}", plugin_dir);
    debug!("监听器已开始工作");

    // 防抖机制:存储待处理的事件和时间戳
    let mut pending_events: HashMap<PathBuf, (EventKind, Instant)> = HashMap::new();
    let debounce_duration = Duration::from_millis(500); // 防抖延迟 500ms
    debug!("防抖机制已启用,延迟: {}ms", debounce_duration.as_millis());

    // 事件处理循环
    loop {
        tokio::select! {
            // 处理停止信号
            _ = stop_rx.recv() => {
                info!("收到停止信号,停止监听插件目录");
                trace!("监听循环退出");
                break;
            }
            // 处理文件系统事件
            event_result = rx.recv() => {
                match event_result {
                    Some(Ok(event)) => {
                        trace!("收到文件系统事件: {:?}", event.kind);
                        // 只处理 .spk 文件的事件
                        for path in &event.paths {
                            if let Some(extension) = path.extension() {
                                if extension == "spk" {
                                    trace!("检测到 .spk 文件事件: {} - {:?}", path.display(), event.kind);
                                    // 更新防抖映射
                                    pending_events.insert(path.clone(), (event.kind.clone(), Instant::now()));
                                }
                            }
                        }
                    }
                    Some(Err(e)) => {
                        error!("文件系统监听错误: {}", e);
                    }
                    None => {
                        warn!("文件系统事件通道已关闭");
                        break;
                    }
                }
            }
        }

        // 处理防抖后的事件
        let now = Instant::now();
        let mut events_to_process: Vec<(PathBuf, EventKind)> = Vec::new();
        
        pending_events.retain(|path, (kind, timestamp)| {
            if now.duration_since(*timestamp) >= debounce_duration {
                events_to_process.push((path.clone(), kind.clone()));
                false // 移除已处理的事件
            } else {
                true // 保留未到时间的事件
            }
        });

        if !events_to_process.is_empty() {
            debug!("处理 {} 个防抖后的事件", events_to_process.len());
        }

        // 处理事件
        for (path, kind) in events_to_process {
            trace!("处理文件系统事件: {} - {:?}", path.display(), kind);
            let plugins_clone = plugins.clone();
            let plugin_dir_str = plugin_dir.to_string();
            let temp_dir_str = temp_dir.to_string();
            let ed25519_key = ed25519_public_key_path.clone();
            let rsa_key = rsa_private_key_path.clone();
            let library_path_clone = library_path.map(|s| s.clone());

            tokio::spawn(async move {
                if let Err(e) = handle_file_system_event(
                    &plugins_clone,
                    &plugin_dir_str,
                    &temp_dir_str,
                    ed25519_key.as_ref(),
                    rsa_key.as_ref(),
                    library_path_clone.as_ref(),
                    &path,
                    &kind,
                ).await {
                    error!("处理文件系统事件失败: {} - {}", path.display(), e);
                }
            });
        }

        // 短暂休眠,避免 CPU 占用过高
        sleep(Duration::from_millis(100)).await;
    }

    info!("插件目录监听已停止");
    trace!("监听任务完成");
    Ok(())
}

/// 处理文件系统事件
async fn handle_file_system_event(
    plugins: &PluginMap,
    plugin_dir: &str,
    temp_dir: &str,
    ed25519_public_key_path: Option<&String>,
    rsa_private_key_path: Option<&String>,
    library_path: Option<&String>,
    path: &Path,
    kind: &EventKind,
) -> PluginManagerResult<()> {
    trace!("处理文件系统事件: {} - {:?}", path.display(), kind);
    
    match kind {
        EventKind::Create(_) => {
            info!("检测到新插件文件: {}", path.display());
            debug!("触发插件创建处理流程");
            handle_plugin_create(
                plugins,
                path,
                plugin_dir,
                temp_dir,
                ed25519_public_key_path,
                rsa_private_key_path,
                library_path,
            )
            .await
        }
        EventKind::Remove(_) => {
            info!("检测到插件文件删除: {}", path.display());
            debug!("触发插件删除处理流程");
            handle_plugin_remove(plugins, path).await
        }
        EventKind::Modify(_) => {
            info!("检测到插件文件修改: {}", path.display());
            debug!("触发插件修改处理流程(先删除再创建)");
            // 修改时先删除再创建(重新加载)
            handle_plugin_remove(plugins, path).await?;
            handle_plugin_create(
                plugins,
                path,
                plugin_dir,
                temp_dir,
                ed25519_public_key_path,
                rsa_private_key_path,
                library_path,
            )
            .await
        }
        _ => {
            // 忽略其他类型的事件
            trace!("忽略事件类型: {:?}", kind);
            Ok(())
        }
    }
}

/// 处理插件创建事件
async fn handle_plugin_create(
    plugins: &PluginMap,
    plugin_path: &Path,
    plugin_dir: &str,
    temp_dir: &str,
    ed25519_public_key_path: Option<&String>,
    rsa_private_key_path: Option<&String>,
    library_path: Option<&String>,
) -> PluginManagerResult<()> {
    trace!("处理插件创建事件: {}", plugin_path.display());
    
    let plugin_file = plugin_path
        .to_str()
        .ok_or_else(|| {
            error!("插件文件路径无效: {}", plugin_path.display());
            PluginManagerError::LoadFailed("插件文件路径无效".to_string())
        })?;

    // 检查文件是否真的存在(可能事件触发时文件还在写入)
    if !plugin_path.exists() {
        warn!("插件文件不存在,跳过加载: {}", plugin_file);
        return Ok(());
    }
    debug!("插件文件存在,等待文件写入完成");

    // 等待一小段时间,确保文件写入完成
    sleep(Duration::from_millis(100)).await;

    // 再次检查文件是否存在
    if !plugin_path.exists() {
        warn!("插件文件在等待后仍不存在,跳过加载: {}", plugin_file);
        return Ok(());
    }
    trace!("文件写入完成,开始加载插件");

    // 加载插件
    let logger = SharedLogger::new();
    match load_plugin(
        plugin_file,
        ed25519_public_key_path.cloned(),
        rsa_private_key_path.cloned(),
        temp_dir,
        library_path,
        logger,
    )
    .await
    {
        Ok(instance) => {
            let plugin_id = instance.metadata.id.clone();
            debug!("插件加载成功: {} (ID: {})", instance.metadata.name, plugin_id);
            
            // 检查插件是否已存在
            {
                let plugins_guard = plugins.read().await;
                if plugins_guard.contains_key(&plugin_id) {
                    warn!("插件 {} 已存在,跳过加载", plugin_id);
                    return Ok(());
                }
            }

            if instance.metadata.is_sub_plugin {
                // 子插件
                debug!("这是子插件,挂载到父插件");
                if let Err(e) = insert_child_plugin(plugins.clone(), instance).await {
                    error!("挂载子插件失败: {}", e);
                    return Err(e);
                }
            } else {
                // 主插件
                debug!("这是主插件,直接插入");
                if let Err(e) = insert_plugin_instance(plugins.clone(), instance).await {
                    error!("插入插件实例失败: {}", e);
                    return Err(e);
                }
            }
            info!("插件自动加载成功: {}", plugin_file);
            trace!("插件创建处理完成");
            Ok(())
        }
        Err(e) => {
            error!("插件自动加载失败: {} - {}", plugin_file, e);
            Err(e)
        }
    }
}

/// 处理插件删除事件
async fn handle_plugin_remove(
    plugins: &PluginMap,
    plugin_path: &Path,
) -> PluginManagerResult<()> {
    trace!("处理插件删除事件: {}", plugin_path.display());
    
    // 从文件路径推断插件ID
    let file_name = plugin_path
        .file_stem()
        .and_then(|s| s.to_str())
        .ok_or_else(|| {
            error!("无法从文件路径获取插件名称: {}", plugin_path.display());
            PluginManagerError::NotFound("无法从文件路径获取插件名称".to_string())
        })?;
    
    debug!("从文件名推断插件: {}", file_name);

    // 查找匹配的插件
    let plugin_id = {
        let plugins_guard = plugins.read().await;
        
        // 首先尝试通过文件名匹配插件ID(文件名格式通常是: {plugin-id}-{version}.spk)
        // 或者通过插件名称匹配
        plugins_guard
            .iter()
            .find_map(|(id, instance)| {
                // 检查文件名是否包含插件ID或名称
                let plugin_name = &instance.metadata.name;
                if file_name.contains(id) || file_name.contains(plugin_name) {
                    trace!("找到匹配的插件: {} (ID: {})", plugin_name, id);
                    Some(id.clone())
                } else {
                    None
                }
            })
    };

    if let Some(plugin_id) = plugin_id {
        info!("找到匹配的插件 {},执行卸载", plugin_id);
        debug!("开始卸载插件: {}", plugin_id);
        // 直接调用卸载操作
        perform_unload(plugins.clone(), &plugin_id).await?;
        trace!("插件删除处理完成");
        Ok(())
    } else {
        warn!(
            "未找到与文件 {} 对应的插件,跳过卸载",
            plugin_path.display()
        );
        debug!("文件名: {}", file_name);
        Ok(())
    }
}