ash-rpc 4.1.4

A comprehensive JSON-RPC 2.0 implementation with multiple transport layers and advanced features
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
//! Builder patterns for JSON-RPC types.

use crate::types::{Error, Notification, Request, RequestId, Response};

/// Builder for JSON-RPC requests
pub struct RequestBuilder {
    method: String,
    params: Option<serde_json::Value>,
    id: Option<RequestId>,
    correlation_id: Option<String>,
}

impl RequestBuilder {
    /// Create a new request builder
    pub fn new(method: impl Into<String>) -> Self {
        Self {
            method: method.into(),
            params: None,
            id: None,
            correlation_id: Some(uuid::Uuid::new_v4().to_string()),
        }
    }

    /// Set request parameters
    #[must_use]
    pub fn params(mut self, params: serde_json::Value) -> Self {
        self.params = Some(params);
        self
    }

    /// Set request ID
    #[must_use]
    pub fn id(mut self, id: RequestId) -> Self {
        self.id = Some(id);
        self
    }

    /// Set correlation ID
    #[must_use]
    pub fn correlation_id(mut self, correlation_id: String) -> Self {
        self.correlation_id = Some(correlation_id);
        self
    }

    /// Build the request
    #[must_use]
    pub fn build(self) -> Request {
        Request {
            jsonrpc: "2.0".to_owned(),
            method: self.method,
            params: self.params,
            id: self.id,
            correlation_id: self.correlation_id,
        }
    }
}

/// Builder for JSON-RPC responses
pub struct ResponseBuilder {
    result: Option<serde_json::Value>,
    error: Option<Error>,
    id: Option<RequestId>,
    correlation_id: Option<String>,
}

impl ResponseBuilder {
    /// Create a new response builder
    #[must_use]
    pub fn new() -> Self {
        Self {
            result: None,
            error: None,
            id: None,
            correlation_id: None,
        }
    }

    /// Set successful result
    #[must_use]
    pub fn success(mut self, result: serde_json::Value) -> Self {
        self.result = Some(result);
        self
    }

    /// Set error
    #[must_use]
    pub fn error(mut self, error: Error) -> Self {
        self.error = Some(error);
        self
    }

    /// Set response ID
    #[must_use]
    pub fn id(mut self, id: Option<RequestId>) -> Self {
        self.id = id;
        self
    }
    /// Set correlation ID
    #[must_use]
    pub fn correlation_id(mut self, correlation_id: Option<String>) -> Self {
        self.correlation_id = correlation_id;
        self
    }
    /// Build the response
    #[must_use]
    pub fn build(self) -> Response {
        Response {
            jsonrpc: "2.0".to_owned(),
            result: self.result,
            error: self.error,
            id: self.id,
            correlation_id: self.correlation_id,
        }
    }
}

/// Builder for JSON-RPC notifications
pub struct NotificationBuilder {
    method: String,
    params: Option<serde_json::Value>,
}

impl NotificationBuilder {
    /// Create a new notification builder
    pub fn new(method: impl Into<String>) -> Self {
        Self {
            method: method.into(),
            params: None,
        }
    }

    /// Set notification parameters
    #[must_use]
    pub fn params(mut self, params: serde_json::Value) -> Self {
        self.params = Some(params);
        self
    }

    /// Build the notification
    #[must_use]
    pub fn build(self) -> Notification {
        Notification {
            jsonrpc: "2.0".to_owned(),
            method: self.method,
            params: self.params,
        }
    }
}

/// Builder for JSON-RPC errors
pub struct ErrorBuilder {
    code: i32,
    message: String,
    data: Option<serde_json::Value>,
}

impl ErrorBuilder {
    /// Create a new error builder
    pub fn new(code: i32, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            data: None,
        }
    }

    /// Add additional error data
    #[must_use]
    pub fn data(mut self, data: serde_json::Value) -> Self {
        self.data = Some(data);
        self
    }

    /// Build the error
    #[must_use]
    pub fn build(self) -> Error {
        Error {
            code: self.code,
            message: self.message,
            data: self.data,
        }
    }
}

impl Default for ResponseBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for security configuration with validation
#[cfg(any(feature = "tcp", feature = "tcp-stream", feature = "tcp-stream-tls"))]
pub struct SecurityConfigBuilder {
    max_connections: usize,
    max_request_size: usize,
    request_timeout: std::time::Duration,
    idle_timeout: std::time::Duration,
}

#[cfg(any(feature = "tcp", feature = "tcp-stream", feature = "tcp-stream-tls"))]
impl SecurityConfigBuilder {
    /// Create a new security config builder with secure defaults
    #[must_use]
    pub fn new() -> Self {
        Self {
            max_connections: 1000,
            max_request_size: 1024 * 1024, // 1 MB
            request_timeout: std::time::Duration::from_secs(30),
            idle_timeout: std::time::Duration::from_secs(300), // 5 minutes
        }
    }

    /// Set maximum concurrent connections
    ///
    /// # Arguments
    /// * `max` - Maximum number of connections (1-100000)
    ///
    /// # Panics
    /// Panics if max is 0 or greater than 100000
    #[must_use]
    pub fn max_connections(mut self, max: usize) -> Self {
        assert!(
            max > 0 && max <= 100_000,
            "max_connections must be between 1 and 100000"
        );
        self.max_connections = max;
        self
    }

    /// Set maximum request size in bytes
    ///
    /// # Arguments
    /// * `size` - Maximum size in bytes (1024 to 100MB)
    ///
    /// # Panics
    /// Panics if size is less than 1024 bytes or greater than 100MB
    #[must_use]
    pub fn max_request_size(mut self, size: usize) -> Self {
        assert!(
            (1024..=100 * 1024 * 1024).contains(&size),
            "max_request_size must be between 1KB and 100MB"
        );
        self.max_request_size = size;
        self
    }

    /// Set request timeout
    ///
    /// # Arguments
    /// * `timeout` - Timeout duration (1 second to 5 minutes)
    ///
    /// # Panics
    /// Panics if timeout is less than 1 second or greater than 5 minutes
    #[must_use]
    pub fn request_timeout(mut self, timeout: std::time::Duration) -> Self {
        assert!(
            (1..=300).contains(&timeout.as_secs()),
            "request_timeout must be between 1 second and 5 minutes"
        );
        self.request_timeout = timeout;
        self
    }

    /// Set idle connection timeout
    ///
    /// # Arguments
    /// * `timeout` - Timeout duration (10 seconds to 1 hour)
    ///
    /// # Panics
    /// Panics if timeout is less than 10 seconds or greater than 1 hour
    #[must_use]
    pub fn idle_timeout(mut self, timeout: std::time::Duration) -> Self {
        assert!(
            (10..=3600).contains(&timeout.as_secs()),
            "idle_timeout must be between 10 seconds and 1 hour"
        );
        self.idle_timeout = timeout;
        self
    }

    /// Build the security configuration with validation
    pub fn build(self) -> crate::transports::SecurityConfig {
        tracing::info!(
            max_connections = self.max_connections,
            max_request_size = self.max_request_size,
            request_timeout_secs = self.request_timeout.as_secs(),
            idle_timeout_secs = self.idle_timeout.as_secs(),
            "creating security configuration"
        );

        crate::transports::SecurityConfig {
            max_connections: self.max_connections,
            max_request_size: self.max_request_size,
            request_timeout: self.request_timeout,
            idle_timeout: self.idle_timeout,
        }
    }
}

#[cfg(any(feature = "tcp", feature = "tcp-stream", feature = "tcp-stream-tls"))]
impl Default for SecurityConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(all(
    test,
    any(feature = "tcp", feature = "tcp-stream", feature = "tcp-stream-tls")
))]
mod tests {
    use super::*;

    #[test]
    #[should_panic(expected = "max_connections must be between 1 and 100000")]
    fn test_max_connections_zero_panics() {
        SecurityConfigBuilder::new().max_connections(0).build();
    }

    #[test]
    fn test_valid_security_config() {
        let config = SecurityConfigBuilder::new()
            .max_connections(500)
            .max_request_size(2 * 1024 * 1024)
            .request_timeout(std::time::Duration::from_secs(60))
            .idle_timeout(std::time::Duration::from_secs(600))
            .build();

        assert_eq!(config.max_connections, 500);
        assert_eq!(config.max_request_size, 2 * 1024 * 1024);
    }

    // RequestBuilder tests
    #[test]
    fn test_request_builder_basic() {
        let request = RequestBuilder::new("test_method").build();
        assert_eq!(request.method, "test_method");
        assert_eq!(request.jsonrpc, "2.0");
        assert!(request.correlation_id.is_some());
    }

    #[test]
    fn test_request_builder_with_params() {
        let params = serde_json::json!({"key": "value"});
        let request = RequestBuilder::new("method").params(params.clone()).build();
        assert_eq!(request.params, Some(params));
    }

    #[test]
    fn test_request_builder_with_id() {
        let id = serde_json::json!(123);
        let request = RequestBuilder::new("method").id(id.clone()).build();
        assert_eq!(request.id, Some(id));
    }

    #[test]
    fn test_request_builder_with_correlation_id() {
        let correlation_id = "custom-correlation-id".to_string();
        let request = RequestBuilder::new("method")
            .correlation_id(correlation_id.clone())
            .build();
        assert_eq!(request.correlation_id, Some(correlation_id));
    }

    #[test]
    fn test_request_builder_complete() {
        let params = serde_json::json!([1, 2, 3]);
        let id = serde_json::json!(456);
        let correlation_id = "test-corr-id".to_string();

        let request = RequestBuilder::new("complete_method")
            .params(params.clone())
            .id(id.clone())
            .correlation_id(correlation_id.clone())
            .build();

        assert_eq!(request.method, "complete_method");
        assert_eq!(request.params, Some(params));
        assert_eq!(request.id, Some(id));
        assert_eq!(request.correlation_id, Some(correlation_id));
    }

    // ResponseBuilder tests
    #[test]
    fn test_response_builder_success() {
        let result = serde_json::json!({"status": "ok"});
        let id = serde_json::json!(1);

        let response = ResponseBuilder::new()
            .success(result.clone())
            .id(Some(id.clone()))
            .build();

        assert_eq!(response.result, Some(result));
        assert!(response.error.is_none());
        assert_eq!(response.id, Some(id));
    }

    #[test]
    fn test_response_builder_error() {
        let error =
            crate::ErrorBuilder::new(crate::error_codes::INVALID_REQUEST, "Invalid request")
                .build();
        let id = serde_json::json!(2);

        let response = ResponseBuilder::new()
            .error(error.clone())
            .id(Some(id.clone()))
            .build();

        assert!(response.result.is_none());
        assert_eq!(
            response.error.unwrap().code,
            crate::error_codes::INVALID_REQUEST
        );
        assert_eq!(response.id, Some(id));
    }

    #[test]
    fn test_response_builder_with_correlation_id_basic() {
        let correlation_id = "resp-corr-id".to_string();
        let response = ResponseBuilder::new()
            .success(serde_json::json!("ok"))
            .correlation_id(Some(correlation_id.clone()))
            .build();

        assert_eq!(response.correlation_id, Some(correlation_id));
    }

    #[test]
    fn test_response_builder_jsonrpc_version() {
        let response = ResponseBuilder::new()
            .success(serde_json::json!("test"))
            .build();
        assert_eq!(response.jsonrpc, "2.0");
    }

    // NotificationBuilder tests
    #[test]
    fn test_notification_builder_basic() {
        let notification = NotificationBuilder::new("event").build();
        assert_eq!(notification.method, "event");
        assert_eq!(notification.jsonrpc, "2.0");
        assert!(notification.params.is_none());
    }

    #[test]
    fn test_notification_builder_with_params() {
        let params = serde_json::json!({"event": "update"});
        let notification = NotificationBuilder::new("notify")
            .params(params.clone())
            .build();
        assert_eq!(notification.params, Some(params));
    }

    // ErrorBuilder tests
    #[test]
    fn test_error_builder_basic() {
        let error = ErrorBuilder::new(crate::error_codes::INVALID_REQUEST, "Test error").build();
        assert_eq!(error.code, crate::error_codes::INVALID_REQUEST);
        assert_eq!(error.message, "Test error");
        assert!(error.data.is_none());
    }

    #[test]
    fn test_error_builder_with_data() {
        let data = serde_json::json!({"detail": "more info"});
        let error = ErrorBuilder::new(crate::error_codes::INTERNAL_ERROR, "Error")
            .data(data.clone())
            .build();
        assert_eq!(error.data, Some(data));
    }

    #[test]
    fn test_error_builder_string_conversion() {
        let error = ErrorBuilder::new(
            crate::error_codes::INTERNAL_ERROR,
            String::from("Dynamic error"),
        )
        .build();
        assert_eq!(error.message, "Dynamic error");
    }

    // SecurityConfigBuilder validation tests
    #[test]
    #[should_panic(expected = "max_request_size must be between")]
    fn test_security_config_request_size_too_small() {
        SecurityConfigBuilder::new()
            .max_request_size(512) // Less than 1KB
            .build();
    }

    #[test]
    #[should_panic(expected = "max_request_size must be between")]
    fn test_security_config_request_size_too_large() {
        SecurityConfigBuilder::new()
            .max_request_size(200 * 1024 * 1024) // More than 100MB
            .build();
    }

    #[test]
    #[should_panic(expected = "max_connections must be between")]
    fn test_security_config_connections_too_large() {
        SecurityConfigBuilder::new()
            .max_connections(150_000)
            .build();
    }

    #[test]
    fn test_security_config_boundary_values() {
        // Test minimum valid values
        let config_min = SecurityConfigBuilder::new()
            .max_connections(1)
            .max_request_size(1024)
            .build();
        assert_eq!(config_min.max_connections, 1);
        assert_eq!(config_min.max_request_size, 1024);

        // Test maximum valid values
        let config_max = SecurityConfigBuilder::new()
            .max_connections(100_000)
            .max_request_size(100 * 1024 * 1024)
            .build();
        assert_eq!(config_max.max_connections, 100_000);
        assert_eq!(config_max.max_request_size, 100 * 1024 * 1024);
    }

    #[test]
    fn test_security_config_timeouts() {
        let request_timeout = std::time::Duration::from_secs(45);
        let idle_timeout = std::time::Duration::from_secs(900);

        let config = SecurityConfigBuilder::new()
            .request_timeout(request_timeout)
            .idle_timeout(idle_timeout)
            .build();

        assert_eq!(config.request_timeout, request_timeout);
        assert_eq!(config.idle_timeout, idle_timeout);
    }

    #[test]
    fn test_security_config_defaults() {
        let config = SecurityConfigBuilder::new().build();
        assert_eq!(config.max_connections, 1000);
        assert_eq!(config.max_request_size, 1024 * 1024);
        assert_eq!(config.request_timeout, std::time::Duration::from_secs(30));
        assert_eq!(config.idle_timeout, std::time::Duration::from_secs(300));
    }

    #[test]
    fn test_security_config_builder_default() {
        let builder = SecurityConfigBuilder::default();
        let config = builder.build();
        assert_eq!(config.max_connections, 1000);
    }

    #[test]
    #[should_panic(expected = "request_timeout must be between")]
    fn test_security_config_timeout_too_short() {
        SecurityConfigBuilder::new()
            .request_timeout(std::time::Duration::from_millis(500))
            .build();
    }

    #[test]
    #[should_panic(expected = "request_timeout must be between")]
    fn test_security_config_timeout_too_long() {
        SecurityConfigBuilder::new()
            .request_timeout(std::time::Duration::from_secs(400))
            .build();
    }

    #[test]
    #[should_panic(expected = "idle_timeout must be between")]
    fn test_security_config_idle_timeout_too_short() {
        SecurityConfigBuilder::new()
            .idle_timeout(std::time::Duration::from_secs(5))
            .build();
    }

    #[test]
    #[should_panic(expected = "idle_timeout must be between")]
    fn test_security_config_idle_timeout_too_long() {
        SecurityConfigBuilder::new()
            .idle_timeout(std::time::Duration::from_secs(4000))
            .build();
    }

    #[test]
    fn test_request_builder_method_set() {
        let request = RequestBuilder::new("test_method").build();
        assert_eq!(request.method, "test_method");
    }

    #[test]
    fn test_request_builder_auto_correlation_id() {
        let request = RequestBuilder::new("test").build();
        assert!(request.correlation_id.is_some());
    }

    #[test]
    fn test_request_builder_custom_correlation_id() {
        let custom_id = "custom-correlation-123".to_string();
        let request = RequestBuilder::new("test")
            .correlation_id(custom_id.clone())
            .build();
        assert_eq!(request.correlation_id, Some(custom_id));
    }

    #[test]
    fn test_request_builder_full_chain() {
        let request = RequestBuilder::new("full_test")
            .params(serde_json::json!({"key": "value"}))
            .id(serde_json::json!(123))
            .correlation_id("corr-123".to_string())
            .build();

        assert_eq!(request.method, "full_test");
        assert!(request.params.is_some());
        assert_eq!(request.id, Some(serde_json::json!(123)));
        assert_eq!(request.correlation_id, Some("corr-123".to_string()));
    }

    #[test]
    fn test_response_builder_default_trait() {
        let builder = ResponseBuilder::default();
        let response = builder.build();
        assert_eq!(response.jsonrpc, "2.0");
    }

    #[test]
    fn test_response_builder_success_with_null() {
        let response = ResponseBuilder::new()
            .success(serde_json::json!(null))
            .build();
        assert_eq!(response.result, Some(serde_json::json!(null)));
    }

    #[test]
    fn test_response_builder_with_correlation_id() {
        let corr_id = "test-correlation".to_string();
        let response = ResponseBuilder::new()
            .success(serde_json::json!(42))
            .correlation_id(Some(corr_id.clone()))
            .build();
        assert_eq!(response.correlation_id, Some(corr_id));
    }

    #[test]
    fn test_response_builder_full_error() {
        let error = ErrorBuilder::new(crate::error_codes::INTERNAL_ERROR, "Custom error")
            .data(serde_json::json!({"field": "value"}))
            .build();

        let response = ResponseBuilder::new()
            .error(error.clone())
            .id(Some(serde_json::json!(1)))
            .correlation_id(Some("err-corr".to_string()))
            .build();

        assert!(response.result.is_none());
        assert_eq!(response.error, Some(error));
        assert_eq!(response.id, Some(serde_json::json!(1)));
        assert_eq!(response.correlation_id, Some("err-corr".to_string()));
    }

    #[test]
    fn test_notification_builder_string_method() {
        let notification = NotificationBuilder::new(String::from("dynamic_method")).build();
        assert_eq!(notification.method, "dynamic_method");
    }

    #[test]
    fn test_error_builder_multiple_data() {
        let error = ErrorBuilder::new(crate::error_codes::INTERNAL_ERROR, "Error")
            .data(serde_json::json!({"key1": "value1"}))
            .build();

        assert!(error.data.is_some());
        let data = error.data.unwrap();
        assert_eq!(data["key1"], "value1");
    }
}

/// Builder for streaming response
#[cfg(feature = "streaming")]
pub struct StreamResponseBuilder {
    result: Option<serde_json::Value>,
    error: Option<Error>,
    id: RequestId,
    stream_id: String,
    stream_status: Option<crate::streaming::StreamStatus>,
}

#[cfg(feature = "streaming")]
impl StreamResponseBuilder {
    /// Create a new stream response builder
    pub fn new(stream_id: impl Into<String>, id: RequestId) -> Self {
        Self {
            result: None,
            error: None,
            id,
            stream_id: stream_id.into(),
            stream_status: None,
        }
    }

    /// Set successful result
    #[must_use]
    pub fn success(mut self, result: serde_json::Value) -> Self {
        self.result = Some(result);
        self.stream_status = Some(crate::streaming::StreamStatus::Active);
        self
    }

    /// Set error
    #[must_use]
    pub fn error(mut self, error: Error) -> Self {
        self.error = Some(error);
        self.stream_status = Some(crate::streaming::StreamStatus::Error);
        self
    }

    /// Set stream status
    #[must_use]
    pub fn status(mut self, status: crate::streaming::StreamStatus) -> Self {
        self.stream_status = Some(status);
        self
    }

    /// Build the stream response
    #[must_use]
    pub fn build(self) -> crate::streaming::StreamResponse {
        crate::streaming::StreamResponse {
            jsonrpc: "2.0".to_owned(),
            result: self.result,
            error: self.error,
            id: self.id,
            stream_id: self.stream_id,
            stream_status: self.stream_status,
        }
    }
}