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
//! 插件管理器配置相关定义

use super::constants::{DEFAULT_PLUGIN_DIR, DEFAULT_TEMP_DIR, DEFAULT_TIMEOUT_SECS};
use std::path::Path;

/// 插件管理器配置
pub struct PluginManagerConfig {
    /// 插件目录路径
    pub(crate) plugin_dir: String,
    /// Ed25519 公钥路径(用于验证插件数字签名)
    pub(crate) ed25519_public_key_path: Option<String>,
    /// RSA 私钥路径(用于解密 AES 密钥)
    pub(crate) rsa_private_key_path: Option<String>,
    /// 插件动态库临时目录
    pub(crate) temp_dir: String,
    /// 动态库路径(用于获取插件包下的动态库路径)
    pub(crate) library_path: Option<String>,
    /// 插件操作超时时间(秒)
    pub(crate) timeout_secs: u64,
    /// 启动目录监听
    pub(crate) enable_plugin_dir_watch: bool,
}

impl Default for PluginManagerConfig {
    fn default() -> Self {
        Self {
            plugin_dir: DEFAULT_PLUGIN_DIR.to_string(),
            ed25519_public_key_path: None,
            rsa_private_key_path: None,
            temp_dir: DEFAULT_TEMP_DIR.to_string(),
            library_path: None,
            timeout_secs: DEFAULT_TIMEOUT_SECS,
            enable_plugin_dir_watch: false
        }
    }
}

impl PluginManagerConfig {
    /// 创建新的配置构建器
    ///
    /// 使用构建器模式创建配置,允许链式调用设置各个配置项。
    ///
    /// # 返回值
    /// * `PluginManagerConfigBuilder` - 配置构建器实例
    ///
    /// # 示例
    /// ```no_run
    /// # use plugins::error::PluginManagerResult;
    /// # async fn example() -> PluginManagerResult<()> {
    /// let config = PluginManagerConfig::builder()
    ///     .plugin_dir("./plugins".to_string())
    ///     .ed25519_public_key("/path/to/key.pub".to_string())
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn builder() -> PluginManagerConfigBuilder {
        PluginManagerConfigBuilder::default()
    }

    /// 设置插件目录
    ///
    /// 设置插件文件所在的目录路径。
    ///
    /// # 参数
    /// * `dir` - 插件目录路径
    ///
    /// # 返回值
    /// * `Self` - 返回自身,支持链式调用
    pub fn with_plugin_dir(mut self, dir: String) -> Self {
        self.plugin_dir = dir;
        self
    }

    /// 设置 Ed25519 公钥路径
    ///
    /// 设置用于验证插件签名的 Ed25519 公钥文件路径。
    ///
    /// # 参数
    /// * `path` - Ed25519 公钥文件路径
    ///
    /// # 返回值
    /// * `Self` - 返回自身,支持链式调用
    pub fn with_ed25519_public_key(mut self, path: String) -> Self {
        self.ed25519_public_key_path = Some(path);
        self
    }

    /// 设置 RSA 私钥路径
    ///
    /// 设置用于解密插件包的 RSA 私钥文件路径。
    ///
    /// # 参数
    /// * `path` - RSA 私钥文件路径
    ///
    /// # 返回值
    /// * `Self` - 返回自身,支持链式调用
    pub fn with_rsa_private_key(mut self, path: String) -> Self {
        self.rsa_private_key_path = Some(path);
        self
    }

    /// 设置临时目录
    ///
    /// 设置插件解包和临时文件存储的目录路径。
    ///
    /// # 参数
    /// * `dir` - 临时目录路径
    ///
    /// # 返回值
    /// * `Self` - 返回自身,支持链式调用
    pub fn with_temp_dir(mut self, dir: String) -> Self {
        self.temp_dir = dir;
        self
    }

    /// 设置动态库路径
    ///
    /// 设置插件包中动态库文件的相对路径。如果动态库不在插件包根目录,需要指定此路径。
    ///
    /// # 参数
    /// * `path` - 动态库相对路径(相对于插件包根目录)
    ///
    /// # 返回值
    /// * `Self` - 返回自身,支持链式调用
    pub fn with_library_path(mut self, path: String) -> Self {
        self.library_path = Some(path);
        self
    }

    /// 设置超时时间(秒)
    ///
    /// 设置插件操作(初始化、启动、停止等)的默认超时时间。
    ///
    /// # 参数
    /// * `secs` - 超时时间(秒)
    ///
    /// # 返回值
    /// * `Self` - 返回自身,支持链式调用
    pub fn with_timeout_secs(mut self, secs: u64) -> Self {
        self.timeout_secs = secs;
        self
    }

    /// 设置是否启用插件目录监听
    ///
    /// 设置是否启用插件目录监听。
    ///
    /// # 参数
    /// * `enable` - 是否启用插件目录监听
    ///
    /// # 返回值
    /// * `Self` - 返回自身,支持链式调用
    pub fn with_enable_plugin_dir_watch(mut self, enable: bool) -> Self {
        self.enable_plugin_dir_watch = enable;
        self
    }

    /// 获取动态库路径
    ///
    /// 返回配置的动态库相对路径。
    ///
    /// # 返回值
    /// * `Option<&String>` - 如果配置了动态库路径返回 `Some`,否则返回 `None`
    pub fn library_path(&self) -> Option<&String> {
        self.library_path.as_ref()
    }

    /// 获取超时时间(秒)
    ///
    /// 返回配置的默认超时时间。
    ///
    /// # 返回值
    /// * `u64` - 超时时间(秒)
    pub fn timeout_secs(&self) -> u64 {
        self.timeout_secs
    }
}

/// 插件管理器配置构建器
#[derive(Default)]
pub struct PluginManagerConfigBuilder {
    plugin_dir: Option<String>,
    ed25519_public_key_path: Option<String>,
    rsa_private_key_path: Option<String>,
    temp_dir: Option<String>,
    library_path: Option<String>,
    timeout_secs: Option<u64>,
    enable_plugin_dir_watch: Option<bool>,
}

impl PluginManagerConfigBuilder {
    /// 设置插件目录
    ///
    /// 设置插件文件所在的目录路径。
    ///
    /// # 参数
    /// * `dir` - 插件目录路径
    ///
    /// # 返回值
    /// * `Self` - 返回自身,支持链式调用
    pub fn plugin_dir(mut self, dir: String) -> Self {
        self.plugin_dir = Some(dir);
        self
    }

    /// 设置 Ed25519 公钥路径
    ///
    /// 设置用于验证插件签名的 Ed25519 公钥文件路径。
    ///
    /// # 参数
    /// * `path` - Ed25519 公钥文件路径
    ///
    /// # 返回值
    /// * `Self` - 返回自身,支持链式调用
    pub fn ed25519_public_key(mut self, path: String) -> Self {
        self.ed25519_public_key_path = Some(path);
        self
    }

    /// 设置 RSA 私钥路径
    ///
    /// 设置用于解密插件包的 RSA 私钥文件路径。
    ///
    /// # 参数
    /// * `path` - RSA 私钥文件路径
    ///
    /// # 返回值
    /// * `Self` - 返回自身,支持链式调用
    pub fn rsa_private_key(mut self, path: String) -> Self {
        self.rsa_private_key_path = Some(path);
        self
    }

    /// 设置临时目录
    ///
    /// 设置插件解包和临时文件存储的目录路径。
    ///
    /// # 参数
    /// * `dir` - 临时目录路径
    ///
    /// # 返回值
    /// * `Self` - 返回自身,支持链式调用
    pub fn temp_dir(mut self, dir: String) -> Self {
        self.temp_dir = Some(dir);
        self
    }

    /// 设置动态库路径
    ///
    /// 设置插件包中动态库文件的相对路径。如果动态库不在插件包根目录,需要指定此路径。
    ///
    /// # 参数
    /// * `path` - 动态库相对路径(相对于插件包根目录)
    ///
    /// # 返回值
    /// * `Self` - 返回自身,支持链式调用
    pub fn library_path(mut self, path: String) -> Self {
        self.library_path = Some(path);
        self
    }

    /// 设置超时时间(秒)
    ///
    /// 设置插件操作(初始化、启动、停止等)的默认超时时间。
    ///
    /// # 参数
    /// * `secs` - 超时时间(秒)
    ///
    /// # 返回值
    /// * `Self` - 返回自身,支持链式调用
    pub fn timeout_secs(mut self, secs: u64) -> Self {
        self.timeout_secs = Some(secs);
        self
    }

    /// 设置是否启用插件目录监听
    ///
    /// 设置是否启用插件目录监听。
    ///
    /// # 参数
    /// * `enable` - 是否启用插件目录监听
    ///
    /// # 返回值
    /// * `Self` - 返回自身,支持链式调用
    pub fn enable_plugin_dir_watch(mut self, enable: bool) -> Self {
        self.enable_plugin_dir_watch = Some(enable);
        self
    }

    /// 构建配置
    ///
    /// 使用构建器中设置的参数创建 `PluginManagerConfig` 实例。
    /// 未设置的参数将使用默认值。
    /// 所有路径参数(`plugin_dir`、`temp_dir`、`ed25519_public_key_path`、`rsa_private_key_path`)
    /// 如果设置为相对路径,会将其转换为绝对路径(基于**程序运行时的工作目录**)。
    ///
    /// # 相对路径说明
    /// 相对路径是相对于程序运行时的工作目录(current working directory),
    /// 也就是执行程序时所在的目录。例如:
    /// - 如果在 `/project` 目录下运行程序,`./plugins` 会被解析为 `/project/plugins`
    /// - 如果在 `/other` 目录下运行程序,`./plugins` 会被解析为 `/other/plugins`
    ///
    /// 如果需要在不同目录下运行程序,建议使用绝对路径。
    ///
    /// # 返回值
    /// * `PluginManagerResult<PluginManagerConfig>` - 配置实例
    ///
    /// # 错误
    /// * `PluginManagerError::Io` - 如果路径规范化失败
    ///
    /// # 默认值
    /// * `plugin_dir`: `/opt/secra/plugins`
    /// * `temp_dir`: `/opt/secra/plugins/temp`
    /// * `timeout_secs`: `30`
    /// * `ed25519_public_key_path`: `None`
    /// * `rsa_private_key_path`: `None`
    /// * `library_path`: `None`
    ///
    /// # 示例
    /// ```no_run
    /// let config = PluginManagerConfigBuilder::default()
    ///     .plugin_dir("./plugins".to_string())
    ///     .temp_dir("./temp".to_string())
    ///     .ed25519_public_key("./keys/ed25519.pub".to_string())
    ///     .rsa_private_key("./keys/rsa.key".to_string())
    ///     .timeout_secs(60)
    ///     .build()?;
    /// ```
    pub fn build(self) -> crate::error::PluginManagerResult<PluginManagerConfig> {
        // 将相对路径转换为绝对路径
        let plugin_dir = self
            .plugin_dir
            .unwrap_or_else(|| DEFAULT_PLUGIN_DIR.to_string());
        let plugin_dir = resolve_path(&plugin_dir).map_err(|e| {
            crate::error::PluginManagerError::ConfigError(format!(
                "解析 plugin_dir 路径失败 ({}): {}",
                plugin_dir, e
            ))
        })?;

        let temp_dir = self
            .temp_dir
            .unwrap_or_else(|| DEFAULT_TEMP_DIR.to_string());
        let temp_dir = resolve_path(&temp_dir).map_err(|e| {
            crate::error::PluginManagerError::ConfigError(format!(
                "解析 temp_dir 路径失败 ({}): {}",
                temp_dir, e
            ))
        })?;

        // 将密钥路径的相对路径转换为绝对路径(如果存在)
        let ed25519_public_key_path = self
            .ed25519_public_key_path
            .map(|path| {
                resolve_path(&path).map_err(|e| {
                    crate::error::PluginManagerError::ConfigError(format!(
                        "解析 ed25519_public_key_path 路径失败 ({}): {}",
                        path, e
                    ))
                })
            })
            .transpose()?;

        let rsa_private_key_path = self
            .rsa_private_key_path
            .map(|path| {
                resolve_path(&path).map_err(|e| {
                    crate::error::PluginManagerError::ConfigError(format!(
                        "解析 rsa_private_key_path 路径失败 ({}): {}",
                        path, e
                    ))
                })
            })
            .transpose()?;

        Ok(PluginManagerConfig {
            plugin_dir,
            ed25519_public_key_path,
            rsa_private_key_path,
            temp_dir,
            library_path: self.library_path,
            timeout_secs: self.timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS),
            enable_plugin_dir_watch: self.enable_plugin_dir_watch.unwrap_or(false),
        })
    }
}

/// 解析路径,将相对路径转换为绝对路径
///
/// 如果路径是绝对路径,直接返回。
/// 如果路径是相对路径,基于**程序运行时的工作目录**(current working directory)
/// 转换为绝对路径。工作目录是执行程序时所在的目录,可以通过 `std::env::current_dir()` 获取。
///
/// # 参数
/// * `path` - 要解析的路径字符串
///
/// # 返回值
/// * `PluginManagerResult<String>` - 成功时返回绝对路径字符串
///
/// # 错误
/// * `PluginManagerError::Io` - 如果路径规范化失败
///
/// # 注意
/// 相对路径是相对于程序运行时的工作目录,而不是相对于可执行文件的位置。
/// 如果需要在不同目录下运行程序,建议使用绝对路径或确保工作目录正确。
fn resolve_path(path: &str) -> crate::error::PluginManagerResult<String> {
    let path = Path::new(path);

    // 如果已经是绝对路径,直接规范化
    if path.is_absolute() {
        let canonical = path
            .canonicalize()
            .or_else(|e| {
                // 如果路径不存在,尝试规范化父目录
                if let Some(parent) = path.parent() {
                    parent
                        .canonicalize()
                        .map(|p| p.join(path.file_name().unwrap_or_default()))
                        .map_err(|_| {
                            std::io::Error::new(
                                std::io::ErrorKind::NotFound,
                                format!(
                                    "路径不存在且无法规范化父目录: {} (原始错误: {})",
                                    path.display(),
                                    e
                                ),
                            )
                        })
                } else {
                    Err(std::io::Error::new(
                        std::io::ErrorKind::NotFound,
                        format!(
                            "路径不存在且没有父目录: {} (原始错误: {})",
                            path.display(),
                            e
                        ),
                    ))
                }
            })
            .map_err(|e| crate::error::PluginManagerError::Io(e))?;
        return Ok(canonical.to_string_lossy().to_string());
    }

    // 相对路径:基于当前工作目录转换为绝对路径
    let current_dir = std::env::current_dir().map_err(|e| {
        crate::error::PluginManagerError::Io(std::io::Error::new(
            std::io::ErrorKind::Other,
            format!("无法获取当前工作目录: {}", e),
        ))
    })?;

    let absolute_path = current_dir.join(path);

    // 尝试规范化路径(如果路径存在)
    let canonical = absolute_path
        .canonicalize()
        .or_else(|e| {
            // 如果路径不存在,尝试规范化父目录
            if let Some(parent) = absolute_path.parent() {
                parent
                    .canonicalize()
                    .map(|p| p.join(absolute_path.file_name().unwrap_or_default()))
                    .map_err(|_| {
                        std::io::Error::new(
                            std::io::ErrorKind::NotFound,
                            format!(
                                "路径不存在且无法规范化父目录: {} (基于工作目录: {}, 原始错误: {})",
                                absolute_path.display(),
                                current_dir.display(),
                                e
                            ),
                        )
                    })
            } else {
                Err(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    format!(
                        "路径不存在且没有父目录: {} (基于工作目录: {}, 原始错误: {})",
                        absolute_path.display(),
                        current_dir.display(),
                        e
                    ),
                ))
            }
        })
        .map_err(|e| crate::error::PluginManagerError::Io(e))?;

    Ok(canonical.to_string_lossy().to_string())
}