Skip to main content

zerolaunch_plugin_host/
host_dispatch.rs

1//! HostDispatch — handles reverse (plugin→host) RPC calls.
2//!
3//! Routes host/* methods to the appropriate PluginHandle calls.
4
5use zerolaunch_plugin_protocol::{codes, JsonRpcError};
6
7/// 宿主 → 插件的事件推送通道:把注册的回调经此通道以 JSON-RPC
8/// 通知(`plugin/*` 命名空间,无 id)推送给插件进程。
9pub trait PluginEventSink: Send + Sync {
10    /// 推送一条通知(fire-and-forget,失败仅记录日志)。
11    /// 参数:method - `plugin/*` 推送方法名;params - 通知载荷。
12    fn notify(&self, method: &str, params: serde_json::Value);
13}
14
15/// Maps a host/* method name to the corresponding PluginHandle call.
16/// The actual PluginHandle type is provided by src-tauri, so this is
17/// a trait-based dispatch to avoid coupling plugin-host to src-tauri.
18#[async_trait::async_trait]
19pub trait HostCallHandler: Send + Sync {
20    /// Handle a host/* RPC call. Returns Ok(serde_json::Value) on success.
21    async fn handle_host_call(
22        &self,
23        method: &str,
24        params: serde_json::Value,
25    ) -> Result<serde_json::Value, JsonRpcError>;
26
27    /// 注入宿主 → 插件的事件推送通道(重启时重新注入,覆盖旧通道)。
28    /// 默认空实现:不推送事件的宿主可忽略。
29    fn attach_event_sink(&self, _sink: std::sync::Arc<dyn PluginEventSink>) {}
30
31    /// 通知宿主推送通道已失效,注销该插件的订阅回调并取消其定时器。
32    /// 默认空实现。
33    fn detach_event_sink(&self) {}
34}
35
36impl std::fmt::Debug for dyn HostCallHandler {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        write!(f, "HostCallHandler")
39    }
40}
41
42/// Helper for creating "method not found" errors.
43pub fn method_not_found(method: &str) -> JsonRpcError {
44    JsonRpcError::new(
45        codes::METHOD_NOT_FOUND,
46        format!("host method not found: {}", method),
47    )
48}
49
50/// Helper for creating "invalid params" errors.
51pub fn invalid_params(msg: impl Into<String>) -> JsonRpcError {
52    JsonRpcError::new(codes::INVALID_PARAMS, msg)
53}