Skip to main content

cpa_plugin/
rpc.rs

1//! RPC calls over a plugin client and the registration contract
2//! (internal/pluginhost/rpc_client.go, rpc_schema.go).
3
4use std::sync::Arc;
5
6use bytes::Bytes;
7
8use crate::abi::{self, Envelope, method};
9use crate::api::PluginMetadata;
10use crate::client::{GuardError, GuardedClient};
11use crate::go_struct;
12use crate::gojson::{self, GoJson};
13
14/// A failed plugin call.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum CallError {
17    /// The plugin answered with an error envelope (Go `rpcError`).
18    Rpc { code: String, message: String, status: u16 },
19    /// The client is closed, the call failed below RPC, or the response did not decode.
20    Other(String),
21    /// Host code panicked; the caller fuses the plugin.
22    Panic(String),
23}
24
25impl CallError {
26    /// Go `clienterror.HTTPStatusFromError`: the status a plugin error asks for, if any.
27    pub fn status(&self) -> u16 {
28        match self {
29            CallError::Rpc { status, .. } => *status,
30            _ => 0,
31        }
32    }
33
34    pub fn code(&self) -> &str {
35        match self {
36            CallError::Rpc { code, .. } => code,
37            _ => "",
38        }
39    }
40}
41
42impl std::fmt::Display for CallError {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        match self {
45            CallError::Rpc { message, .. } => f.write_str(message),
46            CallError::Other(message) => f.write_str(message),
47            CallError::Panic(message) => write!(f, "plugin panic: {message}"),
48        }
49    }
50}
51
52impl std::error::Error for CallError {}
53
54impl From<GuardError> for CallError {
55    fn from(e: GuardError) -> Self {
56        match e {
57            GuardError::Panic(p) => CallError::Panic(p),
58            other => CallError::Other(other.to_string()),
59        }
60    }
61}
62
63/// Go `callPlugin[T]`: encode, call, decode the envelope and the result.
64pub async fn call<T: GoJson, R: GoJson>(
65    client: &Arc<GuardedClient>,
66    method: &str,
67    request: &R,
68) -> Result<T, CallError> {
69    call_raw(client, method, gojson::to_vec(request)).await
70}
71
72/// [`call`] with an already encoded request.
73pub async fn call_raw<T: GoJson>(client: &Arc<GuardedClient>, method: &str, request: Vec<u8>) -> Result<T, CallError> {
74    let raw = client.call(method, request).await?;
75    decode_response(method, &raw)
76}
77
78/// [`call_raw`] for synchronous callers ([`GuardedClient::call_blocking`]).
79pub fn call_raw_blocking<T: GoJson>(client: &Arc<GuardedClient>, method: &str, request: &[u8]) -> Result<T, CallError> {
80    let raw = client.call_blocking(method, request)?;
81    decode_response(method, &raw)
82}
83
84/// `rpc<X>Request`: a request struct's fields followed by `host_callback_id`
85/// (omitted when empty), as Go's embedding wrappers encode.
86pub fn encode_with_callback<R: gojson::GoStruct>(request: &R, callback_id: &str) -> Vec<u8> {
87    let mut out = Vec::new();
88    let mut w = gojson::ObjWriter::begin(&mut out);
89    w.embed(request);
90    w.field("host_callback_id", &callback_id.to_owned(), true);
91    w.end();
92    out
93}
94
95/// Go `decodeEnvelopeResult` after the envelope decode in `callPlugin`.
96pub fn decode_response<T: GoJson>(method: &str, raw: &[u8]) -> Result<T, CallError> {
97    let envelope =
98        Envelope::parse(raw).map_err(|e| CallError::Other(format!("decode plugin envelope {method}: {e}")))?;
99    decode_envelope(method, envelope)
100}
101
102pub fn decode_envelope<T: GoJson>(method: &str, envelope: Envelope) -> Result<T, CallError> {
103    if !envelope.ok {
104        let Some(error) = envelope.error else {
105            return Err(CallError::Other("plugin call failed".into()));
106        };
107        let message = error.message.trim();
108        return Err(CallError::Rpc {
109            code: error.code.trim().to_owned(),
110            message: if message.is_empty() {
111                "plugin call failed".into()
112            } else {
113                message.to_owned()
114            },
115            status: u16::try_from(error.http_status).unwrap_or(0),
116        });
117    }
118    match envelope.result {
119        None => Ok(T::default()),
120        Some(result) => T::decode(&result).map_err(|e| CallError::Other(format!("decode plugin result {method}: {e}"))),
121    }
122}
123
124go_struct! {
125    /// `rpcLifecycleRequest`.
126    pub struct LifecycleRequest("pluginhost.rpcLifecycleRequest") {
127        "config_yaml" => config_yaml: Bytes,
128        "schema_version" => schema_version: u32,
129    }
130}
131
132go_struct! {
133    /// `rpcCapabilities`.
134    pub struct RpcCapabilities("pluginhost.rpcCapabilities") {
135        "model_registrar" => model_registrar: bool,
136        "model_provider" => model_provider: bool,
137        "auth_provider" => auth_provider: bool,
138        "frontend_auth_provider" => frontend_auth_provider: bool,
139        "frontend_auth_provider_exclusive" => frontend_auth_provider_exclusive: bool,
140        "scheduler" => scheduler: bool,
141        "scheduler_across_priorities" omitempty => scheduler_across_priorities: bool,
142        "model_router" => model_router: bool,
143        "executor" => executor: bool,
144        "executor_model_scope" => executor_model_scope: String,
145        "executor_input_formats" omitempty => executor_input_formats: Vec<String>,
146        "executor_output_formats" omitempty => executor_output_formats: Vec<String>,
147        "request_translator" => request_translator: bool,
148        "request_normalizer" => request_normalizer: bool,
149        "request_interceptor" => request_interceptor: bool,
150        "request_lifecycle_plugin" => request_lifecycle_plugin: bool,
151        "response_translator" => response_translator: bool,
152        "response_before_translator" => response_before_translator: bool,
153        "response_after_translator" => response_after_translator: bool,
154        "response_interceptor" => response_interceptor: bool,
155        "response_stream_interceptor" => stream_chunk_interceptor: bool,
156        "websocket_response_observer" => websocket_response_observer: bool,
157        "thinking_applier" => thinking_applier: bool,
158        "usage_plugin" => usage_plugin: bool,
159        "command_line_plugin" => command_line_plugin: bool,
160        "management_api" => management_api: bool,
161        "quota_provider" => quota_provider: bool,
162    }
163}
164
165go_struct! {
166    /// `rpcRegistration`.
167    pub struct Registration("pluginhost.rpcRegistration") {
168        "schema_version" => schema_version: u32,
169        "metadata" => metadata: PluginMetadata,
170        "capabilities" => capabilities: RpcCapabilities,
171    }
172}
173
174go_struct! {
175    pub struct IdentifierResponse("pluginhost.rpcIdentifierResponse") {
176        "identifier" => identifier: String,
177    }
178}
179
180go_struct! {
181    /// `rpcEmptyResponse`: encodes `{}`, decodes anything.
182    pub struct Empty("pluginhost.rpcEmptyResponse") {}
183}
184
185/// `ExecutorModelScope`.
186pub const SCOPE_BOTH: &str = "both";
187pub const SCOPE_STATIC: &str = "static";
188pub const SCOPE_OAUTH: &str = "oauth";
189
190/// The host-side view of a registered plugin (Go `pluginapi.Plugin` built by
191/// `registerRPCPlugin`). Every capability is an RPC adapter over the same client.
192#[derive(Debug, Clone, Default, PartialEq)]
193pub struct Plugin {
194    pub metadata: PluginMetadata,
195    /// Negotiated schema; a plugin that omits it speaks schema 1.
196    pub schema_version: u32,
197    pub caps: RpcCapabilities,
198    /// `auth.identifier`, asked once at registration (empty on failure).
199    pub auth_identifier: String,
200    /// `quota.identifier`, asked once at registration.
201    pub quota_identifier: String,
202}
203
204impl Plugin {
205    /// Go `normalizedExecutorModelScope`.
206    pub fn executor_model_scope(&self) -> &str {
207        if !self.caps.executor {
208            return SCOPE_BOTH;
209        }
210        match self.caps.executor_model_scope.as_str() {
211            s @ (SCOPE_STATIC | SCOPE_OAUTH | SCOPE_BOTH) => s,
212            _ => SCOPE_BOTH,
213        }
214    }
215
216    pub fn allows_static_models(&self) -> bool {
217        !self.caps.executor || matches!(self.executor_model_scope(), SCOPE_STATIC | SCOPE_BOTH)
218    }
219
220    pub fn allows_oauth_models(&self) -> bool {
221        !self.caps.executor || matches!(self.executor_model_scope(), SCOPE_OAUTH | SCOPE_BOTH)
222    }
223
224    /// Go `validPlugin`: complete metadata and at least one capability.
225    pub fn is_valid(&self) -> bool {
226        let m = &self.metadata;
227        let filled = |s: &str| !s.trim().is_empty();
228        if !(filled(&m.name) && filled(&m.version) && filled(&m.author) && filled(&m.github_repository)) {
229            return false;
230        }
231        let c = &self.caps;
232        c.model_registrar
233            || c.model_provider
234            || c.auth_provider
235            || c.frontend_auth_provider
236            || c.scheduler
237            || c.model_router
238            || c.executor
239            || c.request_translator
240            || c.request_normalizer
241            || c.request_interceptor
242            || c.request_lifecycle_plugin
243            || c.response_translator
244            || c.response_before_translator
245            || c.response_after_translator
246            || c.response_interceptor
247            || c.stream_chunk_interceptor
248            || c.websocket_response_observer
249            || c.thinking_applier
250            || c.usage_plugin
251            || c.command_line_plugin
252            || c.management_api
253            || c.quota_provider
254    }
255}
256
257/// Go `registerRPCPlugin`: `plugin.register` or `plugin.reconfigure`, then the identifier
258/// calls registration makes eagerly.
259pub async fn register(client: &Arc<GuardedClient>, method: &str, config_yaml: &[u8]) -> Result<Plugin, CallError> {
260    let request = LifecycleRequest {
261        config_yaml: Bytes::copy_from_slice(config_yaml),
262        schema_version: abi::SCHEMA_VERSION,
263    };
264    let resp: Registration = call(client, method, &request).await?;
265    if resp.schema_version > abi::SCHEMA_VERSION {
266        return Err(CallError::Other(format!(
267            "plugin schema version {} is not supported",
268            resp.schema_version
269        )));
270    }
271    let mut caps = resp.capabilities;
272    caps.frontend_auth_provider_exclusive &= caps.frontend_auth_provider;
273    caps.scheduler_across_priorities &= caps.scheduler;
274    let mut plugin = Plugin {
275        metadata: resp.metadata,
276        schema_version: resp.schema_version.max(1),
277        caps,
278        ..Default::default()
279    };
280    if plugin.caps.auth_provider {
281        plugin.auth_identifier = identifier(client, method::AUTH_IDENTIFIER).await;
282    }
283    if plugin.caps.quota_provider {
284        plugin.quota_identifier = identifier(client, method::QUOTA_IDENTIFIER).await;
285    }
286    Ok(plugin)
287}
288
289/// Go `callPluginIdentifier`: trimmed, empty on any failure.
290pub async fn identifier(client: &Arc<GuardedClient>, method: &str) -> String {
291    match call::<IdentifierResponse, _>(client, method, &Empty {}).await {
292        Ok(resp) => resp.identifier.trim().to_owned(),
293        Err(_) => String::new(),
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300
301    #[test]
302    fn decode_response_follows_go_rpc_errors() {
303        let err = decode_response::<Empty>(
304            "m",
305            br#"{"ok":false,"error":{"code":" c ","message":"  ","http_status":429}}"#,
306        )
307        .unwrap_err();
308        assert_eq!(
309            err,
310            CallError::Rpc {
311                code: "c".into(),
312                message: "plugin call failed".into(),
313                status: 429
314            }
315        );
316        assert_eq!(
317            decode_response::<Empty>("m", br#"{"ok":false}"#).unwrap_err(),
318            CallError::Other("plugin call failed".into())
319        );
320        assert!(
321            decode_response::<IdentifierResponse>("m", b"nope")
322                .unwrap_err()
323                .to_string()
324                .starts_with("decode plugin envelope m: ")
325        );
326        let id: IdentifierResponse = decode_response("m", br#"{"ok":true}"#).unwrap();
327        assert_eq!(id.identifier, "");
328    }
329
330    #[test]
331    fn lifecycle_request_matches_go_bytes() {
332        let req = LifecycleRequest {
333            config_yaml: Bytes::from_static(b"enabled: true\n"),
334            schema_version: 6,
335        };
336        assert_eq!(
337            gojson::to_vec(&req),
338            br#"{"config_yaml":"ZW5hYmxlZDogdHJ1ZQo=","schema_version":6}"#
339        );
340        assert_eq!(gojson::to_vec(&Empty {}), b"{}");
341    }
342}