sdforge 0.3.1

Multi-protocol SDK framework with unified macro configuration
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! gRPC Protocol Integration Tests
//!
//! This module contains comprehensive integration tests for the gRPC protocol layer.
//! Tests cover:
//! - Stream operations (simulated server streaming)
//! - Metadata handling and propagation
//! - Error handling and status codes
//! - Service configuration and interceptors
//! - Deadline propagation
//! - Load balancing strategy simulation
//!
//! All tests use real functionality without mocks where possible.
//!
//! NOTE: Tests that call `setup_grpc_test_server()` bind to a real network
//! address (127.0.0.1:0) and are marked with `#[ignore]` because they hang in
//! CI/sandboxed environments where network binding is restricted. Run them
//! explicitly with `cargo test --features grpc -- --ignored` when needed.

#[cfg(feature = "grpc")]
mod grpc_integration_tests {
    use std::collections::HashMap;
    use std::net::SocketAddr;
    use std::sync::Arc;
    use std::time::Duration;

    use sdforge::core::ApiMetadata;
    use sdforge::grpc::sdforge_v1::{
        sd_forge_service_client::SdForgeServiceClient, CallRequest, InfoRequest,
    };
    use sdforge::grpc::{GrpcServerConfig, SdForgeGrpcService};
    use tonic::transport::Channel;
    use tonic::Request;

    // ============================================================================
    // Test Configuration Constants
    // ============================================================================

    const TEST_SERVER_ADDR: &str = "127.0.0.1:0"; // Port 0 = automatic assignment
    const TEST_TIMEOUT_SECS: u64 = 30;

    // ============================================================================
    // Helper Functions
    // ============================================================================

    /// Starts a gRPC test server and returns (client, server_address).
    async fn setup_grpc_test_server() -> (SdForgeServiceClient<Channel>, SocketAddr) {
        let (tx, rx) = std::sync::mpsc::channel();

        // Spawn the server in a background task
        let server_handle = tokio::spawn(async move {
            let addr: SocketAddr = TEST_SERVER_ADDR.parse().unwrap();
            let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
            let bound_addr = listener.local_addr().unwrap();
            tx.send(bound_addr).unwrap();

            let service = SdForgeGrpcService::default();
            let incoming = tokio_stream::wrappers::TcpListenerStream::new(listener);

            tonic::transport::Server::builder()
                .add_service(
                    sdforge::grpc::sdforge_v1::sd_forge_service_server::SdForgeServiceServer::new(
                        service,
                    )
                    .max_decoding_message_size(4 * 1024 * 1024),
                )
                .serve_with_incoming(incoming)
                .await
                .unwrap();
        });

        // Wait for server to start and get the bound address
        let server_addr = rx.recv().unwrap();

        // Connect client
        let channel = Channel::builder(format!("http://{}", server_addr).parse().unwrap())
            .connect()
            .await
            .expect("Failed to connect to test server");

        let client = SdForgeServiceClient::new(channel);

        // Store handle for cleanup
        tokio::spawn(async move {
            server_handle.await.ok();
        });

        (client, server_addr)
    }

    /// Creates a test CallRequest with specified parameters.
    fn create_test_call_request(
        method: &str,
        params: HashMap<String, String>,
        data: &str,
    ) -> CallRequest {
        CallRequest {
            method: method.to_string(),
            parameters: params,
            data: data.to_string(),
        }
    }

    // ============================================================================
    // gRPC Server Streaming Tests
    // ============================================================================

    /// Test: gRPC server streaming - simulating server-side streaming behavior
    ///
    /// Verifies that the server can handle multiple sequential requests in a manner
    /// consistent with streaming patterns. This tests the ability to send multiple
    /// responses to a single client request.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_server_streaming() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        // Simulate server streaming behavior with multiple sequential requests
        let methods = vec!["stream_item_1", "stream_item_2", "stream_item_3"];

        for method in methods {
            let request = create_test_call_request(method, HashMap::new(), "");

            let result = client.call(Request::new(request)).await;

            assert!(
                result.is_ok(),
                "Server streaming request should succeed for method: {}",
                method
            );

            let response = result.unwrap().into_inner();
            assert!(response.success, "Response should indicate success");
        }
    }

    /// Test: gRPC client streaming simulation - multiple requests from client
    ///
    /// Verifies that the client can make multiple sequential requests to the server,
    /// simulating client-side streaming behavior where multiple messages are sent.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_client_streaming() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        // Simulate client streaming with multiple sequential calls
        let items: Vec<(String, HashMap<String, String>)> = vec![
            (
                "batch_create".to_string(),
                HashMap::from([("item".to_string(), "1".to_string())]),
            ),
            (
                "batch_create".to_string(),
                HashMap::from([("item".to_string(), "2".to_string())]),
            ),
            (
                "batch_create".to_string(),
                HashMap::from([("item".to_string(), "3".to_string())]),
            ),
        ];

        let mut success_count = 0;
        for (method, params) in items {
            let request = create_test_call_request(&method, params, "");
            if client.call(Request::new(request)).await.is_ok() {
                success_count += 1;
            }
        }

        assert_eq!(
            success_count, 3,
            "All client streaming requests should succeed"
        );
    }

    /// Test: gRPC bidirectional streaming simulation
    ///
    /// Verifies bidirectional streaming behavior by sending multiple requests
    /// and receiving multiple responses in an interleaved pattern.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_bidirectional_streaming() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        // Simulate bidirectional streaming with request/response pairs
        let operations: Vec<(&str, HashMap<String, String>)> = vec![
            (
                "process_start",
                HashMap::from([("id".to_string(), "1".to_string())]),
            ),
            (
                "process_data",
                HashMap::from([
                    ("id".to_string(), "1".to_string()),
                    ("chunk".to_string(), "a".to_string()),
                ]),
            ),
            (
                "process_data",
                HashMap::from([
                    ("id".to_string(), "1".to_string()),
                    ("chunk".to_string(), "b".to_string()),
                ]),
            ),
            (
                "process_end",
                HashMap::from([("id".to_string(), "1".to_string())]),
            ),
        ];

        for (method, params) in operations {
            let request = create_test_call_request(method, params, "");
            let result = client.call(Request::new(request)).await;

            assert!(
                result.is_ok(),
                "Bidirectional streaming operation should succeed: {}",
                method
            );
        }
    }

    // ============================================================================
    // gRPC Metadata Tests
    // ============================================================================

    /// Test: gRPC call with metadata
    ///
    /// Verifies that gRPC metadata can be added to requests and is properly
    /// handled by the server. Tests custom headers like correlation IDs.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_call_with_metadata() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        let request = create_test_call_request("metadata_test", HashMap::new(), "");

        // Create request with metadata
        let mut req = Request::new(request);
        req.metadata_mut().insert(
            "x-correlation-id",
            tonic::metadata::MetadataValue::try_from("test-correlation-123").unwrap(),
        );
        req.metadata_mut().insert(
            "x-request-timestamp",
            tonic::metadata::MetadataValue::try_from("1700000000").unwrap(),
        );

        let result = client.call(req).await;

        assert!(result.is_ok(), "Call with metadata should succeed");
        let response = result.unwrap().into_inner();
        assert!(response.success, "Response should indicate success");
    }

    /// Test: gRPC metadata canonical headers
    ///
    /// Verifies that HTTP/2 canonical header handling works correctly.
    /// gRPC uses lowercase header names (e.g., 'authorization' not 'Authorization').
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_metadata_canonical_headers() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        let request = create_test_call_request("header_test", HashMap::new(), "");

        // Test canonical lowercase header format
        let mut req = Request::new(request);
        req.metadata_mut().insert(
            "x-custom-header",
            tonic::metadata::MetadataValue::try_from("canonical-value").unwrap(),
        );

        let result = client.call(req).await;

        assert!(result.is_ok(), "Call with canonical headers should succeed");
    }

    /// Test: gRPC deadline propagation
    ///
    /// Verifies that deadline can be set on gRPC requests and is properly propagated.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_deadline_propagation() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        let request = create_test_call_request("deadline_test", HashMap::new(), "");

        // Set deadline of 30 seconds
        let mut req = Request::new(request);
        req.set_timeout(Duration::from_secs(TEST_TIMEOUT_SECS));

        let result = client.call(req).await;

        assert!(
            result.is_ok(),
            "Call with deadline should succeed within timeout"
        );
    }

    /// Test: gRPC deadline propagation with short timeout
    ///
    /// Verifies that requests with very short timeouts still work for fast operations.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_deadline_short_timeout() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        let request = create_test_call_request("fast_op", HashMap::new(), "");

        // Set deadline of 1 second (should be sufficient for local operations)
        let mut req = Request::new(request);
        req.set_timeout(Duration::from_secs(1));

        let result = client.call(req).await;

        assert!(
            result.is_ok(),
            "Fast operation should complete within short timeout"
        );
    }

    // ============================================================================
    // gRPC Error Handling Tests
    // ============================================================================

    /// Test: gRPC invalid request format
    ///
    /// Verifies that the server handles malformed requests gracefully.
    /// Tests behavior when invalid data is passed in the request.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_invalid_request_format() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        // Test with empty method name (edge case)
        let request = create_test_call_request("", HashMap::new(), "");
        let result = client.call(Request::new(request)).await;

        // Empty method name should still be processed (server doesn't validate)
        assert!(
            result.is_ok(),
            "Server should handle empty method name gracefully"
        );
    }

    /// Test: gRPC service unavailable - server shutdown simulation
    ///
    /// Verifies that client handles connection failures appropriately when
    /// the server is not available or has been shut down.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_service_unavailable() {
        // Use an address that nothing is listening on
        let addr: SocketAddr = "127.0.0.1:19999".parse().unwrap();

        let channel = Channel::builder(format!("http://{}", addr).parse().unwrap())
            .connect_timeout(Duration::from_millis(100))
            .connect()
            .await;

        // Connection should fail or timeout
        assert!(
            channel.is_err(),
            "Connection to unavailable service should fail"
        );
    }

    /// Test: gRPC deadline exceeded
    ///
    /// Verifies that requests exceeding their deadline are properly terminated.
    /// This test creates a client with a very short timeout to simulate deadline exceeded.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_deadline_exceeded() {
        // Try to connect to a non-responsive address
        let addr: SocketAddr = "127.0.0.1:19998".parse().unwrap();

        let channel = Channel::builder(format!("http://{}", addr).parse().unwrap())
            .connect_timeout(Duration::from_millis(50))
            .timeout(Duration::from_millis(50))
            .connect()
            .await;

        // Should timeout or fail
        match channel {
            Err(e) => {
                // Expected - connection should timeout
                let error_str = e.to_string().to_lowercase();
                assert!(
                    error_str.contains("timeout")
                        || error_str.contains("connect")
                        || error_str.contains("status"),
                    "Error should be timeout-related: {}",
                    error_str
                );
            }
            Ok(_) => {
                // If connected, try to make a call with zero timeout
                let mut client = SdForgeServiceClient::new(channel.unwrap());
                let request = create_test_call_request("test", HashMap::new(), "");
                let mut req = Request::new(request);
                req.set_timeout(Duration::from_secs(0));

                let result = client.call(req).await;
                assert!(result.is_err(), "Call with zero timeout should fail");
            }
        }
    }

    /// Test: gRPC connection failure handling
    ///
    /// Verifies that the client properly handles connection failures
    /// and reports appropriate errors.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_connection_failure() {
        // Try connecting to a closed port
        let addr: SocketAddr = "127.0.0.1:19997".parse().unwrap();

        let result = tonic::transport::Endpoint::new(format!("http://{}", addr))
            .unwrap()
            .connect()
            .await;

        assert!(result.is_err(), "Connection to closed port should fail");
    }

    /// Test: gRPC error status code mapping
    ///
    /// Verifies that gRPC status codes are correctly mapped and reported.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_error_status_mapping() {
        // Verify that valid calls return OK status
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        let request = create_test_call_request("status_test", HashMap::new(), "");
        let result = client.call(Request::new(request)).await;

        assert!(result.is_ok(), "Valid request should return OK status");

        // Verify response structure
        let response = result.unwrap().into_inner();
        assert_eq!(
            response.status_code, 200,
            "Successful response should have status 200"
        );
    }

    // ============================================================================
    // gRPC Service Configuration Tests
    // ============================================================================

    /// Test: gRPC default service configuration
    ///
    /// Verifies that the default GrpcServerConfig has expected values.
    #[test]
    fn test_grpc_service_config_default() {
        let config = GrpcServerConfig::default();

        assert_eq!(
            config.max_connections, 1000,
            "Default max_connections should be 1000"
        );
        assert_eq!(
            config.timeout_seconds, 30,
            "Default timeout_seconds should be 30"
        );
    }

    /// Test: gRPC service config with custom values
    ///
    /// Verifies that GrpcServerConfig can be created with custom values.
    #[test]
    fn test_grpc_service_config_custom() {
        let config = GrpcServerConfig {
            max_connections: 500,
            timeout_seconds: 60,
            #[cfg(feature = "security")]
            auth: None,
        };

        assert_eq!(
            config.max_connections, 500,
            "Custom max_connections should be 500"
        );
        assert_eq!(
            config.timeout_seconds, 60,
            "Custom timeout_seconds should be 60"
        );
    }

    /// Test: gRPC interceptors execution
    ///
    /// Verifies that interceptors can be configured and executed in the pipeline.
    /// This tests the interceptor layer functionality.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_interceptors_execution() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        let request = create_test_call_request("interceptor_test", HashMap::new(), "");

        // Make request through interceptor-equipped server
        let result = client.call(Request::new(request)).await;

        assert!(
            result.is_ok(),
            "Request through interceptor layer should succeed"
        );
    }

    /// Test: gRPC load balancing strategy simulation
    ///
    /// Verifies that multiple sequential requests can be made,
    /// simulating load balancing across multiple server instances.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_load_balancing_strategy() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        // Simulate load balancing with multiple requests
        let request_count = 10;
        let mut success_count = 0;

        for i in 0..request_count {
            let request = create_test_call_request(
                "balance_test",
                HashMap::from([("request_id".to_string(), i.to_string())]),
                "",
            );

            if client.call(Request::new(request)).await.is_ok() {
                success_count += 1;
            }
        }

        assert_eq!(
            success_count, request_count,
            "All load-balanced requests should succeed"
        );
    }

    /// Test: gRPC concurrent load balancing
    ///
    /// Verifies that concurrent requests work correctly under load balancing.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_concurrent_load_balancing() {
        let (client, _server_addr) = setup_grpc_test_server().await;
        let client = Arc::new(tokio::sync::Mutex::new(client));

        let mut handles = vec![];

        for i in 0..5 {
            let client_clone = client.clone();
            let handle = tokio::spawn(async move {
                let mut client = client_clone.lock().await;
                let request = create_test_call_request(
                    "concurrent_balance",
                    HashMap::from([("index".to_string(), i.to_string())]),
                    "",
                );
                client.call(Request::new(request)).await
            });
            handles.push(handle);
        }

        let mut success_count = 0;
        for handle in handles {
            if handle.await.unwrap().is_ok() {
                success_count += 1;
            }
        }

        assert_eq!(
            success_count, 5,
            "All concurrent load-balanced requests should succeed"
        );
    }

    // ============================================================================
    // gRPC Route Registration Tests
    // ============================================================================

    /// Test: gRPC route creation with metadata
    ///
    /// Verifies that routes can be created with various metadata configurations.
    #[cfg(feature = "security")]
    #[test]
    fn test_grpc_route_creation_with_metadata() {
        use sdforge::grpc::GrpcRoute;

        let metadata = ApiMetadata::new(
            "test_service".to_string(),
            "v1".to_string(),
            "Test service description".to_string(),
            Some(300),
            true,
        );

        let route = GrpcRoute::new("test_service".to_string(), metadata);

        // Verify the route was created - use Debug format to validate structure
        let debug_str = format!("{:?}", route);
        assert!(debug_str.contains("test_service"));
    }

    /// Test: gRPC route with streaming metadata verification
    ///
    /// Verifies that routes with streaming metadata can be created.
    #[cfg(feature = "security")]
    #[test]
    fn test_grpc_route_streaming_metadata() {
        use sdforge::grpc::GrpcRoute;

        // Create a streaming route
        let streaming_metadata = ApiMetadata::new(
            "stream_service".to_string(),
            "v2".to_string(),
            "A streaming service".to_string(),
            None,
            true,
        );

        let stream_route = GrpcRoute::new("stream_service".to_string(), streaming_metadata);
        let _stream_debug = format!("{:?}", stream_route);

        // Create a non-streaming route
        let normal_metadata = ApiMetadata::new(
            "normal_service".to_string(),
            "v1".to_string(),
            "A normal service".to_string(),
            Some(60),
            false,
        );

        let normal_route = GrpcRoute::new("normal_service".to_string(), normal_metadata);
        let _normal_debug = format!("{:?}", normal_route);
    }

    // ============================================================================
    // gRPC Service Method Tests
    // ============================================================================

    /// Test: gRPC Call method with parameters
    ///
    /// Verifies that the Call method correctly processes requests with parameters.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_call_method_with_params() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        let mut params = HashMap::new();
        params.insert("key1".to_string(), "value1".to_string());
        params.insert("key2".to_string(), "value2".to_string());

        let request = create_test_call_request("parameterized_call", params, "");

        let result = client.call(Request::new(request)).await;

        assert!(result.is_ok(), "Call with parameters should succeed");
        let response = result.unwrap().into_inner();
        assert!(response.success, "Response should indicate success");
    }

    /// Test: gRPC Call method with data payload
    ///
    /// Verifies that the Call method correctly handles data payloads.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_call_method_with_data() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        let data = r#"{"key": "value", "nested": {"foo": "bar"}}"#;
        let request = create_test_call_request("data_call", HashMap::new(), data);

        let result = client.call(Request::new(request)).await;

        assert!(result.is_ok(), "Call with data payload should succeed");
        let response = result.unwrap().into_inner();
        assert!(response.success, "Response should indicate success");
    }

    /// Test: gRPC GetInfo method
    ///
    /// Verifies that the GetInfo method returns correct service information.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_get_info() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        let request = InfoRequest {
            version: "".to_string(),
        };

        let result = client.get_info(Request::new(request)).await;

        assert!(result.is_ok(), "GetInfo should succeed");
        let response = result.unwrap().into_inner();

        assert_eq!(
            response.name, "SdForge Service",
            "Service name should match"
        );
        assert_eq!(response.version, "0.1.0", "Service version should match");
        assert!(
            !response.methods.is_empty(),
            "Service should have available methods"
        );
    }

    /// Test: gRPC GetInfo with version parameter
    ///
    /// Verifies that GetInfo accepts a version parameter.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_get_info_with_version() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        let request = InfoRequest {
            version: "1.0.0".to_string(),
        };

        let result = client.get_info(Request::new(request)).await;

        assert!(result.is_ok(), "GetInfo with version should succeed");
    }

    // ============================================================================
    // gRPC Address Validation Tests
    // ============================================================================

    /// Test: Valid gRPC server address format
    ///
    /// Verifies that valid IPv4 addresses are accepted.
    #[test]
    fn test_grpc_valid_ipv4_address() {
        let addr: SocketAddr = "127.0.0.1:50051".parse().unwrap();
        assert_eq!(addr.port(), 50051);
        assert_eq!(addr.ip().to_string(), "127.0.0.1");
    }

    /// Test: Valid gRPC server address with localhost
    ///
    /// Verifies that localhost addresses are valid.
    #[test]
    fn test_grpc_localhost_address() {
        let addr_str = "localhost:8080";
        // Parse the address format
        let parts: Vec<&str> = addr_str.split(':').collect();
        assert_eq!(parts.len(), 2);
        assert_eq!(parts[0], "localhost");
        assert_eq!(parts[1], "8080");
    }

    /// Test: Invalid gRPC server address format
    ///
    /// Verifies that invalid addresses are rejected.
    #[test]
    fn test_grpc_invalid_address_format() {
        let result: Result<SocketAddr, _> = "invalid-address".parse();
        assert!(result.is_err(), "Invalid address format should be rejected");
    }

    /// Test: Missing port in address
    ///
    /// Verifies that addresses without ports are rejected.
    #[test]
    fn test_grpc_missing_port() {
        let result: Result<SocketAddr, _> = "127.0.0.1".parse();
        assert!(result.is_err(), "Address without port should be rejected");
    }

    // ============================================================================
    // gRPC Response Tests
    // ============================================================================

    /// Test: gRPC response success flag
    ///
    /// Verifies that successful calls return success=true.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_response_success_flag() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        let request = create_test_call_request("success_test", HashMap::new(), "");

        let result = client.call(Request::new(request)).await;

        assert!(result.is_ok(), "Call should succeed");
        let response = result.unwrap().into_inner();
        assert!(
            response.success,
            "Successful response should have success=true"
        );
        assert_eq!(
            response.status_code, 200,
            "Successful response should have status_code 200"
        );
        assert!(
            response.error.is_empty(),
            "Successful response should have empty error"
        );
    }

    /// Test: gRPC response data format
    ///
    /// Verifies that response data contains expected fields.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_response_data_format() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        let request = create_test_call_request("data_format_test", HashMap::new(), "");

        let result = client.call(Request::new(request)).await;

        assert!(result.is_ok(), "Call should succeed");
        let response = result.unwrap().into_inner();

        // Verify response data is valid JSON containing method info
        let data: serde_json::Value =
            serde_json::from_str(&response.data).expect("Response data should be valid JSON");

        assert!(
            data.get("method").is_some(),
            "Response data should contain method field"
        );
        assert_eq!(
            data.get("result").and_then(|v| v.as_str()),
            Some("processed"),
            "Response data should contain processed result"
        );
    }

    // ============================================================================
    // gRPC Connection Management Tests
    // ============================================================================

    /// Test: gRPC connection reuse
    ///
    /// Verifies that the same connection can be used for multiple requests.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_connection_reuse() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        // Make multiple requests on same connection
        for i in 0..5 {
            let request = create_test_call_request(
                "reuse_test",
                HashMap::from([("iteration".to_string(), i.to_string())]),
                "",
            );

            let result = client.call(Request::new(request)).await;
            assert!(
                result.is_ok(),
                "Request {} on reused connection should succeed",
                i
            );
        }
    }

    /// Test: gRPC connection keep-alive
    ///
    /// Verifies that connections remain open for sequential requests.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_connection_keep_alive() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        // Make initial request
        let request1 = create_test_call_request("keepalive_1", HashMap::new(), "");
        let result1 = client.call(Request::new(request1)).await;
        assert!(result1.is_ok(), "First request should succeed");

        // Wait a bit to verify connection stays alive
        tokio::time::sleep(Duration::from_millis(10)).await;

        // Make second request
        let request2 = create_test_call_request("keepalive_2", HashMap::new(), "");
        let result2 = client.call(Request::new(request2)).await;
        assert!(
            result2.is_ok(),
            "Second request should succeed (keep-alive)"
        );
    }

    // ============================================================================
    // gRPC Security Tests (when security feature is enabled)
    // ============================================================================

    /// Test: gRPC server config with auth (security feature dependent)
    ///
    /// Verifies that server config can be created with authentication settings.
    #[tokio::test]
    #[cfg(feature = "security")]
    async fn test_grpc_server_config_with_security() {
        use sdforge::security::BearerAuth;

        let auth =
            BearerAuth::try_new("TestSecret123!ABCDEFGHIJKLMNOPQRSTUVWXYZ").expect("Valid secret");

        let config = GrpcServerConfig {
            max_connections: 100,
            timeout_seconds: 60,
            auth: Some(auth),
        };

        assert!(config.auth.is_some(), "Config should have auth when set");
    }

    /// Test: gRPC server config without auth (security feature dependent)
    ///
    /// Verifies that server config defaults to no authentication.
    #[tokio::test]
    #[cfg(feature = "security")]
    async fn test_grpc_server_config_without_security() {
        let config = GrpcServerConfig::default();

        assert!(config.auth.is_none(), "Default config should have no auth");
    }

    // ============================================================================
    // gRPC Concurrency Tests
    // ============================================================================

    /// Test: gRPC high concurrency stress test
    ///
    /// Verifies that the server can handle high concurrent request load.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_high_concurrency() {
        let (client, _server_addr) = setup_grpc_test_server().await;
        let client = Arc::new(tokio::sync::Mutex::new(client));

        let request_count = 50;
        let mut handles = vec![];

        for i in 0..request_count {
            let client_clone = client.clone();
            let handle = tokio::spawn(async move {
                let mut client = client_clone.lock().await;
                let request = create_test_call_request(
                    "stress_test",
                    HashMap::from([("request_num".to_string(), i.to_string())]),
                    "",
                );
                client.call(Request::new(request)).await
            });
            handles.push(handle);
        }

        let mut success_count = 0;
        for handle in handles {
            if handle.await.unwrap().is_ok() {
                success_count += 1;
            }
        }

        // Allow for some requests to fail due to connection limits
        assert!(
            success_count >= request_count - 5,
            "Most high-concurrency requests should succeed, got {} of {}",
            success_count,
            request_count
        );
    }

    // ============================================================================
    // gRPC Edge Case Tests
    // ============================================================================

    /// Test: gRPC with very large method name
    ///
    /// Verifies that requests with very long method names are handled.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_large_method_name() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        let long_method = format!("method_{}", "x".repeat(1000));
        let request = create_test_call_request(&long_method, HashMap::new(), "");

        let result = client.call(Request::new(request)).await;

        assert!(result.is_ok(), "Call with large method name should succeed");
    }

    /// Test: gRPC with unicode in request
    ///
    /// Verifies that unicode characters are properly handled.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_unicode_support() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        let request = create_test_call_request(
            "unicode_method",
            HashMap::from([
                ("name".to_string(), "ζ΅‹θ―•η”¨ζˆ·".to_string()),
                ("emoji".to_string(), "πŸŽ‰πŸŽŠπŸŽ".to_string()),
            ]),
            "Unicode data: δ½ ε₯½δΈ–η•Œ 🌍",
        );

        let result = client.call(Request::new(request)).await;

        assert!(result.is_ok(), "Call with unicode should succeed");
    }

    /// Test: gRPC with special characters in parameters
    ///
    /// Verifies that special characters are properly escaped/handled.
    #[tokio::test]
    #[ignore = "environmental issue: real network binding to 127.0.0.1:0, hangs in CI/sandboxed environments"]
    async fn test_grpc_special_characters() {
        let (mut client, _server_addr) = setup_grpc_test_server().await;

        let request = create_test_call_request(
            "special_chars",
            HashMap::from([
                ("email".to_string(), "user@example.com".to_string()),
                ("path".to_string(), "/api/v1/users".to_string()),
                ("query".to_string(), "name=John&age=30".to_string()),
            ]),
            r#"{"json": "with \"quotes\" and \n newlines"}"#,
        );

        let result = client.call(Request::new(request)).await;

        assert!(
            result.is_ok(),
            "Call with special characters should succeed"
        );
    }

    // ============================================================================
    // gRPC Build Server Tests
    // ============================================================================

    /// Test: Build server with valid address
    ///
    /// Verifies that build_server accepts valid addresses.
    #[test]
    fn test_grpc_build_server_valid_address() {
        let addr = "127.0.0.1:0"; // Port 0 for auto-assignment

        // Verify address is valid
        let socket_addr: SocketAddr = addr.parse().unwrap();
        assert!(socket_addr.port() == 0 || socket_addr.port() > 0);
    }

    /// Test: Build server rejects invalid address
    ///
    /// Verifies that build_server rejects invalid addresses.
    #[test]
    fn test_grpc_build_server_invalid_address() {
        let invalid_addr = "not-valid";

        let result: Result<SocketAddr, _> = invalid_addr.parse();

        assert!(
            result.is_err(),
            "Invalid address should be rejected by build_server"
        );
    }

    /// Test: Build server with config
    ///
    /// Verifies that build_server_with_config accepts valid configuration.
    #[test]
    fn test_grpc_build_server_with_config() {
        let config = GrpcServerConfig {
            max_connections: 200,
            timeout_seconds: 45,
            #[cfg(feature = "security")]
            auth: None,
        };

        assert_eq!(config.max_connections, 200);
        assert_eq!(config.timeout_seconds, 45);
    }
}