server-less 0.5.0

Composable derive macros for common Rust patterns
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
//! Integration tests for the JSON-RPC over HTTP macro.

#![allow(dead_code)]
#![allow(unused_variables)]

use serde_json::json;
use server_less::{jsonrpc, server};

#[derive(Clone)]
struct Calculator;

#[jsonrpc]
impl Calculator {
    /// Add two numbers
    pub fn add(&self, a: i32, b: i32) -> i32 {
        a + b
    }

    /// Subtract two numbers
    pub fn subtract(&self, a: i32, b: i32) -> i32 {
        a - b
    }

    /// Multiply two numbers
    pub fn multiply(&self, a: i32, b: i32) -> i32 {
        a * b
    }

    /// Echo a message
    pub fn echo(&self, message: String) -> String {
        message
    }
}

#[test]
fn test_jsonrpc_methods_list() {
    let methods = Calculator::jsonrpc_methods();
    assert!(methods.contains(&"add".to_string()));
    assert!(methods.contains(&"subtract".to_string()));
    assert!(methods.contains(&"multiply".to_string()));
    assert!(methods.contains(&"echo".to_string()));
}

#[tokio::test]
async fn test_jsonrpc_handle_add() {
    let calc = Calculator;
    let request = json!({
        "jsonrpc": "2.0",
        "method": "add",
        "params": {"a": 5, "b": 3},
        "id": 1
    });

    let response = calc.jsonrpc_handle_async(request).await;

    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["result"], 8);
    assert_eq!(response["id"], 1);
}

#[tokio::test]
async fn test_jsonrpc_handle_subtract() {
    let calc = Calculator;
    let request = json!({
        "jsonrpc": "2.0",
        "method": "subtract",
        "params": {"a": 10, "b": 4},
        "id": 2
    });

    let response = calc.jsonrpc_handle_async(request).await;
    assert_eq!(response["result"], 6);
}

#[tokio::test]
async fn test_jsonrpc_handle_string_params() {
    let calc = Calculator;
    let request = json!({
        "jsonrpc": "2.0",
        "method": "echo",
        "params": {"message": "hello world"},
        "id": 3
    });

    let response = calc.jsonrpc_handle_async(request).await;
    assert_eq!(response["result"], "hello world");
}

#[tokio::test]
async fn test_jsonrpc_method_not_found() {
    let calc = Calculator;
    let request = json!({
        "jsonrpc": "2.0",
        "method": "nonexistent",
        "params": {},
        "id": 4
    });

    let response = calc.jsonrpc_handle_async(request).await;
    assert!(response["error"].is_object());
    assert!(
        response["error"]["message"]
            .as_str()
            .unwrap()
            .contains("not found")
    );
}

#[tokio::test]
async fn test_jsonrpc_invalid_version() {
    let calc = Calculator;
    let request = json!({
        "jsonrpc": "1.0",
        "method": "add",
        "params": {"a": 1, "b": 2},
        "id": 5
    });

    let response = calc.jsonrpc_handle_async(request).await;
    assert!(response["error"].is_object());
    assert_eq!(response["error"]["code"], -32600);
}

#[tokio::test]
async fn test_jsonrpc_notification_no_response() {
    let calc = Calculator;
    // Notification = no id field
    let request = json!({
        "jsonrpc": "2.0",
        "method": "add",
        "params": {"a": 1, "b": 2}
    });

    let response = calc.jsonrpc_handle_async(request).await;
    // Notifications return null (no response)
    assert!(response.is_null());
}

#[tokio::test]
async fn test_jsonrpc_batch_request() {
    let calc = Calculator;
    let request = json!([
        {"jsonrpc": "2.0", "method": "add", "params": {"a": 1, "b": 2}, "id": 1},
        {"jsonrpc": "2.0", "method": "multiply", "params": {"a": 3, "b": 4}, "id": 2}
    ]);

    let response = calc.jsonrpc_handle_async(request).await;

    assert!(response.is_array());
    let arr = response.as_array().unwrap();
    assert_eq!(arr.len(), 2);
    assert_eq!(arr[0]["result"], 3);
    assert_eq!(arr[1]["result"], 12);
}

#[tokio::test]
async fn test_jsonrpc_batch_with_notifications() {
    let calc = Calculator;
    let request = json!([
        {"jsonrpc": "2.0", "method": "add", "params": {"a": 1, "b": 2}, "id": 1},
        {"jsonrpc": "2.0", "method": "multiply", "params": {"a": 3, "b": 4}}  // notification
    ]);

    let response = calc.jsonrpc_handle_async(request).await;

    // Only the non-notification gets a response
    assert!(response.is_array());
    let arr = response.as_array().unwrap();
    assert_eq!(arr.len(), 1);
    assert_eq!(arr[0]["result"], 3);
}

// Test async methods
#[derive(Clone)]
struct AsyncService;

#[jsonrpc]
impl AsyncService {
    pub async fn async_echo(&self, message: String) -> String {
        // Simulate async work
        tokio::time::sleep(std::time::Duration::from_millis(1)).await;
        message
    }
}

#[tokio::test]
async fn test_jsonrpc_async_method() {
    let svc = AsyncService;
    let request = json!({
        "jsonrpc": "2.0",
        "method": "async_echo",
        "params": {"message": "async works"},
        "id": 1
    });

    let response = svc.jsonrpc_handle_async(request).await;
    assert_eq!(response["result"], "async works");
}

// Test custom path
#[derive(Clone)]
struct CustomPathService;

#[jsonrpc(path = "/api/v1/rpc")]
impl CustomPathService {
    pub fn ping(&self) -> String {
        "pong".to_string()
    }
}

#[test]
fn test_jsonrpc_custom_path_compiles() {
    // Just verify it compiles with custom path
    let methods = CustomPathService::jsonrpc_methods();
    assert!(methods.contains(&"ping".to_string()));
}

#[test]
fn test_jsonrpc_openapi_paths_generated() {
    let paths = Calculator::jsonrpc_openapi_paths();

    // Should have 1 path: POST /rpc
    assert_eq!(paths.len(), 1);

    let rpc_path = &paths[0];
    assert_eq!(rpc_path.path, "/rpc");
    assert_eq!(rpc_path.method, "post");
    assert!(
        rpc_path
            .operation
            .summary
            .as_ref()
            .unwrap()
            .contains("JSON-RPC")
    );
    assert!(rpc_path.operation.request_body.is_some());

    // Check that responses include 200 and 204
    assert!(rpc_path.operation.responses.contains_key("200"));
    assert!(rpc_path.operation.responses.contains_key("204"));
}

// ============================================================================
// Mount Point Tests
// ============================================================================

/// Child service for mount testing
#[derive(Clone)]
struct MathTools;

#[jsonrpc]
impl MathTools {
    /// Add two numbers
    fn add(&self, a: i32, b: i32) -> i32 {
        a + b
    }

    /// Double a number
    fn double(&self, n: i32) -> i32 {
        n * 2
    }
}

/// Another child service
#[derive(Clone)]
struct StringTools;

#[jsonrpc]
impl StringTools {
    /// Uppercase a string
    fn upper(&self, s: String) -> String {
        s.to_uppercase()
    }
}

/// Parent with static mounts
#[derive(Clone)]
struct JsonRpcApp {
    math: MathTools,
    strings: StringTools,
}

#[jsonrpc]
impl JsonRpcApp {
    /// Ping health check
    fn ping(&self) -> String {
        "pong".to_string()
    }

    /// Mount math tools
    fn math(&self) -> &MathTools {
        &self.math
    }

    /// Mount string tools
    fn strings(&self) -> &StringTools {
        &self.strings
    }
}

#[test]
fn test_jsonrpc_static_mount_methods_listed() {
    let methods = JsonRpcApp::jsonrpc_methods();

    // Leaf method
    assert!(methods.contains(&"ping".to_string()));
    // Mounted methods (dot-separated)
    assert!(methods.contains(&"math.add".to_string()));
    assert!(methods.contains(&"math.double".to_string()));
    assert!(methods.contains(&"strings.upper".to_string()));
}

#[tokio::test]
async fn test_jsonrpc_static_mount_dispatch() {
    let app = JsonRpcApp {
        math: MathTools,
        strings: StringTools,
    };

    // Dispatch to leaf
    let response = app
        .jsonrpc_handle_async(json!({
            "jsonrpc": "2.0",
            "method": "ping",
            "params": {},
            "id": 1
        }))
        .await;
    assert_eq!(response["result"], "pong");

    // Dispatch to mounted child
    let response = app
        .jsonrpc_handle_async(json!({
            "jsonrpc": "2.0",
            "method": "math.add",
            "params": {"a": 10, "b": 5},
            "id": 2
        }))
        .await;
    assert_eq!(response["result"], 15);

    // Dispatch to another mount
    let response = app
        .jsonrpc_handle_async(json!({
            "jsonrpc": "2.0",
            "method": "strings.upper",
            "params": {"s": "hello"},
            "id": 3
        }))
        .await;
    assert_eq!(response["result"], "HELLO");
}

#[tokio::test]
async fn test_jsonrpc_static_mount_double() {
    let app = JsonRpcApp {
        math: MathTools,
        strings: StringTools,
    };

    let response = app
        .jsonrpc_handle_async(json!({
            "jsonrpc": "2.0",
            "method": "math.double",
            "params": {"n": 21},
            "id": 1
        }))
        .await;
    assert_eq!(response["result"], 42);
}

/// Slug mount: parent with parameterized child
#[derive(Clone)]
struct JsonRpcSlugApp {
    math: MathTools,
}

#[jsonrpc]
impl JsonRpcSlugApp {
    /// Access a calculator by ID
    fn calc(&self, id: String) -> &MathTools {
        let _ = &id;
        &self.math
    }
}

#[test]
fn test_jsonrpc_slug_mount_methods_listed() {
    let methods = JsonRpcSlugApp::jsonrpc_methods();

    assert!(methods.contains(&"calc.add".to_string()));
    assert!(methods.contains(&"calc.double".to_string()));
}

#[tokio::test]
async fn test_jsonrpc_slug_mount_dispatch() {
    let app = JsonRpcSlugApp { math: MathTools };

    let response = app
        .jsonrpc_handle_async(json!({
            "jsonrpc": "2.0",
            "method": "calc.add",
            "params": {"id": "calc-1", "a": 3, "b": 4},
            "id": 1
        }))
        .await;
    assert_eq!(response["result"], 7);
}

/// JsonRpcMount trait test
#[test]
fn test_jsonrpc_mount_trait_implemented() {
    use server_less::JsonRpcMount;

    let methods = <MathTools as JsonRpcMount>::jsonrpc_mount_methods();
    assert_eq!(methods.len(), 2);
    assert!(methods.contains(&"add".to_string()));
    assert!(methods.contains(&"double".to_string()));
}

/// Test sync dispatch via JsonRpcMount::jsonrpc_mount_dispatch
#[test]
fn test_jsonrpc_mount_dispatch_sync() {
    use server_less::JsonRpcMount;

    let math = MathTools;

    // Sync dispatch of a sync method works
    let result = math.jsonrpc_mount_dispatch("add", json!({"a": 7, "b": 3}));
    assert!(result.is_ok(), "sync dispatch should succeed for sync method");
    let val = result.unwrap();
    assert_eq!(val, json!(10));

    // Sync dispatch of another method
    let result = math.jsonrpc_mount_dispatch("double", json!({"n": 6}));
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), json!(12));

    // Sync dispatch of a missing method returns Err
    let result = math.jsonrpc_mount_dispatch("nonexistent", json!({}));
    assert!(result.is_err(), "sync dispatch of unknown method should return Err");
}

/// Test that async-only methods return Err when dispatched synchronously
#[derive(Clone)]
struct AsyncOnlyService;

#[server_less::jsonrpc]
impl AsyncOnlyService {
    pub async fn only_async(&self, x: i32) -> i32 {
        x * 2
    }
    pub fn sync_method(&self, x: i32) -> i32 {
        x + 1
    }
}

#[test]
fn test_jsonrpc_mount_dispatch_sync_rejects_async() {
    use server_less::JsonRpcMount;

    let svc = AsyncOnlyService;

    // Sync method works
    let result = svc.jsonrpc_mount_dispatch("sync_method", json!({"x": 5}));
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), json!(6));

    // Async-only method returns Err in sync context
    let result = svc.jsonrpc_mount_dispatch("only_async", json!({"x": 5}));
    assert!(
        result.is_err(),
        "async method should return Err in sync dispatch context"
    );
    assert!(
        result.unwrap_err().contains("sync context"),
        "error message should mention sync context"
    );
}

/// Test ErrorCode::jsonrpc_code() mapping
#[test]
fn test_error_code_jsonrpc_code() {
    use server_less::ErrorCode;
    // Standard invalid params code
    assert_eq!(ErrorCode::InvalidInput.jsonrpc_code(), -32602);
    // Internal error fallback
    assert_eq!(ErrorCode::Internal.jsonrpc_code(), -32603);
    // Method not found code maps to NotImplemented
    assert_eq!(ErrorCode::NotImplemented.jsonrpc_code(), -32601);
}

/// Test that ServerlessError::jsonrpc_code() propagates to JSON-RPC response
#[derive(Debug, server_less::ServerlessError)]
enum RpcError {
    #[error(code = InvalidInput, jsonrpc_code = -32602)]
    BadParams,
    #[error(code = NotFound)]
    Missing,
}

#[derive(Clone)]
struct ErrorService;

#[server_less::jsonrpc]
impl ErrorService {
    fn get_item(&self, id: i32) -> Result<String, RpcError> {
        if id < 0 {
            Err(RpcError::BadParams)
        } else if id == 0 {
            Err(RpcError::Missing)
        } else {
            Ok(format!("item-{}", id))
        }
    }
}

#[tokio::test]
async fn test_jsonrpc_error_code_from_serverless_error() {
    let svc = ErrorService;

    // BadParams → jsonrpc_code -32602
    let response = svc
        .jsonrpc_handle_async(json!({
            "jsonrpc": "2.0",
            "method": "get_item",
            "params": {"id": -1},
            "id": 1
        }))
        .await;
    assert!(response["error"].is_object());
    assert_eq!(
        response["error"]["code"],
        -32602,
        "BadParams should produce JSON-RPC code -32602"
    );

    // Missing → jsonrpc_code derived from NotFound (-32002)
    let response = svc
        .jsonrpc_handle_async(json!({
            "jsonrpc": "2.0",
            "method": "get_item",
            "params": {"id": 0},
            "id": 2
        }))
        .await;
    assert!(response["error"].is_object());
    assert_eq!(
        response["error"]["code"],
        server_less::ErrorCode::NotFound.jsonrpc_code(),
        "Missing should produce the NotFound JSON-RPC code"
    );

    // Successful call
    let response = svc
        .jsonrpc_handle_async(json!({
            "jsonrpc": "2.0",
            "method": "get_item",
            "params": {"id": 42},
            "id": 3
        }))
        .await;
    assert_eq!(response["result"], "item-42");
}

// ============================================================================
// Iterator return type tests
// ============================================================================

#[derive(Clone)]
struct IteratorService;

#[jsonrpc]
impl IteratorService {
    /// Return numbers as an iterator — must serialize to a JSON array
    pub fn numbers(&self) -> impl Iterator<Item = i32> {
        vec![1, 2, 3].into_iter()
    }

    /// Return strings as an iterator
    pub fn words(&self) -> impl Iterator<Item = String> {
        vec!["hello".to_string(), "world".to_string()].into_iter()
    }
}

#[tokio::test]
async fn test_jsonrpc_iterator_serializes_to_array() {
    let svc = IteratorService;
    let request = json!({
        "jsonrpc": "2.0",
        "method": "numbers",
        "params": {},
        "id": 1
    });

    let response = svc.jsonrpc_handle_async(request).await;

    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["id"], 1);
    assert!(response["result"].is_array(), "iterator result must be a JSON array, got: {}", response);
    assert_eq!(response["result"], json!([1, 2, 3]));
}

#[tokio::test]
async fn test_jsonrpc_iterator_strings_serializes_to_array() {
    let svc = IteratorService;
    let request = json!({
        "jsonrpc": "2.0",
        "method": "words",
        "params": {},
        "id": 2
    });

    let response = svc.jsonrpc_handle_async(request).await;

    assert!(response["result"].is_array(), "iterator result must be a JSON array");
    assert_eq!(response["result"], json!(["hello", "world"]));
}

// ============================================================================
// Missing / Wrong-Type Parameter Tests
// ============================================================================

#[tokio::test]
async fn test_jsonrpc_missing_required_param_returns_32602() {
    let calc = Calculator;
    // Call `add` but omit `b` — should yield Invalid Params (-32602)
    let request = json!({
        "jsonrpc": "2.0",
        "method": "add",
        "params": {"a": 5},
        "id": 10
    });

    let response = calc.jsonrpc_handle_async(request).await;

    assert!(response["error"].is_object(), "expected an error object, got: {}", response);
    assert_eq!(
        response["error"]["code"],
        -32602,
        "missing required param must produce -32602, got: {}",
        response["error"]["code"]
    );
    assert!(
        response["error"]["message"]
            .as_str()
            .unwrap_or("")
            .to_lowercase()
            .contains("missing"),
        "error message should mention 'missing', got: {}",
        response["error"]["message"]
    );
}

#[tokio::test]
async fn test_jsonrpc_wrong_type_param_returns_32602() {
    let calc = Calculator;
    // `add` expects i32 for `a`; pass a string instead
    let request = json!({
        "jsonrpc": "2.0",
        "method": "add",
        "params": {"a": "not-a-number", "b": 3},
        "id": 11
    });

    let response = calc.jsonrpc_handle_async(request).await;

    assert!(response["error"].is_object(), "expected an error object, got: {}", response);
    assert_eq!(
        response["error"]["code"],
        -32602,
        "wrong-type param must produce -32602, got: {}",
        response["error"]["code"]
    );
}

// ============================================================================
// Optional Wrong-Type and Unknown Param Tests
// ============================================================================

/// Service with optional parameters for type-mismatch testing.
#[derive(Clone)]
struct OptionalParamService;

#[jsonrpc]
impl OptionalParamService {
    /// Search with required query and optional limit
    pub fn search(&self, query: String, limit: Option<u32>) -> String {
        format!("query={} limit={:?}", query, limit)
    }

    /// Method with no parameters (for unknown-param warning test)
    pub fn ping(&self) -> String {
        "pong".to_string()
    }
}

/// Optional parameter present with wrong type → -32602 (not silent None).
#[tokio::test]
async fn test_jsonrpc_optional_wrong_type_returns_32602() {
    let svc = OptionalParamService;
    // `limit` is Option<u32>; passing a string should produce -32602
    let request = json!({
        "jsonrpc": "2.0",
        "method": "search",
        "params": {"query": "hello", "limit": "not-a-number"},
        "id": 20
    });

    let response = svc.jsonrpc_handle_async(request).await;

    assert!(
        response["error"].is_object(),
        "optional param with wrong type must return an error, got: {}",
        response
    );
    assert_eq!(
        response["error"]["code"],
        -32602,
        "optional wrong-type must produce -32602, got: {}",
        response["error"]["code"]
    );
    assert!(
        response["error"]["message"]
            .as_str()
            .unwrap_or("")
            .to_lowercase()
            .contains("limit"),
        "error message should mention 'limit', got: {}",
        response["error"]["message"]
    );
}

/// Optional parameter absent → success (None), not an error.
#[tokio::test]
async fn test_jsonrpc_optional_absent_is_ok() {
    let svc = OptionalParamService;
    let request = json!({
        "jsonrpc": "2.0",
        "method": "search",
        "params": {"query": "hello"},
        "id": 21
    });

    let response = svc.jsonrpc_handle_async(request).await;
    assert!(response["error"].is_null(), "absent optional should succeed, got: {}", response);
    assert!(response["result"].is_string(), "should return a string result, got: {}", response);
}

/// Unknown parameter sent → call still succeeds (warning goes to stderr).
///
/// This test verifies the happy-path: unknown params don't break dispatch.
/// To observe the warning message run the tests with `-- --nocapture`.
#[tokio::test]
async fn test_jsonrpc_unknown_param_does_not_break_dispatch() {
    let svc = OptionalParamService;
    let request = json!({
        "jsonrpc": "2.0",
        "method": "ping",
        "params": {"unexpected_key": "value"},
        "id": 22
    });

    let response = svc.jsonrpc_handle_async(request).await;
    assert!(
        response["error"].is_null(),
        "unknown param should not cause an error, got: {}",
        response
    );
    assert_eq!(
        response["result"], "pong",
        "should still return the correct result"
    );
}

/// Unknown parameter with known params → call still succeeds.
#[tokio::test]
async fn test_jsonrpc_unknown_extra_param_does_not_break_dispatch() {
    let svc = OptionalParamService;
    let request = json!({
        "jsonrpc": "2.0",
        "method": "search",
        "params": {"query": "hello", "limit": 5, "typo_param": "oops"},
        "id": 23
    });

    let response = svc.jsonrpc_handle_async(request).await;
    assert!(
        response["error"].is_null(),
        "unknown extra param should not cause an error, got: {}",
        response
    );
    assert!(response["result"].is_string(), "should still return a result");
}

// ============================================================================
// Hidden Method Tests
// ============================================================================

#[derive(Clone)]
struct HiddenRpcService;

#[jsonrpc]
impl HiddenRpcService {
    /// Public method
    pub fn public_method(&self) -> String {
        "public".to_string()
    }

    /// Hidden method - callable but not listed
    #[server(hidden)]
    pub fn hidden_method(&self, value: i32) -> i32 {
        value * 2
    }
}

#[test]
fn test_jsonrpc_hidden_method_not_in_methods_list() {
    let methods = HiddenRpcService::jsonrpc_methods();
    // Public method appears in listing
    assert!(methods.contains(&"public_method".to_string()));
    // Hidden method does NOT appear in listing
    assert!(!methods.contains(&"hidden_method".to_string()));
}

#[tokio::test]
async fn test_jsonrpc_hidden_method_still_callable() {
    let svc = HiddenRpcService;
    // Hidden method must still dispatch even though it's absent from jsonrpc_methods()
    let request = json!({
        "jsonrpc": "2.0",
        "method": "hidden_method",
        "params": {"value": 21},
        "id": 1
    });
    let response = svc.jsonrpc_handle_async(request).await;
    assert_eq!(response["result"], json!(42));
}

#[test]
fn test_jsonrpc_hidden_method_absent_from_openapi_paths() {
    let paths = HiddenRpcService::jsonrpc_openapi_paths();
    // There is exactly one path (the JSON-RPC endpoint).
    assert_eq!(paths.len(), 1);
    // The method enum in the request body must not list the hidden method.
    let path = &paths[0];
    let body = path.operation.request_body.as_ref().unwrap();
    let body_str = body.to_string();
    assert!(body_str.contains("public_method"), "public_method must be in OpenRPC body");
    assert!(!body_str.contains("hidden_method"), "hidden_method must not be in OpenRPC body");
}