simplejrpc 0.1.0

Unix-socket JSON-RPC 2.0 SDK with middleware, config, and validation
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
//! Request context and Unix-socket JSON-RPC server.
//!
//! # Architecture
//!
//! ```text
//! UnixListener.accept
//!   → read Content-Length frame
//!   → parse JSON-RPC request
//!   → MiddlewareChain.run_request
//!   → dispatch handler by method name
//!   → wrap AppResponse
//!   → MiddlewareChain.run_response
//!   → write framed JSON-RPC response
//! ```
//!
//! # Examples
//!
//! ## Minimal server
//!
//! ```no_run
//! use simplejrpc::Server;
//! use serde_json::json;
//!
//! # async fn demo() -> simplejrpc::Result<()> {
//! let srv = Server::builder()
//!     .register("ping", |_| async { Ok(json!("pong")) })
//!     .build();
//! srv.serve("/tmp/demo.sock").await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## With typed params helper
//!
//! ```
//! use simplejrpc::Request;
//! use serde::Deserialize;
//! use serde_json::json;
//!
//! #[derive(Deserialize)]
//! struct Add { a: i64, b: i64 }
//!
//! # async fn demo(req: Request) -> simplejrpc::Result<serde_json::Value> {
//! let p: Add = req.params()?;
//! Ok(json!(p.a + p.b))
//! # }
//! ```

use std::collections::HashMap;
use std::future::Future;
use std::path::Path;
use std::pin::Pin;
use std::sync::Arc;

use async_trait::async_trait;
use parking_lot::RwLock;
use serde_json::{json, Value};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{UnixListener, UnixStream};
use tracing::{debug, error, info};

use crate::codec::{encode_frame, FrameReader};
use crate::error::{Error, Result};
use crate::middleware::{Middleware, MiddlewareChain};
use crate::response::AppResponse;

/// Optional read API for [`Request`] wrappers (override helpers in app code).
///
/// ```
/// use simplejrpc::server::{Request, RequestView};
/// use serde_json::{json, Value};
///
/// struct Masked(Request);
/// impl RequestView for Masked {
///     fn method(&self) -> &str { self.0.method() }
///     fn params_raw(&self) -> &Value { self.0.params_raw() }
///     fn id(&self) -> &Value { self.0.id() }
///     fn extension(&self, key: &str) -> Option<&Value> { self.0.extension(key) }
///     fn param_str(&self, key: &str) -> Option<&str> {
///         if key == "secret" { Some("***") } else { self.params_raw().get(key)?.as_str() }
///     }
/// }
/// let m = Masked(Request::new("m", json!({"secret": "pw"}), json!(1)));
/// assert_eq!(RequestView::param_str(&m, "secret"), Some("***"));
/// ```
pub trait RequestView: Send + Sync {
    /// JSON-RPC method name.
    fn method(&self) -> &str;
    /// Raw `params` (`null` / object / array).
    fn params_raw(&self) -> &Value;
    /// Request id.
    fn id(&self) -> &Value;
    /// Per-request extension slot (middleware → handler).
    fn extension(&self, key: &str) -> Option<&Value>;

    /// Deserialize params into `T`.
    fn params<T: serde::de::DeserializeOwned>(&self) -> Result<T> {
        serde_json::from_value(self.params_raw().clone()).map_err(Error::from)
    }

    /// Object field as `i64`.
    fn param_i64(&self, key: &str) -> Option<i64> {
        self.params_raw().get(key)?.as_i64()
    }

    /// Object field as `&str`.
    fn param_str(&self, key: &str) -> Option<&str> {
        self.params_raw().get(key)?.as_str()
    }
}

/// Mutable request bits used by middleware.
pub trait RequestMut: RequestView {
    /// Set a request-local extension value.
    fn set_extension(&mut self, key: impl Into<String>, value: Value);
    /// Mutable params JSON.
    fn params_mut(&mut self) -> &mut Value;
    /// Mutable extension map.
    fn extensions_mut(&mut self) -> &mut HashMap<String, Value>;
}

/// Incoming RPC request (Go `gsock.Request`).
///
/// Also implements [`RequestView`] / [`RequestMut`] for app-side wrappers.
///
/// # Examples
///
/// ```
/// use simplejrpc::Request;
/// use serde_json::json;
///
/// let mut req = Request::new("add", json!({"a": 1, "b": 2}), json!(1));
/// assert_eq!(req.method(), "add");
/// assert_eq!(req.param_i64("a"), Some(1));
/// req.set_extension("lang", json!("en"));
/// assert_eq!(req.extension("lang"), Some(&json!("en")));
/// ```
#[derive(Debug, Clone)]
pub struct Request {
    method: String,
    params: Value,
    id: Value,
    extensions: HashMap<String, Value>,
}

impl Request {
    /// Create a request (primarily for tests / middleware).
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Request;
    /// use serde_json::json;
    /// let req = Request::new("ping", json!({}), json!(1));
    /// assert_eq!(req.id(), &json!(1));
    /// ```
    pub fn new(method: impl Into<String>, params: Value, id: Value) -> Self {
        Self::from_parts(method.into(), params, id, HashMap::new())
    }

    /// Build from raw parts (for custom wrappers that reassemble a request).
    ///
    /// # Examples
    ///
    /// ```
    /// use std::collections::HashMap;
    /// use simplejrpc::Request;
    /// use serde_json::json;
    ///
    /// let req = Request::from_parts("ping".into(), json!({}), json!(1), HashMap::new());
    /// assert_eq!(req.method(), "ping");
    /// ```
    pub fn from_parts(
        method: String,
        params: Value,
        id: Value,
        extensions: HashMap<String, Value>,
    ) -> Self {
        Self {
            method,
            params,
            id,
            extensions,
        }
    }

    /// Split into raw parts (pair with [`Self::from_parts`]).
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Request;
    /// use serde_json::json;
    ///
    /// let req = Request::new("m", json!({"a": 1}), json!(7));
    /// let (method, params, id, ext) = req.into_parts();
    /// assert_eq!(method, "m");
    /// assert_eq!(id, json!(7));
    /// assert!(ext.is_empty());
    /// let _ = params;
    /// ```
    pub fn into_parts(self) -> (String, Value, Value, HashMap<String, Value>) {
        (self.method, self.params, self.id, self.extensions)
    }

    /// JSON-RPC method name.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Request;
    /// use serde_json::json;
    /// assert_eq!(Request::new("x", json!({}), json!(1)).method(), "x");
    /// ```
    pub fn method(&self) -> &str {
        &self.method
    }

    /// Raw params value (`null`, object, or array).
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Request;
    /// use serde_json::json;
    /// let req = Request::new("echo", json!([1, 2]), json!(1));
    /// assert_eq!(req.params_raw(), &json!([1, 2]));
    /// ```
    pub fn params_raw(&self) -> &Value {
        &self.params
    }

    /// Deserialize params into `T`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Json`] when deserialization fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Request;
    /// use serde::Deserialize;
    /// use serde_json::json;
    ///
    /// #[derive(Deserialize)]
    /// struct Add { a: i64, b: i64 }
    ///
    /// let req = Request::new("add", json!({"a": 1, "b": 2}), json!(1));
    /// let p: Add = req.params().unwrap();
    /// assert_eq!(p.a + p.b, 3);
    /// ```
    pub fn params<T: serde::de::DeserializeOwned>(&self) -> Result<T> {
        serde_json::from_value(self.params.clone()).map_err(Error::from)
    }


    /// Read an object field as `i64`.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Request;
    /// use serde_json::json;
    /// let req = Request::new("m", json!({"n": 9}), json!(1));
    /// assert_eq!(req.param_i64("n"), Some(9));
    /// assert_eq!(req.param_i64("missing"), None);
    /// ```
    pub fn param_i64(&self, key: &str) -> Option<i64> {
        self.params.get(key)?.as_i64()
    }

    /// Read an object field as `&str`.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Request;
    /// use serde_json::json;
    /// let req = Request::new("m", json!({"s": "hi"}), json!(1));
    /// assert_eq!(req.param_str("s"), Some("hi"));
    /// ```
    pub fn param_str(&self, key: &str) -> Option<&str> {
        self.params.get(key)?.as_str()
    }

    /// JSON-RPC request id.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Request;
    /// use serde_json::json;
    /// assert_eq!(Request::new("m", json!({}), json!(7)).id(), &json!(7));
    /// ```
    pub fn id(&self) -> &Value {
        &self.id
    }

    /// Store a middleware / app extension value.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Request;
    /// use serde_json::json;
    /// let mut req = Request::new("m", json!({}), json!(1));
    /// req.set_extension("trace_id", json!("abc"));
    /// ```
    pub fn set_extension(&mut self, key: impl Into<String>, value: Value) {
        self.extensions.insert(key.into(), value);
    }

    /// Read an extension previously set by middleware or the handler.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Request;
    /// use serde_json::json;
    /// let mut req = Request::new("m", json!({}), json!(1));
    /// req.set_extension("k", json!(true));
    /// assert_eq!(req.extension("k"), Some(&json!(true)));
    /// ```
    pub fn extension(&self, key: &str) -> Option<&Value> {
        self.extensions.get(key)
    }

    /// Mutable access to raw params JSON.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Request;
    /// use serde_json::json;
    /// let mut req = Request::new("m", json!({"n": 1}), json!(1));
    /// *req.params_mut() = json!({"n": 2});
    /// assert_eq!(req.param_i64("n"), Some(2));
    /// ```
    pub fn params_mut(&mut self) -> &mut Value {
        &mut self.params
    }

    /// Mutable access to the extension map.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Request;
    /// use serde_json::json;
    /// let mut req = Request::new("m", json!({}), json!(1));
    /// req.extensions_mut().insert("k".into(), json!(1));
    /// assert_eq!(req.extension("k"), Some(&json!(1)));
    /// ```
    pub fn extensions_mut(&mut self) -> &mut HashMap<String, Value> {
        &mut self.extensions
    }
}

impl RequestView for Request {
    fn method(&self) -> &str {
        &self.method
    }

    fn params_raw(&self) -> &Value {
        &self.params
    }

    fn id(&self) -> &Value {
        &self.id
    }

    fn extension(&self, key: &str) -> Option<&Value> {
        self.extensions.get(key)
    }
}

impl RequestMut for Request {
    fn set_extension(&mut self, key: impl Into<String>, value: Value) {
        self.extensions.insert(key.into(), value);
    }

    fn params_mut(&mut self) -> &mut Value {
        &mut self.params
    }

    fn extensions_mut(&mut self) -> &mut HashMap<String, Value> {
        &mut self.extensions
    }
}

/// Async handler strategy trait for stateful services.
///
/// Prefer [`ServerBuilder::register`] for closures; implement this trait when
/// the handler needs shared state behind `Arc`.
///
/// The return value is the envelope **`data`** field only. The server wraps it
/// as [`AppResponse::ok`] (or maps [`Error`] via [`Error::to_app_response`]).
/// Do **not** return a full [`AppResponse`] from `handle`.
///
/// # Examples
///
/// ```
/// use async_trait::async_trait;
/// use simplejrpc::{Request, Result, RpcHandler};
/// use serde_json::{json, Value};
///
/// struct Ping;
///
/// #[async_trait]
/// impl RpcHandler for Ping {
///     async fn handle(&self, _req: Request) -> Result<Value> {
///         Ok(json!("pong"))
///     }
/// }
/// ```
#[async_trait]
pub trait RpcHandler: Send + Sync {
    /// Handle one request and return JSON-RPC envelope **`data`** (not [`AppResponse`]).
    ///
    /// # Errors
    ///
    /// Return [`Error::Biz`] / [`Error::Validation`] for client-visible failures.
    /// Internal variants are sanitized by [`Error::client_message`].
    async fn handle(&self, req: Request) -> Result<Value>;
}

/// Type-erased boxed future handler used by advanced integrations.
///
/// Signature: `Fn(Request) -> Pin<Box<dyn Future<Output = Result<Value>> + Send>>`.
/// Most applications should use [`ServerBuilder::register`] instead.
pub type HandlerFn =
    Arc<dyn Fn(Request) -> Pin<Box<dyn Future<Output = Result<Value>> + Send>> + Send + Sync>;

/// Adapts a typed async closure into [`RpcHandler`] for the builder registry.
struct ClosureHandler<F>(F);

#[async_trait]
impl<F, Fut> RpcHandler for ClosureHandler<F>
where
    F: Fn(Request) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<Value>> + Send + 'static,
{
    async fn handle(&self, req: Request) -> Result<Value> {
        (self.0)(req).await
    }
}

/// Server builder (Builder pattern).
///
/// Register methods, attach middleware, then [`Self::build`].
///
/// # Examples
///
/// ```
/// use simplejrpc::Server;
/// use serde_json::json;
///
/// let server = Server::builder()
///     .register("ping", |_| async { Ok(json!("pong")) })
///     .build();
/// let _ = server;
/// ```
#[derive(Default)]
pub struct ServerBuilder {
    handlers: HashMap<String, Arc<dyn RpcHandler>>,
    middlewares: MiddlewareChain,
}

impl ServerBuilder {
    /// Create an empty builder.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::ServerBuilder;
    /// let _ = ServerBuilder::new();
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Register an async closure as a method handler.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Server;
    /// use serde_json::json;
    ///
    /// let _ = Server::builder().register("echo", |req| async move {
    ///     Ok(req.params_raw().clone())
    /// });
    /// ```
    pub fn register<F, Fut>(mut self, method: impl Into<String>, f: F) -> Self
    where
        F: Fn(Request) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Value>> + Send + 'static,
    {
        self.handlers
            .insert(method.into(), Arc::new(ClosureHandler(f)));
        self
    }

    /// Register a trait-object handler (Strategy pattern).
    ///
    /// # Examples
    ///
    /// ```
    /// use async_trait::async_trait;
    /// use simplejrpc::{Request, Result, RpcHandler, Server};
    /// use serde_json::{json, Value};
    /// use std::sync::Arc;
    ///
    /// struct Ping;
    /// #[async_trait]
    /// impl RpcHandler for Ping {
    ///     async fn handle(&self, _: Request) -> Result<Value> { Ok(json!("pong")) }
    /// }
    ///
    /// let _ = Server::builder().register_handler("ping", Arc::new(Ping));
    /// ```
    pub fn register_handler(mut self, method: impl Into<String>, h: Arc<dyn RpcHandler>) -> Self {
        self.handlers.insert(method.into(), h);
        self
    }

    /// Attach middleware (onion model).
    ///
    /// # Examples
    ///
    /// ```
    /// use async_trait::async_trait;
    /// use simplejrpc::middleware::Middleware;
    /// use simplejrpc::Server;
    /// use std::sync::Arc;
    ///
    /// struct Nop;
    /// #[async_trait]
    /// impl Middleware for Nop {}
    ///
    /// let _ = Server::builder().with_middleware(Arc::new(Nop));
    /// ```
    pub fn with_middleware(mut self, mw: Arc<dyn Middleware>) -> Self {
        self.middlewares.push(mw);
        self
    }

    /// Build an immutable [`Server`].
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Server;
    /// let _ = Server::builder().build();
    /// ```
    pub fn build(self) -> Server {
        Server {
            handlers: RwLock::new(self.handlers),
            middlewares: self.middlewares,
        }
    }
}

/// JSON-RPC Unix server facade.
///
/// # Examples
///
/// ```no_run
/// use simplejrpc::Server;
/// use serde_json::json;
///
/// # async fn demo() -> simplejrpc::Result<()> {
/// let srv = Server::builder()
///     .register("ping", |_| async { Ok(json!("pong")) })
///     .build();
/// srv.serve("/tmp/demo.sock").await?;
/// # Ok(())
/// # }
/// ```
pub struct Server {
    handlers: RwLock<HashMap<String, Arc<dyn RpcHandler>>>,
    middlewares: MiddlewareChain,
}

impl Server {
    /// Start building a server.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::Server;
    /// let _ = Server::builder();
    /// ```
    pub fn builder() -> ServerBuilder {
        ServerBuilder::new()
    }

    /// Dynamically register (or replace) a handler on a running [`Server`].
    ///
    /// Prefer [`ServerBuilder::register`] / [`ServerBuilder::register_handler`] at
    /// build time. Use this for plugins / hot registration after [`ServerBuilder::build`].
    ///
    /// # Examples
    ///
    /// ```
    /// use async_trait::async_trait;
    /// use simplejrpc::{Request, Result, RpcHandler, Server};
    /// use serde_json::{json, Value};
    /// use std::sync::Arc;
    ///
    /// struct Ping;
    /// #[async_trait]
    /// impl RpcHandler for Ping {
    ///     async fn handle(&self, _: Request) -> Result<Value> { Ok(json!("pong")) }
    /// }
    ///
    /// let srv = Server::builder().build();
    /// srv.insert_handler("ping", Arc::new(Ping));
    /// ```
    pub fn insert_handler(&self, method: impl Into<String>, h: Arc<dyn RpcHandler>) {
        self.handlers.write().insert(method.into(), h);
    }

    /// Serve forever on `socket_path` (removes a stale socket file first).
    ///
    /// This future only completes on fatal accept errors (normally it runs
    /// until the process exits). Prefer [`Self::serve_with_shutdown`] in tests.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn demo() -> simplejrpc::Result<()> {
    /// use simplejrpc::Server;
    /// use serde_json::json;
    /// Server::builder()
    ///     .register("ping", |_| async { Ok(json!("pong")) })
    ///     .build()
    ///     .serve("/tmp/demo.sock")
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn serve(self, socket_path: impl AsRef<Path>) -> Result<()> {
        let path = socket_path.as_ref();
        let listener = bind_unix_listener(path).await?;
        info!(?path, "simplejrpc listening");

        let server = Arc::new(self);
        loop {
            let (stream, _) = listener.accept().await?;
            let srv = Arc::clone(&server);
            tokio::spawn(async move {
                if let Err(e) = srv.handle_connection(stream).await {
                    error!(error = %e, "connection closed with error");
                }
            });
        }
    }

    /// Serve until `shutdown` receives `true` (for integration tests).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn demo() -> simplejrpc::Result<()> {
    /// use simplejrpc::Server;
    /// use serde_json::json;
    /// let (tx, rx) = tokio::sync::watch::channel(false);
    /// let handle = tokio::spawn(async move {
    ///     Server::builder()
    ///         .register("ping", |_| async { Ok(json!("pong")) })
    ///         .build()
    ///         .serve_with_shutdown("/tmp/demo.sock", rx)
    ///         .await
    /// });
    /// let _ = tx.send(true);
    /// let _ = handle.await;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn serve_with_shutdown(
        self,
        socket_path: impl AsRef<Path>,
        mut shutdown: tokio::sync::watch::Receiver<bool>,
    ) -> Result<()> {
        let path = socket_path.as_ref();
        let listener = bind_unix_listener(path).await?;
        let server = Arc::new(self);

        loop {
            tokio::select! {
                _ = shutdown.changed() => {
                    if *shutdown.borrow() {
                        info!("shutdown signal");
                        break;
                    }
                }
                accepted = listener.accept() => {
                    let (stream, _) = accepted?;
                    spawn_connection(Arc::clone(&server), stream);
                }
            }
        }
        let _ = tokio::fs::remove_file(path).await;
        Ok(())
    }

    async fn handle_connection(self: Arc<Self>, mut stream: UnixStream) -> Result<()> {
        let mut reader = FrameReader::new();
        let mut buf = vec![0u8; 8192];

        loop {
            let n = stream.read(&mut buf).await?;
            if n == 0 {
                break;
            }
            reader.push(&buf[..n]);
            self.write_pending_responses(&mut reader, &mut stream)
                .await?;
        }
        Ok(())
    }

    async fn write_pending_responses(
        self: &Arc<Self>,
        reader: &mut FrameReader,
        stream: &mut UnixStream,
    ) -> Result<()> {
        while let Some(body) = reader.try_next()? {
            let response_body = self.dispatch_raw(&body).await?;
            stream.write_all(&encode_frame(&response_body)).await?;
        }
        Ok(())
    }

    async fn dispatch_raw(&self, body: &[u8]) -> Result<Vec<u8>> {
        let (id, method, mut request) = parse_incoming_rpc(body)?;
        debug!(%method, "dispatch");

        self.middlewares.run_request(&mut request).await;
        let app = self.invoke_method(&method, request).await;
        let app = self.finish_response(app, &method).await;
        encode_rpc_result(id, app)
    }

    async fn invoke_method(&self, method: &str, request: Request) -> AppResponse {
        // Clone under the lock, then drop the guard before `.await`
        // (parking_lot guards are not `Send`).
        let handler = self.handlers.read().get(method).cloned();
        match handler {
            None => AppResponse::error(404, "Not Found").with_endpoint(method),
            Some(h) => run_handler_catch_panic(method, h, request).await,
        }
    }

    async fn finish_response(&self, app: AppResponse, method: &str) -> AppResponse {
        match self.middlewares.run_response(app).await {
            Ok(a) => a,
            Err(e) => {
                error!(error = %e, method = %method, "response middleware failed");
                internal_app_error(method)
            }
        }
    }
}

fn parse_incoming_rpc(body: &[u8]) -> Result<(Value, String, Request)> {
    // Missing `id` / `params` default to JSON null; missing `method` becomes "".
    let req_val: Value = serde_json::from_slice(body)?;
    let id = req_val.get("id").cloned().unwrap_or(Value::Null);
    let method = req_val
        .get("method")
        .and_then(|m| m.as_str())
        .unwrap_or("")
        .to_string();
    let params = req_val.get("params").cloned().unwrap_or(Value::Null);
    let request = Request::new(method.clone(), params, id.clone());
    Ok((id, method, request))
}

/// Bind a Unix listener, removing a stale socket file at `path` if present.
async fn bind_unix_listener(path: &Path) -> Result<UnixListener> {
    if path.exists() {
        let _ = tokio::fs::remove_file(path).await;
    }
    Ok(UnixListener::bind(path)?)
}

/// Fire-and-forget accept path (errors on one connection do not stop the listener).
fn spawn_connection(server: Arc<Server>, stream: UnixStream) {
    tokio::spawn(async move {
        let _ = server.handle_connection(stream).await;
    });
}

async fn run_handler_catch_panic(
    method: &str,
    handler: Arc<dyn RpcHandler>,
    request: Request,
) -> AppResponse {
    // Catch panics so a bad handler cannot tear down the accept loop
    // or leak stack traces to clients.
    match tokio::task::spawn(async move { handler.handle(request).await }).await {
        Ok(Ok(data)) => AppResponse::ok(data).with_endpoint(method),
        Ok(Err(e)) => e.to_app_response(method),
        Err(join_err) => {
            error!(
                error = %join_err,
                method = %method,
                "rpc handler panicked (caught); details logged only"
            );
            internal_app_error(method)
        }
    }
}

/// Sanitized 5xx-style envelope for panics / middleware failures (never leaks internals).
fn internal_app_error(method: &str) -> AppResponse {
    AppResponse::error(
        crate::RpcCode::Internal.code(),
        crate::sanitize::CLIENT_INTERNAL_MSG,
    )
    .with_endpoint(method)
}

/// Always encode business outcome as JSON-RPC `result` (never JSON-RPC `error`).
fn encode_rpc_result(id: Value, app: AppResponse) -> Result<Vec<u8>> {
    let rpc = json!({
        "jsonrpc": "2.0",
        "id": id,
        "result": app,
    });
    Ok(serde_json::to_vec(&rpc)?)
}