Skip to main content

agentmux_srv_core/backend/rpc/
engine.rs

1// Copyright 2025, Command Line Inc.
2// Copyright 2025-2026, AgentMux Corp.
3// SPDX-License-Identifier: Apache-2.0
4
5//! RPC engine: handles incoming RPC requests, dispatches to handlers,
6//! and manages request/response lifecycle with timeouts and streaming.
7//! Port of Go's pkg/wshutil/wshrpc.go (WshRpc struct + handler dispatch).
8
9
10use std::collections::HashMap;
11use std::future::Future;
12use std::pin::Pin;
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::{Arc, Mutex};
15
16use tokio::sync::mpsc;
17use uuid::Uuid;
18
19use super::super::rpc_types::{RpcContext, RpcMessage, RpcOpts, COMMAND_EVENT_RECV};
20use super::schema::RpcSchema;
21
22// ---- Constants (match Go) ----
23
24pub const DEFAULT_TIMEOUT_MS: i64 = 5000;
25const RESP_CH_SIZE: usize = 32;
26
27// ---- Handler types ----
28
29/// Result type for RPC handler responses.
30pub type HandlerResult = Result<Option<serde_json::Value>, String>;
31
32/// Decides, before a command's handler runs, whether this connection may call it: `Err` is the refusal the
33/// caller is sent. Set per connection by srv (`server::dispatch_guard`).
34pub type DispatchGuard = Arc<dyn Fn(&str, &serde_json::Value, &RpcContext) -> Result<(), String> + Send + Sync>;
35
36/// A boxed async handler function.
37/// Takes the command data and returns either:
38/// - Ok(Some(value)) for a single response
39/// - Ok(None) for no response
40/// - Err(msg) for an error response
41pub type CommandHandler = Box<
42    dyn Fn(serde_json::Value, RpcContext) -> Pin<Box<dyn Future<Output = HandlerResult> + Send>>
43        + Send
44        + Sync,
45>;
46
47/// A streaming handler that returns a channel of responses.
48pub type StreamHandler = Box<
49    dyn Fn(
50            serde_json::Value,
51            RpcContext,
52        )
53            -> Pin<Box<dyn Future<Output = Result<mpsc::Receiver<HandlerResult>, String>> + Send>>
54        + Send
55        + Sync,
56>;
57
58enum Handler {
59    Call(CommandHandler),
60    #[allow(dead_code)]
61    Stream(StreamHandler),
62}
63
64// ---- RPC Response Handler ----
65
66/// Allows an RPC handler to send responses back to the caller.
67/// Matches Go's `RpcResponseHandler`.
68pub struct RpcResponseHandler {
69    engine: Arc<WshRpcEngine>,
70    req_id: String,
71    #[allow(dead_code)]
72    source: String,
73    canceled: AtomicBool,
74    done: AtomicBool,
75}
76
77impl RpcResponseHandler {
78    /// Send a single response (or streaming chunk).
79    /// Set `done` to true for the final response.
80    pub fn send_response(&self, data: Option<serde_json::Value>, done: bool) {
81        if self.done.load(Ordering::Relaxed) {
82            return;
83        }
84        let msg = RpcMessage {
85            resid: self.req_id.clone(),
86            data,
87            cont: !done,
88            ..Default::default()
89        };
90        if done {
91            self.done.store(true, Ordering::Relaxed);
92        }
93        self.engine.send_output(msg);
94    }
95
96    /// Send an error response.
97    pub fn send_error(&self, err: &str) {
98        if self.done.load(Ordering::Relaxed) {
99            return;
100        }
101        self.done.store(true, Ordering::Relaxed);
102        let msg = RpcMessage {
103            resid: self.req_id.clone(),
104            error: err.to_string(),
105            ..Default::default()
106        };
107        self.engine.send_output(msg);
108    }
109
110    /// Check if the request has been canceled.
111    #[allow(dead_code)]
112    pub fn is_canceled(&self) -> bool {
113        self.canceled.load(Ordering::Relaxed)
114    }
115
116    /// Get the source route ID of the request.
117    #[allow(dead_code)]
118    pub fn get_source(&self) -> &str {
119        &self.source
120    }
121
122    /// Mark this handler as canceled.
123    fn cancel(&self) {
124        self.canceled.store(true, Ordering::Relaxed);
125    }
126
127    /// Finalize: send empty done response if not already done.
128    fn finalize(&self) {
129        if self.done.load(Ordering::Relaxed) {
130            return;
131        }
132        self.send_response(None, true);
133    }
134}
135
136// ---- RPC Request Handler (client-side) ----
137
138/// Tracks an outgoing request and collects responses.
139/// Matches Go's `RpcRequestHandler`.
140#[allow(dead_code)]
141pub struct RpcRequestHandler {
142    req_id: String,
143    resp_rx: mpsc::Receiver<RpcMessage>,
144    last_was_cont: bool,
145}
146
147impl RpcRequestHandler {
148    /// Get the next response. Returns None if the stream is done.
149    #[allow(dead_code)]
150    pub async fn next_response(&mut self) -> Option<Result<serde_json::Value, String>> {
151        if !self.last_was_cont && self.req_id.is_empty() {
152            return None;
153        }
154        match self.resp_rx.recv().await {
155            Some(msg) => {
156                self.last_was_cont = msg.cont;
157                if !msg.error.is_empty() {
158                    Some(Err(msg.error))
159                } else {
160                    Some(Ok(msg.data.unwrap_or(serde_json::Value::Null)))
161                }
162            }
163            None => None,
164        }
165    }
166
167    /// Check if the response stream is complete.
168    #[allow(dead_code)]
169    pub fn is_done(&self) -> bool {
170        !self.last_was_cont
171    }
172
173    /// Get the request ID.
174    #[allow(dead_code)]
175    pub fn req_id(&self) -> &str {
176        &self.req_id
177    }
178}
179
180// ---- RPC Engine ----
181
182struct EngineInner {
183    handlers: HashMap<String, Handler>,
184    pending_responses: HashMap<String, mpsc::Sender<RpcMessage>>,
185    active_handlers: HashMap<String, Arc<RpcResponseHandler>>,
186    #[allow(dead_code)]
187    auth_token: String,
188    rpc_context: Option<RpcContext>,
189    /// The id a registered external host gave this connection when it proxied it (verified by srv),
190    /// kept beside the context because registering as an agent replaces the whole context.
191    gateway_conn: Option<String>,
192    /// Who may call which command; absent for an engine nothing guards (tests, in-process callers).
193    guard: Option<DispatchGuard>,
194    /// Request/response types of every command registered through
195    /// [`WshRpcEngine::register_typed`]. Lives beside `handlers` so the
196    /// mapping is a side effect of registration and cannot drift from it.
197    schema: RpcSchema,
198}
199
200/// Core RPC engine: handles incoming RPC requests, dispatches to registered
201/// command handlers, and manages request/response lifecycle.
202///
203/// Port of Go's `WshRpc` from pkg/wshutil/wshrpc.go.
204pub struct WshRpcEngine {
205    inner: Mutex<EngineInner>,
206    output_tx: mpsc::UnboundedSender<RpcMessage>,
207}
208
209impl WshRpcEngine {
210    /// Lock `inner`, recovering from mutex poison instead of propagating
211    /// the panic. A poisoned mutex means a previous handler panicked while
212    /// holding the lock — the data is still consistent for our purposes
213    /// (inserts/removes on HashMaps), so recovery is safe here.
214    fn lock_inner(&self) -> std::sync::MutexGuard<'_, EngineInner> {
215        self.inner.lock().unwrap_or_else(|e| e.into_inner())
216    }
217
218    /// Create a new RPC engine.
219    /// Returns the engine and a receiver for outgoing messages.
220    pub fn new() -> (Arc<Self>, mpsc::UnboundedReceiver<RpcMessage>) {
221        let (output_tx, output_rx) = mpsc::unbounded_channel();
222        let engine = Arc::new(Self {
223            inner: Mutex::new(EngineInner {
224                handlers: HashMap::new(),
225                pending_responses: HashMap::new(),
226                active_handlers: HashMap::new(),
227                auth_token: String::new(),
228                rpc_context: None,
229                gateway_conn: None,
230                guard: None,
231                schema: RpcSchema::new(),
232            }),
233            output_tx,
234        });
235        (engine, output_rx)
236    }
237
238    /// Install a call handler without touching the schema.
239    ///
240    /// The one path that must not evict: [`Self::register_typed`] records a
241    /// binding and then installs its wrapper, so going through the public
242    /// [`Self::register_handler`] would delete the entry it had just written.
243    fn install_call_handler(&self, command: &str, handler: CommandHandler) {
244        let mut inner = self.lock_inner();
245        inner
246            .handlers
247            .insert(command.to_string(), Handler::Call(handler));
248    }
249
250    /// Register a call handler (single request → single response).
251    ///
252    /// Drops any typed binding previously recorded for `command`: the last
253    /// registration wins for the handler map, so it must win for the schema
254    /// too, or `schema_json()` would advertise a request/response pair the
255    /// live handler no longer implements.
256    pub fn register_handler(&self, command: &str, handler: CommandHandler) {
257        self.lock_inner().schema.remove(command);
258        self.install_call_handler(command, handler);
259    }
260
261    /// Register a call handler from typed request/response values, and
262    /// record the pair in this engine's [`RpcSchema`].
263    ///
264    /// Behaviourally identical to [`Self::register_handler`]: the closure is
265    /// wrapped in exactly the deserialize → run → serialize steps every
266    /// hand-written handler already performs, so migrating one is not
267    /// supposed to change what goes over the wire. What it adds is that the
268    /// `Req`/`Resp` pairing becomes *data* the process can dump, which is
269    /// the prerequisite for generating the frontend's bindings instead of
270    /// hand-maintaining them — see `schema.rs` and
271    /// `docs/specs/SPEC_RPC_BINDINGS_CODEGEN_2026_09_07.md`.
272    ///
273    /// Two deliberate differences from the untyped path, both matching what
274    /// the existing handlers do anyway:
275    ///
276    /// - **Deserialization failure is reported as `Err`**, with the command
277    ///   name and serde's message — the same `format!("{cmd}: {e}")` shape
278    ///   the hand-written handlers use.
279    /// - **A response is always sent** (`Ok(Some(..))`). Handlers that must
280    ///   answer with nothing at all keep using `register_handler`; `Resp =
281    ///   ()` serializes to `null`, which is a response, not silence.
282    ///
283    /// Serialization failure is also an `Err` rather than a panic: a
284    /// response type whose `Serialize` fails is a bug, but it is not worth
285    /// taking the connection down for.
286    ///
287    /// Both types must derive `ts_rs::TS`: the schema records each as
288    /// TypeScript, which is what the generated frontend stubs
289    /// (`frontend/app/store/rpc-api/generated.ts`) are built from. A typed
290    /// command whose types have no TypeScript would be one the frontend has
291    /// to describe by hand again.
292    pub fn register_typed<Req, Resp, F, Fut>(&self, command: &'static str, handler: F)
293    where
294        Req: serde::de::DeserializeOwned + ts_rs::TS + Send + 'static,
295        Resp: serde::Serialize + ts_rs::TS + Send + 'static,
296        F: Fn(Req, RpcContext) -> Fut + Send + Sync + 'static,
297        Fut: std::future::Future<Output = Result<Resp, String>> + Send + 'static,
298    {
299        {
300            let mut inner = self.lock_inner();
301            inner.schema.record_typed::<Req, Resp>(command);
302        }
303
304        let handler = std::sync::Arc::new(handler);
305        // install_call_handler, not register_handler: the latter evicts the
306        // schema entry recorded just above.
307        self.install_call_handler(
308            command,
309            Box::new(move |data, ctx| {
310                let handler = handler.clone();
311                Box::pin(async move {
312                    let req: Req = serde_json::from_value(data)
313                        .map_err(|e| format!("{command}: {e}"))?;
314                    let resp = handler(req, ctx).await?;
315                    let value = serde_json::to_value(&resp)
316                        .map_err(|e| format!("{command}: response is not serializable: {e}"))?;
317                    Ok(Some(value))
318                })
319            }),
320        );
321    }
322
323    /// Snapshot of every typed command's request/response pair, in command
324    /// order. Handlers registered through the untyped [`Self::register_handler`]
325    /// are absent — that is what lets the migration proceed one at a time.
326    #[cfg(any(test, feature = "test-support"))]
327    pub fn schema_json(&self) -> serde_json::Value {
328        self.lock_inner().schema.to_json()
329    }
330
331    /// Every command with a handler, typed or not, sorted.
332    #[cfg(any(test, feature = "test-support"))]
333    pub fn command_names(&self) -> Vec<String> {
334        let mut names: Vec<String> = self.lock_inner().handlers.keys().cloned().collect();
335        names.sort();
336        names
337    }
338
339    /// Number of commands registered through the typed path.
340    #[cfg(test)]
341    pub fn typed_command_count(&self) -> usize {
342        self.lock_inner().schema.len()
343    }
344
345    /// Register a streaming handler (single request → stream of responses).
346    #[allow(dead_code)]
347    pub fn register_stream_handler(&self, command: &str, handler: StreamHandler) {
348        let mut inner = self.lock_inner();
349        // Same eviction as register_handler — a streaming command has no
350        // single typed response to describe.
351        inner.schema.remove(command);
352        inner
353            .handlers
354            .insert(command.to_string(), Handler::Stream(handler));
355    }
356
357    /// Set the authentication token.
358    #[allow(dead_code)]
359    pub fn set_auth_token(&self, token: &str) {
360        let mut inner = self.lock_inner();
361        inner.auth_token = token.to_string();
362    }
363
364    /// Get the authentication token.
365    #[allow(dead_code)]
366    pub fn get_auth_token(&self) -> String {
367        let inner = self.lock_inner();
368        inner.auth_token.clone()
369    }
370
371    /// Set the RPC context.
372    #[allow(dead_code)]
373    pub fn set_rpc_context(&self, ctx: RpcContext) {
374        let mut inner = self.lock_inner();
375        inner.rpc_context = Some(ctx);
376    }
377
378    /// Guard every command this connection calls: `guard` runs before the handler and a refusal is the answer.
379    pub fn set_dispatch_guard(&self, guard: DispatchGuard) {
380        self.lock_inner().guard = Some(guard);
381    }
382
383    /// Whether this connection may call `command` (also asked for the websocket's own input commands, which
384    /// do not go through [`Self::handle_message`]).
385    pub fn check_dispatch(&self, command: &str, data: &serde_json::Value) -> Result<(), String> {
386        let (guard, ctx) = {
387            let inner = self.lock_inner();
388            (inner.guard.clone(), inner.rpc_context.clone().unwrap_or_default())
389        };
390        guard.map_or(Ok(()), |g| g(command, data, &ctx))
391    }
392
393    /// Answers a call that must not run (no such command, or the guard refuses this connection it), recording a refusal; true when it did.
394    fn refuse_before_running(&self, command: &str, data: &serde_json::Value, ctx: &RpcContext, reqid: &str, handler: &RpcResponseHandler, known: bool) -> bool {
395        let refusal = if known { self.check_dispatch(command, data).err() } else { Some(format!("unknown command: {command}")) };
396        let Some(refusal) = refusal else { return false };
397        if known {
398            super::action_record::after_call(command, data, ctx, reqid, &Err(refusal.clone()));
399        }
400        handler.send_error(&refusal);
401        self.cleanup_handler(reqid);
402        true
403    }
404
405    /// The context handlers get for this connection's next call.
406    pub fn rpc_context(&self) -> RpcContext {
407        self.lock_inner().rpc_context.clone().unwrap_or_default()
408    }
409
410    /// Record that the CEF host (or, on a headless srv, a confirmed local
411    /// browser session) vouched for this connection as the person's window
412    /// (`server::operator_proof`). Refused, returning false, once the
413    /// connection has registered as an agent. [`Self::set_rpc_context`]
414    /// replaces the whole context, so registering afterwards drops the proof.
415    pub fn mark_operator_proven(&self) -> bool {
416        let mut inner = self.lock_inner();
417        let ctx = inner.rpc_context.get_or_insert_with(RpcContext::default);
418        if !ctx.agent_id.is_empty() {
419            return false;
420        }
421        ctx.operator_proven = true;
422        true
423    }
424
425    /// Record that a registered external host vouched for this connection as `person`'s window until the
426    /// unix second `until` (`server::external_host`). Refused, returning false, once the connection has
427    /// registered as an agent; registering afterwards drops the proof, as for the CEF host's.
428    pub fn mark_operator_proven_for(&self, person: &str, until: u64) -> bool {
429        let mut inner = self.lock_inner();
430        let ctx = inner.rpc_context.get_or_insert_with(RpcContext::default);
431        if !ctx.agent_id.is_empty() {
432            return false;
433        }
434        ctx.operator_proven = true;
435        ctx.operator_person = Some(person.to_string());
436        ctx.operator_proof_until = Some(until);
437        true
438    }
439
440    /// Drop any operator proof this connection holds (an external host's lease that was ended).
441    pub fn clear_operator_proof(&self) {
442        let mut inner = self.lock_inner();
443        if let Some(ctx) = inner.rpc_context.as_mut() {
444            ctx.operator_proven = false;
445            ctx.operator_person = None;
446            ctx.operator_proof_until = None;
447        }
448    }
449
450    /// Remember the id an external host gave this connection (set once, when it connects).
451    pub fn set_gateway_conn(&self, id: String) {
452        self.lock_inner().gateway_conn = Some(id);
453    }
454
455    /// The id an external host gave this connection, if it came through one and srv verified it.
456    pub fn gateway_conn(&self) -> Option<String> {
457        self.lock_inner().gateway_conn.clone()
458    }
459
460    /// Process an incoming message (from the transport layer).
461    pub fn handle_message(self: &Arc<Self>, msg: RpcMessage) {
462        // Cancel handling
463        if msg.cancel {
464            if !msg.reqid.is_empty() {
465                self.handle_cancel_request(&msg.reqid);
466            }
467            return;
468        }
469
470        // Event handling (special: no response)
471        if msg.command == COMMAND_EVENT_RECV {
472            // Events are handled by the event listener, not via RPC handlers
473            return;
474        }
475
476        // New command (request)
477        if !msg.command.is_empty() {
478            let engine = self.clone();
479            tokio::spawn(async move {
480                engine.handle_request(msg).await;
481            });
482            return;
483        }
484
485        // Response (has resid)
486        if !msg.resid.is_empty() {
487            self.handle_response(msg);
488        }
489    }
490
491    /// Send an RPC command and wait for a single response.
492    #[allow(dead_code)]
493    pub async fn send_command(
494        self: &Arc<Self>,
495        command: &str,
496        data: serde_json::Value,
497        opts: &RpcOpts,
498    ) -> Result<serde_json::Value, String> {
499        let mut handler = self.send_request(command, data, opts)?;
500        match handler.next_response().await {
501            Some(result) => result,
502            None => Err("no response received".to_string()),
503        }
504    }
505
506    /// Send an RPC command and get a request handler for streaming responses.
507    #[allow(dead_code)]
508    pub fn send_request(
509        self: &Arc<Self>,
510        command: &str,
511        data: serde_json::Value,
512        opts: &RpcOpts,
513    ) -> Result<RpcRequestHandler, String> {
514        let req_id = Uuid::new_v4().to_string();
515        let (resp_tx, resp_rx) = mpsc::channel(RESP_CH_SIZE);
516
517        {
518            let mut inner = self.lock_inner();
519            inner
520                .pending_responses
521                .insert(req_id.clone(), resp_tx);
522        }
523
524        let timeout = if opts.timeout > 0 {
525            opts.timeout
526        } else {
527            DEFAULT_TIMEOUT_MS
528        };
529        let route = if opts.route.is_empty() {
530            String::new()
531        } else {
532            opts.route.clone()
533        };
534
535        let msg = RpcMessage {
536            command: command.to_string(),
537            reqid: req_id.clone(),
538            timeout,
539            route,
540            data: Some(data),
541            authtoken: self.get_auth_token(),
542            ..Default::default()
543        };
544        self.send_output(msg);
545
546        Ok(RpcRequestHandler {
547            req_id,
548            resp_rx,
549            last_was_cont: true, // assume more data initially
550        })
551    }
552
553    /// Send a fire-and-forget command (no response expected).
554    #[allow(dead_code)]
555    pub fn send_command_no_response(
556        &self,
557        command: &str,
558        data: serde_json::Value,
559        route: &str,
560    ) {
561        let msg = RpcMessage {
562            command: command.to_string(),
563            data: Some(data),
564            route: route.to_string(),
565            authtoken: self.get_auth_token(),
566            ..Default::default()
567        };
568        self.send_output(msg);
569    }
570
571    // ---- Internal ----
572
573    fn send_output(&self, msg: RpcMessage) {
574        if self.output_tx.send(msg).is_err() {
575            tracing::warn!("[rpc-engine] output channel closed — message dropped");
576        }
577    }
578
579    async fn handle_request(self: Arc<Self>, msg: RpcMessage) {
580        let request_start = std::time::Instant::now();
581        let timeout_ms = if msg.timeout > 0 {
582            msg.timeout
583        } else {
584            DEFAULT_TIMEOUT_MS
585        };
586
587        let handler = Arc::new(RpcResponseHandler {
588            engine: self.clone(),
589            req_id: msg.reqid.clone(),
590            source: msg.source.clone(),
591            canceled: AtomicBool::new(false),
592            done: AtomicBool::new(false),
593        });
594
595        // Register the active handler
596        if !msg.reqid.is_empty() {
597            let mut inner = self.lock_inner();
598            inner
599                .active_handlers
600                .insert(msg.reqid.clone(), handler.clone());
601        }
602
603        let rpc_context = {
604            let inner = self.lock_inner();
605            inner.rpc_context.clone().unwrap_or_default()
606        };
607
608        let data = msg.data.unwrap_or(serde_json::Value::Null);
609        let command = msg.command.clone();
610
611        // Look up handler
612        let has_call;
613        let has_stream;
614        {
615            let inner = self.lock_inner();
616            match inner.handlers.get(&command) {
617                Some(Handler::Call(_)) => {
618                    has_call = true;
619                    has_stream = false;
620                }
621                Some(Handler::Stream(_)) => {
622                    has_call = false;
623                    has_stream = true;
624                }
625                None => {
626                    has_call = false;
627                    has_stream = false;
628                }
629            }
630        }
631
632        let dispatch_elapsed = request_start.elapsed();
633
634        if self.refuse_before_running(&command, &data, &rpc_context, &msg.reqid, &handler, has_call || has_stream) {
635            return;
636        }
637
638        let timeout_dur = std::time::Duration::from_millis(timeout_ms as u64);
639
640        if has_call {
641            // Call handler: single response with timeout.
642            // Create the future while holding the lock, then drop the lock before awaiting.
643            let handler_start = std::time::Instant::now();
644            let fut = {
645                let inner = self.lock_inner();
646                match inner.handlers.get(&command) {
647                    Some(Handler::Call(h)) => h(data.clone(), rpc_context.clone()),
648                    _ => Box::pin(async { Err("handler disappeared".to_string()) }),
649                }
650            };
651            let result = tokio::time::timeout(timeout_dur, fut).await;
652            let handler_elapsed = handler_start.elapsed();
653            let total_elapsed = request_start.elapsed();
654
655            // debug, not info: fires on every websocket RPC call, of any kind
656            // — ~27% of an unrotated 406 MB launcher-log mirror on a real
657            // machine (SPEC_WIN10_PAGEFILE_OOM_CRASH_2026_06_29 P1). Default
658            // production filter is info, so this is now suppressed unless
659            // RUST_LOG=debug is set; still there for perf debugging on demand.
660            tracing::debug!(
661                "[rpc-perf] command={} dispatch={:.2}ms handler={:.2}ms total={:.2}ms",
662                command,
663                dispatch_elapsed.as_secs_f64() * 1000.0,
664                handler_elapsed.as_secs_f64() * 1000.0,
665                total_elapsed.as_secs_f64() * 1000.0,
666            );
667
668            // Who did what, recorded here so no handler can leave it out (`action_record`).
669            let outcome = match &result {
670                Ok(Ok(resp)) => super::action_record::outcome_of_response(&command, resp.as_ref()),
671                Ok(Err(err)) => Err(err.clone()),
672                Err(_) => Err(format!("EC-TIME: timeout ({}ms)", timeout_ms)),
673            };
674            super::action_record::after_call(&command, &data, &rpc_context, &msg.reqid, &outcome);
675
676            match result {
677                Ok(Ok(resp_data)) => handler.send_response(resp_data, true),
678                Ok(Err(err)) => handler.send_error(&err),
679                Err(_) => handler.send_error(&format!("EC-TIME: timeout ({}ms)", timeout_ms)),
680            }
681        } else {
682            // Stream handler: same pattern — build future under lock, await outside.
683            let fut = {
684                let inner = self.lock_inner();
685                match inner.handlers.get(&command) {
686                    Some(Handler::Stream(h)) => h(data.clone(), rpc_context.clone()),
687                    _ => Box::pin(async { Err("handler disappeared".to_string()) }),
688                }
689            };
690            let stream_result = tokio::time::timeout(timeout_dur, fut).await;
691            let outcome = match &stream_result {
692                Ok(Ok(_)) => Ok(()),
693                Ok(Err(err)) => Err(err.clone()),
694                Err(_) => Err(format!("EC-TIME: timeout ({}ms)", timeout_ms)),
695            };
696            super::action_record::after_call(&command, &data, &rpc_context, &msg.reqid, &outcome);
697
698            match stream_result {
699                Ok(Ok(mut rx)) => {
700                    // Read streaming responses
701                    loop {
702                        match tokio::time::timeout(timeout_dur, rx.recv()).await {
703                            Ok(Some(Ok(resp_data))) => {
704                                handler.send_response(resp_data, false);
705                            }
706                            Ok(Some(Err(err))) => {
707                                handler.send_error(&err);
708                                break;
709                            }
710                            Ok(None) => {
711                                // Channel closed — stream done
712                                handler.finalize();
713                                break;
714                            }
715                            Err(_) => {
716                                handler.send_error(&format!(
717                                    "EC-TIME: stream timeout ({}ms)",
718                                    timeout_ms
719                                ));
720                                break;
721                            }
722                        }
723                    }
724                }
725                Ok(Err(err)) => handler.send_error(&err),
726                Err(_) => {
727                    handler.send_error(&format!("EC-TIME: timeout ({}ms)", timeout_ms))
728                }
729            }
730        }
731
732        self.cleanup_handler(&msg.reqid);
733    }
734
735    fn handle_response(&self, msg: RpcMessage) {
736        let inner = self.lock_inner();
737        if let Some(tx) = inner.pending_responses.get(&msg.resid) {
738            let is_done = !msg.cont;
739            if tx.try_send(msg.clone()).is_err() {
740                tracing::warn!(resid = %msg.resid, "[rpc-engine] response channel full/closed — reply dropped");
741            }
742            if is_done {
743                drop(inner);
744                let mut inner = self.lock_inner();
745                inner.pending_responses.remove(&msg.resid);
746            }
747        }
748    }
749
750    fn handle_cancel_request(&self, req_id: &str) {
751        let inner = self.lock_inner();
752        if let Some(handler) = inner.active_handlers.get(req_id) {
753            handler.cancel();
754        }
755    }
756
757    fn cleanup_handler(&self, req_id: &str) {
758        if req_id.is_empty() {
759            return;
760        }
761        let mut inner = self.lock_inner();
762        inner.active_handlers.remove(req_id);
763    }
764}
765
766// ====================================================================
767// Tests
768// ====================================================================
769
770#[cfg(test)]
771mod tests {
772    use super::*;
773
774    /// Replacing a typed command through an untyped path clears its schema
775    /// entry (codex P2 on #3074).
776    ///
777    /// The handler map's last-registration-wins rule has to hold for the
778    /// schema too. If it did not, `schema_json()` would keep advertising the
779    /// old request/response pair for a command whose live handler no longer
780    /// accepts it — and a generator reading that would emit a client stub
781    /// that fails at runtime. A stale binding is worse than a missing one.
782    #[tokio::test]
783    async fn replacing_a_typed_command_through_an_untyped_path_clears_its_schema_entry() {
784        #[derive(serde::Deserialize, ts_rs::TS)]
785        struct Req {
786            #[allow(dead_code)]
787            v: i32,
788        }
789        #[derive(serde::Serialize, ts_rs::TS)]
790        struct Resp {
791            ok: bool,
792        }
793
794        let (engine, _rx) = WshRpcEngine::new();
795        engine.register_typed("typed-then-untyped", |_r: Req, _ctx| async move {
796            Ok(Resp { ok: true })
797        });
798        assert_eq!(engine.typed_command_count(), 1, "typed registration should be recorded");
799
800        // Same command, now an untyped handler.
801        engine.register_handler(
802            "typed-then-untyped",
803            Box::new(|_data, _ctx| Box::pin(async move { Ok(Some(serde_json::json!("plain"))) })),
804        );
805        assert_eq!(
806            engine.typed_command_count(),
807            0,
808            "an untyped re-registration must drop the stale typed pair",
809        );
810
811        // And the same via the streaming path, which has no single response
812        // type to describe at all.
813        engine.register_typed("typed-then-stream", |_r: Req, _ctx| async move {
814            Ok(Resp { ok: true })
815        });
816        assert_eq!(engine.typed_command_count(), 1);
817        engine.register_stream_handler(
818            "typed-then-stream",
819            Box::new(|_data, _ctx| {
820                Box::pin(async move {
821                    let (_tx, rx) = mpsc::channel(1);
822                    Ok(rx)
823                })
824            }),
825        );
826        assert_eq!(
827            engine.typed_command_count(),
828            0,
829            "a streaming re-registration must drop the stale typed pair too",
830        );
831    }
832
833    #[tokio::test]
834    async fn register_typed_still_records_after_the_wrapper_is_installed() {
835        // Guards the ordering inside register_typed: it records the binding
836        // and then installs the wrapper. Routing that install through the
837        // public evicting path would delete the entry it had just written,
838        // and this assertion is what catches that.
839        //
840        // NB: keep either registration function's name away from an
841        // immediately-following parenthesised word in prose here.
842        // test/contract/rpc-contract.test.ts scans this file with a regex
843        // that does not skip comments, so such a phrase reads to it as a
844        // real registration whose command it cannot resolve, and fails the
845        // contract extractor. (This comment is deliberately phrased to
846        // describe the trap without containing it.)
847        #[derive(serde::Deserialize, ts_rs::TS)]
848        struct Req {
849            #[allow(dead_code)]
850            v: i32,
851        }
852        #[derive(serde::Serialize, ts_rs::TS)]
853        struct Resp {
854            ok: bool,
855        }
856
857        let (engine, _rx) = WshRpcEngine::new();
858        engine.register_typed("stays-recorded", |_r: Req, _ctx| async move {
859            Ok(Resp { ok: true })
860        });
861        let schema = engine.schema_json();
862        let rows = schema.as_array().unwrap();
863        assert_eq!(rows.len(), 1, "register_typed must not evict its own entry");
864        assert_eq!(rows[0]["command"], "stays-recorded");
865    }
866
867    #[tokio::test]
868    async fn test_register_and_call_handler() {
869        let (engine, mut output_rx) = WshRpcEngine::new();
870
871        engine.register_handler(
872            "echo",
873            Box::new(|data, _ctx| {
874                Box::pin(async move { Ok(Some(data)) })
875            }),
876        );
877
878        let msg = RpcMessage {
879            command: "echo".to_string(),
880            reqid: "req-1".to_string(),
881            data: Some(serde_json::json!({"hello": "world"})),
882            ..Default::default()
883        };
884        engine.handle_message(msg);
885
886        // Collect the response
887        let resp = tokio::time::timeout(
888            std::time::Duration::from_secs(1),
889            output_rx.recv(),
890        )
891        .await
892        .unwrap()
893        .unwrap();
894
895        assert_eq!(resp.resid, "req-1");
896        assert!(!resp.cont);
897        assert_eq!(resp.data, Some(serde_json::json!({"hello": "world"})));
898    }
899
900    #[tokio::test]
901    async fn test_unknown_command_returns_error() {
902        let (engine, mut output_rx) = WshRpcEngine::new();
903
904        let msg = RpcMessage {
905            command: "nonexistent".to_string(),
906            reqid: "req-2".to_string(),
907            ..Default::default()
908        };
909        engine.handle_message(msg);
910
911        let resp = tokio::time::timeout(
912            std::time::Duration::from_secs(1),
913            output_rx.recv(),
914        )
915        .await
916        .unwrap()
917        .unwrap();
918
919        assert_eq!(resp.resid, "req-2");
920        assert!(resp.error.contains("unknown command"));
921    }
922
923    #[tokio::test]
924    async fn test_handler_error_returns_error_response() {
925        let (engine, mut output_rx) = WshRpcEngine::new();
926
927        engine.register_handler(
928            "failme",
929            Box::new(|_data, _ctx| {
930                Box::pin(async move { Err("something went wrong".to_string()) })
931            }),
932        );
933
934        let msg = RpcMessage {
935            command: "failme".to_string(),
936            reqid: "req-3".to_string(),
937            ..Default::default()
938        };
939        engine.handle_message(msg);
940
941        let resp = tokio::time::timeout(
942            std::time::Duration::from_secs(1),
943            output_rx.recv(),
944        )
945        .await
946        .unwrap()
947        .unwrap();
948
949        assert_eq!(resp.error, "something went wrong");
950    }
951
952    #[tokio::test]
953    async fn test_send_command_roundtrip() {
954        let (engine, mut output_rx) = WshRpcEngine::new();
955
956        // Spawn a "server" that echoes responses
957        let engine_clone = engine.clone();
958        tokio::spawn(async move {
959            if let Some(msg) = output_rx.recv().await {
960                // This is the outgoing request — echo it back as a response
961                let resp = RpcMessage {
962                    resid: msg.reqid.clone(),
963                    data: msg.data.clone(),
964                    ..Default::default()
965                };
966                engine_clone.handle_message(resp);
967            }
968        });
969
970        let opts = RpcOpts {
971            timeout: 1000,
972            ..Default::default()
973        };
974        let result = engine
975            .send_command("test", serde_json::json!(42), &opts)
976            .await;
977
978        assert!(result.is_ok());
979        assert_eq!(result.unwrap(), serde_json::json!(42));
980    }
981
982    #[tokio::test]
983    async fn test_stream_handler() {
984        let (engine, mut output_rx) = WshRpcEngine::new();
985
986        engine.register_stream_handler(
987            "counter",
988            Box::new(|_data, _ctx| {
989                Box::pin(async move {
990                    let (tx, rx) = mpsc::channel(8);
991                    tokio::spawn(async move {
992                        for i in 0..3 {
993                            let _ = tx.send(Ok(Some(serde_json::json!(i)))).await;
994                        }
995                        // Channel drops → stream done
996                    });
997                    Ok(rx)
998                })
999            }),
1000        );
1001
1002        let msg = RpcMessage {
1003            command: "counter".to_string(),
1004            reqid: "req-stream".to_string(),
1005            ..Default::default()
1006        };
1007        engine.handle_message(msg);
1008
1009        // Collect streaming responses
1010        let mut responses = Vec::new();
1011        for _ in 0..4 {
1012            // 3 data + 1 final empty
1013            match tokio::time::timeout(
1014                std::time::Duration::from_secs(2),
1015                output_rx.recv(),
1016            )
1017            .await
1018            {
1019                Ok(Some(resp)) => responses.push(resp),
1020                _ => break,
1021            }
1022        }
1023
1024        // Should have 3 streaming chunks + 1 final
1025        assert!(responses.len() >= 3);
1026        // First 3 have cont=true
1027        for resp in &responses[..3] {
1028            assert!(resp.cont);
1029        }
1030        // Last one has cont=false (finalize)
1031        if responses.len() == 4 {
1032            assert!(!responses[3].cont);
1033        }
1034    }
1035
1036    // Paused clock: the handler's 10 s sleep and the 12 s wait below pass at
1037    // once instead of in real time.
1038    #[tokio::test(start_paused = true)]
1039    async fn test_cancel_request() {
1040        let (engine, mut output_rx) = WshRpcEngine::new();
1041
1042        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
1043        engine.register_handler(
1044            "slow",
1045            Box::new(move |_data, _ctx| {
1046                Box::pin(async move {
1047                    // Signal that we started
1048                    // (can't move started_tx into closure that's called multiple times)
1049                    tokio::time::sleep(std::time::Duration::from_secs(10)).await;
1050                    Ok(Some(serde_json::json!("done")))
1051                })
1052            }),
1053        );
1054
1055        // Send command
1056        let msg = RpcMessage {
1057            command: "slow".to_string(),
1058            reqid: "req-cancel".to_string(),
1059            timeout: 10000,
1060            ..Default::default()
1061        };
1062        engine.handle_message(msg);
1063
1064        // Small delay then send cancel
1065        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1066        let cancel_msg = RpcMessage {
1067            cancel: true,
1068            reqid: "req-cancel".to_string(),
1069            ..Default::default()
1070        };
1071        engine.handle_message(cancel_msg);
1072
1073        // The handler will still time out or complete, but the cancel flag should be set
1074        // Just verify we get a response eventually (timeout response)
1075        let resp = tokio::time::timeout(
1076            std::time::Duration::from_secs(12),
1077            output_rx.recv(),
1078        )
1079        .await;
1080        assert!(resp.is_ok());
1081        // Clean up to avoid unused variable warning
1082        drop(started_tx);
1083        drop(started_rx);
1084    }
1085
1086    #[tokio::test]
1087    async fn test_send_command_no_response() {
1088        let (engine, mut output_rx) = WshRpcEngine::new();
1089
1090        engine.send_command_no_response("notify", serde_json::json!({"msg": "hi"}), "");
1091
1092        let msg = tokio::time::timeout(
1093            std::time::Duration::from_millis(100),
1094            output_rx.recv(),
1095        )
1096        .await
1097        .unwrap()
1098        .unwrap();
1099
1100        assert_eq!(msg.command, "notify");
1101        assert!(msg.reqid.is_empty());
1102    }
1103
1104    #[tokio::test]
1105    async fn test_auth_token() {
1106        let (engine, _output_rx) = WshRpcEngine::new();
1107        assert!(engine.get_auth_token().is_empty());
1108
1109        engine.set_auth_token("my-secret-token");
1110        assert_eq!(engine.get_auth_token(), "my-secret-token");
1111    }
1112
1113    #[tokio::test]
1114    async fn test_rpc_context() {
1115        let (engine, _output_rx) = WshRpcEngine::new();
1116
1117        let ctx = RpcContext {
1118            client_type: "connserver".to_string(),
1119            blockid: "blk-1".to_string(),
1120            ..Default::default()
1121        };
1122        engine.set_rpc_context(ctx);
1123
1124        // The context is passed to handlers
1125        engine.register_handler(
1126            "checkctx",
1127            Box::new(|_data, ctx| {
1128                Box::pin(async move {
1129                    Ok(Some(serde_json::json!({
1130                        "ctype": ctx.client_type,
1131                        "blockid": ctx.blockid,
1132                    })))
1133                })
1134            }),
1135        );
1136
1137        let msg = RpcMessage {
1138            command: "checkctx".to_string(),
1139            reqid: "req-ctx".to_string(),
1140            ..Default::default()
1141        };
1142        engine.handle_message(msg);
1143
1144        // Output will contain the context
1145        // (tested indirectly through handler dispatch)
1146    }
1147}