From f75ba2f2eb1d91e6c6512578abaaadd1d4bbfe6d Mon Sep 17 00:00:00 2001 From: ZhuchkaTriplesix Date: Mon, 16 Nov 2026 21:58:09 +0300 Subject: [PATCH 1/2] feat(rust): extension host NDJSON JSON-RPC skeleton Spawn extension children over stdio, run handshake/ping/shutdown, and cover the path with a querya-ext-echo round-trip test (#1903). --- apps/tauri/src-tauri/Cargo.toml | 4 + .../src-tauri/src/bin/querya_ext_echo.rs | 77 ++++++++ apps/tauri/src-tauri/src/commands.rs | 51 +++++ apps/tauri/src-tauri/src/extensions/host.rs | 167 ++++++++++++++++ apps/tauri/src-tauri/src/extensions/mod.rs | 6 + apps/tauri/src-tauri/src/extensions/rpc.rs | 183 ++++++++++++++++++ apps/tauri/src-tauri/src/lib.rs | 10 +- .../src-tauri/tests/extension_host_rpc.rs | 45 +++++ 8 files changed, 542 insertions(+), 1 deletion(-) create mode 100644 apps/tauri/src-tauri/src/bin/querya_ext_echo.rs create mode 100644 apps/tauri/src-tauri/src/extensions/host.rs create mode 100644 apps/tauri/src-tauri/src/extensions/mod.rs create mode 100644 apps/tauri/src-tauri/src/extensions/rpc.rs create mode 100644 apps/tauri/src-tauri/tests/extension_host_rpc.rs diff --git a/apps/tauri/src-tauri/Cargo.toml b/apps/tauri/src-tauri/Cargo.toml index 230e9036..27fb6fef 100644 --- a/apps/tauri/src-tauri/Cargo.toml +++ b/apps/tauri/src-tauri/Cargo.toml @@ -13,6 +13,10 @@ crate-type = ["staticlib", "cdylib", "rlib"] name = "querya-mcp" path = "src/bin/querya_mcp.rs" +[[bin]] +name = "querya-ext-echo" +path = "src/bin/querya_ext_echo.rs" + [build-dependencies] tauri-build = { version = "2", features = [] } diff --git a/apps/tauri/src-tauri/src/bin/querya_ext_echo.rs b/apps/tauri/src-tauri/src/bin/querya_ext_echo.rs new file mode 100644 index 00000000..b5e320ac --- /dev/null +++ b/apps/tauri/src-tauri/src/bin/querya_ext_echo.rs @@ -0,0 +1,77 @@ +//! Minimal echo extension for host round-trip tests (NDJSON JSON-RPC 2.0 over stdio). +//! +//! Methods: `system.handshake`, `system.ping`, `system.shutdown`, `echo.echo`. + +use serde_json::{json, Value}; +use std::io::{self, BufRead, Write}; + +fn main() { + let stdin = io::stdin(); + let mut stdout = io::stdout(); + + for line in stdin.lock().lines() { + let Ok(line) = line else { + break; + }; + if line.trim().is_empty() { + continue; + } + let Ok(req) = serde_json::from_str::(&line) else { + continue; + }; + let id = req.get("id").cloned().unwrap_or(Value::Null); + let method = req.get("method").and_then(Value::as_str).unwrap_or(""); + let params = req.get("params").cloned(); + + let response = match method { + "system.handshake" => { + let extension_id = params + .as_ref() + .and_then(|p| p.get("pluginId")) + .and_then(Value::as_str) + .unwrap_or("querya.echo"); + ok( + id, + json!({ + "protocolVersion": 1, + "extensionId": extension_id, + }), + ) + } + "system.ping" => ok(id, json!("pong")), + "echo.echo" => ok(id, params.unwrap_or(Value::Null)), + "system.shutdown" => { + let line = ok(id, json!({ "ok": true })); + let _ = writeln!(stdout, "{line}"); + let _ = stdout.flush(); + break; + } + other => err(id, -32601, format!("method not found: {other}")), + }; + + if writeln!(stdout, "{response}").is_err() { + break; + } + if stdout.flush().is_err() { + break; + } + } +} + +fn ok(id: Value, result: Value) -> String { + json!({ + "jsonrpc": "2.0", + "id": id, + "result": result, + }) + .to_string() +} + +fn err(id: Value, code: i32, message: String) -> String { + json!({ + "jsonrpc": "2.0", + "id": id, + "error": { "code": code, "message": message }, + }) + .to_string() +} diff --git a/apps/tauri/src-tauri/src/commands.rs b/apps/tauri/src-tauri/src/commands.rs index 265b2f4a..bf8a8bf0 100644 --- a/apps/tauri/src-tauri/src/commands.rs +++ b/apps/tauri/src-tauri/src/commands.rs @@ -960,3 +960,54 @@ pub fn mcp_status( ) -> Result { mcp.status() } + +/// Spawn an extension process and run `system.handshake` (#1903). +#[tauri::command] +pub async fn ext_host_start( + host: State<'_, std::sync::Arc>, + session_id: String, + executable: String, + args: Option>, + handshake_params: Option, +) -> Result { + host.start( + session_id, + std::path::PathBuf::from(executable), + args.unwrap_or_default(), + handshake_params.unwrap_or(serde_json::json!({})), + ) + .await +} + +#[tauri::command] +pub async fn ext_host_call( + host: State<'_, std::sync::Arc>, + session_id: String, + method: String, + params: Option, +) -> Result { + host.call(&session_id, &method, params).await +} + +#[tauri::command] +pub async fn ext_host_ping( + host: State<'_, std::sync::Arc>, + session_id: String, +) -> Result { + host.ping(&session_id).await +} + +#[tauri::command] +pub async fn ext_host_stop( + host: State<'_, std::sync::Arc>, + session_id: String, +) -> Result<(), String> { + host.stop(&session_id).await +} + +#[tauri::command] +pub async fn ext_host_list( + host: State<'_, std::sync::Arc>, +) -> Result, String> { + Ok(host.list().await) +} diff --git a/apps/tauri/src-tauri/src/extensions/host.rs b/apps/tauri/src-tauri/src/extensions/host.rs new file mode 100644 index 00000000..9ef8995e --- /dev/null +++ b/apps/tauri/src-tauri/src/extensions/host.rs @@ -0,0 +1,167 @@ +//! Extension process host: spawn + handshake/ping/shutdown over NDJSON JSON-RPC. + +use super::rpc::{JsonRpcStdioClient, RpcError}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::path::PathBuf; +use std::process::Stdio; +use std::sync::Arc; +use std::time::Duration; +use tokio::process::{Child, Command}; +use tokio::sync::Mutex; + +const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(15); +const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5); + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ExtensionSessionInfo { + pub session_id: String, + pub extension_id: String, + pub protocol_version: Value, + pub executable: String, +} + +struct LiveSession { + info: ExtensionSessionInfo, + child: Child, + rpc: Arc, +} + +/// In-process registry of running extension sessions. +#[derive(Default)] +pub struct ExtensionHost { + sessions: Mutex>, +} + +impl ExtensionHost { + pub fn new() -> Self { + Self::default() + } + + /// Spawn `executable` with `args`, run `system.handshake`, return session info. + pub async fn start( + &self, + session_id: String, + executable: PathBuf, + args: Vec, + handshake_params: Value, + ) -> Result { + { + let guard = self.sessions.lock().await; + if guard.contains_key(&session_id) { + return Err(format!("extension session already running: {session_id}")); + } + } + + let mut child = Command::new(&executable) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .map_err(|e| format!("spawn extension process: {e}"))?; + + let stdin = child + .stdin + .take() + .ok_or_else(|| "extension stdin unavailable".to_string())?; + let stdout = child + .stdout + .take() + .ok_or_else(|| "extension stdout unavailable".to_string())?; + + let rpc = Arc::new(JsonRpcStdioClient::new(stdin, stdout)); + + let handshake = rpc + .send_request_timeout( + "system.handshake", + Some(handshake_params), + HANDSHAKE_TIMEOUT, + ) + .await + .map_err(|e| format!("system.handshake failed: {e}"))?; + + let extension_id = handshake + .get("extensionId") + .or_else(|| handshake.get("pluginId")) + .and_then(Value::as_str) + .unwrap_or("unknown") + .to_owned(); + let protocol_version = handshake + .get("protocolVersion") + .cloned() + .unwrap_or(json!(1)); + + let info = ExtensionSessionInfo { + session_id: session_id.clone(), + extension_id, + protocol_version, + executable: executable.display().to_string(), + }; + + let mut guard = self.sessions.lock().await; + guard.insert( + session_id, + LiveSession { + info: info.clone(), + child, + rpc, + }, + ); + Ok(info) + } + + pub async fn call( + &self, + session_id: &str, + method: &str, + params: Option, + ) -> Result { + let rpc = { + let guard = self.sessions.lock().await; + let session = guard + .get(session_id) + .ok_or_else(|| format!("unknown extension session: {session_id}"))?; + Arc::clone(&session.rpc) + }; + rpc.send_request(method, params) + .await + .map_err(|e: RpcError| e.message) + } + + pub async fn ping(&self, session_id: &str) -> Result { + self.call(session_id, "system.ping", None).await + } + + pub async fn stop(&self, session_id: &str) -> Result<(), String> { + let mut session = { + let mut guard = self.sessions.lock().await; + guard + .remove(session_id) + .ok_or_else(|| format!("unknown extension session: {session_id}"))? + }; + + let _ = session + .rpc + .send_request_timeout("system.shutdown", None, SHUTDOWN_TIMEOUT) + .await; + session.rpc.close().await; + + match tokio::time::timeout(SHUTDOWN_TIMEOUT, session.child.wait()).await { + Ok(Ok(_)) => Ok(()), + Ok(Err(e)) => Err(format!("wait for extension exit: {e}")), + Err(_) => { + let _ = session.child.kill().await; + Ok(()) + } + } + } + + pub async fn list(&self) -> Vec { + let guard = self.sessions.lock().await; + guard.values().map(|s| s.info.clone()).collect() + } +} diff --git a/apps/tauri/src-tauri/src/extensions/mod.rs b/apps/tauri/src-tauri/src/extensions/mod.rs new file mode 100644 index 00000000..e7456c80 --- /dev/null +++ b/apps/tauri/src-tauri/src/extensions/mod.rs @@ -0,0 +1,6 @@ +//! Extension host: spawn child processes and speak Flutter-compatible NDJSON JSON-RPC. + +pub mod host; +pub mod rpc; + +pub use host::{ExtensionHost, ExtensionSessionInfo}; diff --git a/apps/tauri/src-tauri/src/extensions/rpc.rs b/apps/tauri/src-tauri/src/extensions/rpc.rs new file mode 100644 index 00000000..1c394b82 --- /dev/null +++ b/apps/tauri/src-tauri/src/extensions/rpc.rs @@ -0,0 +1,183 @@ +//! NDJSON JSON-RPC 2.0 client over a child process stdio (Flutter parity). + +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::sync::atomic::{AtomicI64, Ordering}; +use std::sync::Arc; +use std::time::Duration; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::process::{ChildStdin, ChildStdout}; +use tokio::sync::{oneshot, Mutex}; +use tokio::task::JoinHandle; + +const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10); +const MAX_LINE_BYTES: usize = 4 * 1024 * 1024; + +#[derive(Debug)] +pub struct RpcError { + pub message: String, +} + +impl RpcError { + fn new(message: impl Into) -> Self { + Self { + message: message.into(), + } + } +} + +impl std::fmt::Display for RpcError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for RpcError {} + +type PendingMap = HashMap>>; + +/// Host-side NDJSON JSON-RPC client (one request/response line). +pub struct JsonRpcStdioClient { + stdin: Arc>, + next_id: AtomicI64, + pending: Arc>, + reader_task: JoinHandle<()>, + closed: Arc, +} + +impl JsonRpcStdioClient { + pub fn new(stdin: ChildStdin, stdout: ChildStdout) -> Self { + let pending: Arc> = Arc::new(Mutex::new(HashMap::new())); + let pending_reader = Arc::clone(&pending); + let closed = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let closed_reader = Arc::clone(&closed); + + let reader_task = tokio::spawn(async move { + let mut lines = BufReader::new(stdout).lines(); + while let Ok(Some(line)) = lines.next_line().await { + if closed_reader.load(Ordering::SeqCst) { + break; + } + if line.len() > MAX_LINE_BYTES { + fail_all( + &pending_reader, + RpcError::new("JSON-RPC response line exceeds max size"), + ) + .await; + break; + } + let Ok(msg) = serde_json::from_str::(&line) else { + continue; + }; + let Some(id) = msg.get("id").and_then(Value::as_i64) else { + continue; + }; + let result = if let Some(err) = msg.get("error") { + Err(RpcError::new( + err.get("message") + .and_then(Value::as_str) + .unwrap_or("JSON-RPC error") + .to_owned(), + )) + } else { + Ok(msg.get("result").cloned().unwrap_or(Value::Null)) + }; + let mut guard = pending_reader.lock().await; + if let Some(tx) = guard.remove(&id) { + let _ = tx.send(result); + } + } + fail_all( + &pending_reader, + RpcError::new("extension process stdout closed"), + ) + .await; + }); + + Self { + stdin: Arc::new(Mutex::new(stdin)), + next_id: AtomicI64::new(1), + pending, + reader_task, + closed, + } + } + + pub async fn send_request( + &self, + method: &str, + params: Option, + ) -> Result { + self.send_request_timeout(method, params, DEFAULT_TIMEOUT) + .await + } + + pub async fn send_request_timeout( + &self, + method: &str, + params: Option, + timeout: Duration, + ) -> Result { + if self.closed.load(Ordering::SeqCst) { + return Err(RpcError::new("JSON-RPC client is closed")); + } + let id = self.next_id.fetch_add(1, Ordering::SeqCst); + let (tx, rx) = oneshot::channel(); + { + let mut guard = self.pending.lock().await; + guard.insert(id, tx); + } + + let mut payload = json!({ + "jsonrpc": "2.0", + "id": id, + "method": method, + }); + if let Some(p) = params { + payload["params"] = p; + } + + { + let mut stdin = self.stdin.lock().await; + let line = format!("{payload}\n"); + stdin + .write_all(line.as_bytes()) + .await + .map_err(|e| RpcError::new(format!("write RPC request: {e}")))?; + stdin + .flush() + .await + .map_err(|e| RpcError::new(format!("flush RPC request: {e}")))?; + } + + match tokio::time::timeout(timeout, rx).await { + Ok(Ok(result)) => result, + Ok(Err(_)) => Err(RpcError::new("RPC response channel dropped")), + Err(_) => { + let mut guard = self.pending.lock().await; + guard.remove(&id); + Err(RpcError::new(format!( + "JSON-RPC request \"{method}\" timed out after {timeout:?}" + ))) + } + } + } + + pub async fn close(&self) { + if self + .closed + .swap(true, Ordering::SeqCst) + { + return; + } + fail_all(&self.pending, RpcError::new("JSON-RPC client closed")).await; + self.reader_task.abort(); + } +} + +async fn fail_all(pending: &Arc>, err: RpcError) { + let mut guard = pending.lock().await; + for (_, tx) in guard.drain() { + let _ = tx.send(Err(RpcError::new(err.message.clone()))); + } +} diff --git a/apps/tauri/src-tauri/src/lib.rs b/apps/tauri/src-tauri/src/lib.rs index fd8466c4..e9479d2b 100644 --- a/apps/tauri/src-tauri/src/lib.rs +++ b/apps/tauri/src-tauri/src/lib.rs @@ -1,5 +1,6 @@ mod commands; mod connection; +pub mod extensions; pub mod mcp; mod profiles; mod secrets; @@ -14,6 +15,7 @@ pub use connection::{ }; pub use profiles::{ConnectionProfile, ProfileStore, ProfileStoreError}; pub use secrets::{KeyringSecretStore, MemorySecretStore, SecretError, SecretStore, SharedSecretStore}; +pub use extensions::{ExtensionHost, ExtensionSessionInfo}; pub use mcp::{McpController, McpError, McpStatus}; pub use ssh_tunnel::{ SshTunnelError, SshTunnelInfo, SshTunnelOpenRequest, SshTunnelRegistry, @@ -34,7 +36,7 @@ use commands::{ profiles_connect_postgres, profiles_connect_redis, profiles_connect_sqlite, profiles_delete, profiles_list, profiles_upsert, redis_get, redis_key_metas, redis_ping, redis_read_key, redis_scan, redis_set, mcp_start, mcp_status, mcp_stop, ssh_tunnel_close, ssh_tunnel_list, - ssh_tunnel_open, + ssh_tunnel_open, ext_host_start, ext_host_call, ext_host_ping, ext_host_stop, ext_host_list, }; #[tauri::command] @@ -91,6 +93,7 @@ pub fn run() { .manage(KeyringSecretStore::shared()) .manage(SshTunnelRegistry::new()) .manage(McpController::new(registry)) + .manage(std::sync::Arc::new(ExtensionHost::new())) .setup(|app| { use tauri::Manager; let store = ProfileStore::open_default().map_err(|e| { @@ -146,6 +149,11 @@ pub fn run() { mcp_start, mcp_stop, mcp_status, + ext_host_start, + ext_host_call, + ext_host_ping, + ext_host_stop, + ext_host_list, ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); diff --git a/apps/tauri/src-tauri/tests/extension_host_rpc.rs b/apps/tauri/src-tauri/tests/extension_host_rpc.rs new file mode 100644 index 00000000..bc20f7cf --- /dev/null +++ b/apps/tauri/src-tauri/tests/extension_host_rpc.rs @@ -0,0 +1,45 @@ +//! Echo extension round-trip against the NDJSON JSON-RPC host (#1903). + +use querya_desktop_tauri_lib::ExtensionHost; +use serde_json::json; +use std::path::PathBuf; + +fn echo_bin() -> PathBuf { + PathBuf::from(env!("CARGO_BIN_EXE_querya-ext-echo")) +} + +#[tokio::test] +async fn echo_extension_handshake_ping_roundtrip_shutdown() { + let host = ExtensionHost::new(); + let info = host + .start( + "echo-1".into(), + echo_bin(), + vec![], + json!({ + "queryaVersion": "0.1.0", + "pluginId": "querya.echo", + }), + ) + .await + .expect("start"); + + assert_eq!(info.extension_id, "querya.echo"); + assert_eq!(info.protocol_version, json!(1)); + + let pong = host.ping("echo-1").await.expect("ping"); + assert_eq!(pong, json!("pong")); + + let echoed = host + .call( + "echo-1", + "echo.echo", + Some(json!({ "message": "hello-from-host" })), + ) + .await + .expect("echo"); + assert_eq!(echoed, json!({ "message": "hello-from-host" })); + + host.stop("echo-1").await.expect("stop"); + assert!(host.list().await.is_empty()); +} From cbfc518b007e74c5f27bf746ede5962adddc1349 Mon Sep 17 00:00:00 2001 From: ZhuchkaTriplesix Date: Mon, 16 Nov 2026 22:05:22 +0300 Subject: [PATCH 2/2] fix(clippy): silence mongo connect arg count and dead branch Unblock Tauri CI `-D warnings` on epic-base mongo helpers. --- apps/tauri/src-tauri/src/commands.rs | 1 + apps/tauri/src-tauri/src/connection/mongo.rs | 6 +----- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/apps/tauri/src-tauri/src/commands.rs b/apps/tauri/src-tauri/src/commands.rs index bf8a8bf0..546d9741 100644 --- a/apps/tauri/src-tauri/src/commands.rs +++ b/apps/tauri/src-tauri/src/commands.rs @@ -126,6 +126,7 @@ pub fn db_connect_redis( } #[tauri::command] +#[allow(clippy::too_many_arguments)] pub fn db_connect_mongo( host: String, port: u16, diff --git a/apps/tauri/src-tauri/src/connection/mongo.rs b/apps/tauri/src-tauri/src/connection/mongo.rs index 64f305d0..95cd4f7f 100644 --- a/apps/tauri/src-tauri/src/connection/mongo.rs +++ b/apps/tauri/src-tauri/src/connection/mongo.rs @@ -258,11 +258,7 @@ pub fn open_mongo(params: MongoConnectParams) -> ConnectionResult Ok(MongoSession { id, - host: if host.contains("://") { - host.to_owned() - } else { - host.to_owned() - }, + host: host.to_owned(), port: params.port, database, client: Arc::new(Mutex::new(Some(client))),