spikard-http 0.13.0

High-performance HTTP server for Spikard with tower-http middleware stack
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
//! gRPC runtime support for Spikard
//!
//! This module provides gRPC server infrastructure using Tonic, enabling
//! Spikard to handle both HTTP/1.1 REST requests and HTTP/2 gRPC requests.
//!
//! # Architecture
//!
//! The gRPC support follows the same language-agnostic pattern as the HTTP handler:
//!
//! 1. **GrpcHandler trait**: Language-agnostic interface for handling gRPC requests
//! 2. **Service bridge**: Converts between Tonic's types and our internal representation
//! 3. **Streaming support**: Utilities for handling streaming RPCs
//! 4. **Server integration**: Multiplexes HTTP/1.1 and HTTP/2 traffic
//!
//! # Example
//!
//! ```ignore
//! use spikard_http::grpc::{GrpcHandler, GrpcRequestData, GrpcResponseData};
//! use std::sync::Arc;
//!
//! // Implement GrpcHandler for your language binding
//! struct MyGrpcHandler;
//!
//! impl GrpcHandler for MyGrpcHandler {
//!     fn call(&self, request: GrpcRequestData) -> Pin<Box<dyn Future<Output = GrpcHandlerResult> + Send>> {
//!         Box::pin(async move {
//!             // Handle the gRPC request
//!             Ok(GrpcResponseData {
//!                 payload: bytes::Bytes::from("response"),
//!                 metadata: tonic::metadata::MetadataMap::new(),
//!             })
//!         })
//!     }
//!
//!     fn service_name(&self) -> &str {
//!         "mypackage.MyService"
//!     }
//! }
//!
//! // Register with the server
//! let handler = Arc::new(MyGrpcHandler);
//! let config = GrpcConfig::default();
//! ```

pub mod framing;
pub mod handler;
pub mod service;
pub mod streaming;

// Re-export main types
pub use framing::parse_grpc_client_stream;
pub use handler::{GrpcHandler, GrpcHandlerResult, GrpcRequestData, GrpcResponseData, RpcMode};
pub use service::{GenericGrpcService, copy_metadata, is_grpc_request, parse_grpc_path};
pub use streaming::{MessageStream, StreamingRequest, StreamingResponse};

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

/// Configuration for gRPC support
///
/// Controls how the server handles gRPC requests, including compression,
/// timeouts, and protocol settings.
///
/// # Stream Limits
///
/// This configuration enforces message-level size limits but delegates
/// concurrent stream limiting to the HTTP/2 transport layer:
///
/// - **Message Size Limits**: The `max_message_size` field is enforced per
///   individual message (request or response) in both unary and streaming RPCs.
///   When a single message exceeds this limit, the request is rejected with
///   `PAYLOAD_TOO_LARGE` (HTTP 413).
///
/// - **Concurrent Stream Limits**: The `max_concurrent_streams` is an advisory
///   configuration passed to the HTTP/2 layer for connection-level stream
///   negotiation. The HTTP/2 transport automatically enforces this limit and
///   returns GOAWAY frames when exceeded. Applications should not rely on
///   custom enforcement of this limit.
///
/// - **Stream Length Limits**: There is currently no built-in limit on the
///   total number of messages in a stream. Handlers should implement their own
///   message counting if needed. Future versions may add a `max_stream_response_bytes`
///   field to limit total response size per stream.
///
/// # Example
///
/// ```ignore
/// let mut config = GrpcConfig::default();
/// config.max_message_size = 10 * 1024 * 1024; // 10MB per message
/// config.max_concurrent_streams = 50; // Advised to HTTP/2 layer
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GrpcConfig {
    /// Enable gRPC support
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// Maximum message size in bytes (for both sending and receiving)
    ///
    /// This limit applies to individual messages in both unary and streaming RPCs.
    /// When a single message exceeds this size, the request is rejected with HTTP 413
    /// (Payload Too Large).
    ///
    /// Default: 4MB (4194304 bytes)
    ///
    /// # Note
    /// This limit does NOT apply to the total response size in streaming RPCs.
    /// For multi-message streams, the total response can exceed this limit as long
    /// as each individual message stays within the limit.
    #[serde(default = "default_max_message_size")]
    pub max_message_size: usize,

    /// Enable gzip compression for gRPC messages
    #[serde(default = "default_true")]
    pub enable_compression: bool,

    /// Timeout for gRPC requests in seconds (None = no timeout)
    #[serde(default)]
    pub request_timeout: Option<u64>,

    /// Maximum number of concurrent streams per connection (HTTP/2 advisory)
    ///
    /// This value is communicated to HTTP/2 clients as the server's flow control limit.
    /// The HTTP/2 transport layer enforces this limit automatically via SETTINGS frames
    /// and GOAWAY responses. Applications should NOT implement custom enforcement.
    ///
    /// Default: 100 streams per connection
    ///
    /// # Stream Limiting Strategy
    /// - **Per Connection**: This limit applies per HTTP/2 connection, not globally
    /// - **Transport Enforcement**: HTTP/2 handles all stream limiting; applications
    ///   need not implement custom checks
    /// - **Streaming Requests**: In server streaming or bidi streaming, each logical
    ///   RPC consumes one stream slot. Message ordering within a stream follows
    ///   HTTP/2 frame ordering.
    ///
    /// # Future Enhancement
    /// A future `max_stream_response_bytes` field may be added to limit the total
    /// response size in streaming RPCs (separate from per-message limits).
    #[serde(default = "default_max_concurrent_streams")]
    pub max_concurrent_streams: u32,

    /// Enable HTTP/2 keepalive
    #[serde(default = "default_true")]
    pub enable_keepalive: bool,

    /// HTTP/2 keepalive interval in seconds
    #[serde(default = "default_keepalive_interval")]
    pub keepalive_interval: u64,

    /// HTTP/2 keepalive timeout in seconds
    #[serde(default = "default_keepalive_timeout")]
    pub keepalive_timeout: u64,
    // Future extension point:
    // pub max_stream_response_bytes: Option<usize>,  // Total bytes per streaming response
}

impl Default for GrpcConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_message_size: default_max_message_size(),
            enable_compression: true,
            request_timeout: None,
            max_concurrent_streams: default_max_concurrent_streams(),
            enable_keepalive: true,
            keepalive_interval: default_keepalive_interval(),
            keepalive_timeout: default_keepalive_timeout(),
        }
    }
}

const fn default_true() -> bool {
    true
}

const fn default_max_message_size() -> usize {
    4 * 1024 * 1024 // 4MB
}

const fn default_max_concurrent_streams() -> u32 {
    100
}

const fn default_keepalive_interval() -> u64 {
    75 // seconds
}

const fn default_keepalive_timeout() -> u64 {
    20 // seconds
}

/// Registry for gRPC handlers
///
/// Maps service and method names to their handlers and RPC modes. Used by the
/// server to route incoming gRPC requests to the appropriate handler method based
/// on the parsed gRPC path.
///
/// # Example
///
/// ```ignore
/// use spikard_http::grpc::{GrpcRegistry, RpcMode};
/// use std::sync::Arc;
///
/// let mut registry = GrpcRegistry::new();
/// registry.register("mypackage.UserService", "GetUser", Arc::new(user_handler), RpcMode::Unary);
/// registry.register(
///     "mypackage.StreamService",
///     "StreamUsers",
///     Arc::new(stream_handler),
///     RpcMode::ServerStreaming,
/// );
/// ```
type GrpcHandlerEntry = (Arc<dyn GrpcHandler>, RpcMode);
const WILDCARD_METHOD: &str = "*";

#[derive(Clone)]
pub struct GrpcRegistry {
    handlers: Arc<HashMap<(String, String), GrpcHandlerEntry>>,
}

impl GrpcRegistry {
    /// Create a new empty gRPC handler registry
    pub fn new() -> Self {
        Self {
            handlers: Arc::new(HashMap::new()),
        }
    }

    /// Register a gRPC handler for a specific service method
    ///
    /// # Arguments
    ///
    /// * `service_name` - Fully qualified service name (e.g., "mypackage.MyService")
    /// * `method_name` - Method name (e.g., "GetUser")
    /// * `handler` - Handler implementation for this service
    /// * `rpc_mode` - The RPC mode this handler supports (Unary, ServerStreaming, etc.)
    pub fn register(
        &mut self,
        service_name: impl Into<String>,
        method_name: impl Into<String>,
        handler: Arc<dyn GrpcHandler>,
        rpc_mode: RpcMode,
    ) {
        let handlers = Arc::make_mut(&mut self.handlers);
        handlers.insert((service_name.into(), method_name.into()), (handler, rpc_mode));
    }

    /// Register a gRPC handler for an entire service.
    ///
    /// This is a service-level fallback for bindings that route methods inside a
    /// single handler object. Method-specific registrations take precedence over
    /// these wildcard entries during request dispatch.
    pub fn register_service(
        &mut self,
        service_name: impl Into<String>,
        handler: Arc<dyn GrpcHandler>,
        rpc_mode: RpcMode,
    ) {
        self.register(service_name, WILDCARD_METHOD, handler, rpc_mode);
    }

    /// Get a handler and its RPC mode by service and method name
    ///
    /// Returns both the handler and the RPC mode it was registered with. Exact
    /// method matches take precedence over service-level wildcard handlers.
    pub fn get(&self, service_name: &str, method_name: &str) -> Option<(Arc<dyn GrpcHandler>, RpcMode)> {
        self.handlers
            .get(&(service_name.to_owned(), method_name.to_owned()))
            .or_else(|| {
                self.handlers
                    .get(&(service_name.to_owned(), WILDCARD_METHOD.to_owned()))
            })
            .cloned()
    }

    /// Get all registered service names
    pub fn service_names(&self) -> Vec<String> {
        self.handlers
            .keys()
            .map(|(service_name, _)| service_name.clone())
            .collect::<HashSet<_>>()
            .into_iter()
            .collect()
    }

    /// Get all explicitly registered method names for a service.
    pub fn method_names(&self, service_name: &str) -> Vec<String> {
        self.handlers
            .keys()
            .filter(|(registered_service, method_name)| {
                registered_service == service_name && method_name.as_str() != WILDCARD_METHOD
            })
            .map(|(_, method_name)| method_name.clone())
            .collect()
    }

    /// Check if a specific service method is registered.
    pub fn contains(&self, service_name: &str, method_name: &str) -> bool {
        self.handlers
            .contains_key(&(service_name.to_owned(), method_name.to_owned()))
    }

    /// Check if a service has any registered handlers.
    pub fn contains_service(&self, service_name: &str) -> bool {
        self.handlers
            .keys()
            .any(|(registered_service, _)| registered_service == service_name)
    }

    /// Get the number of registered services
    pub fn len(&self) -> usize {
        self.handlers.len()
    }

    /// Check if the registry is empty
    pub fn is_empty(&self) -> bool {
        self.handlers.is_empty()
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::grpc::handler::{GrpcHandler, GrpcHandlerResult, GrpcRequestData};
    use std::future::Future;
    use std::pin::Pin;

    struct TestHandler;

    impl GrpcHandler for TestHandler {
        fn call(&self, _request: GrpcRequestData) -> Pin<Box<dyn Future<Output = GrpcHandlerResult> + Send>> {
            Box::pin(async {
                Ok(GrpcResponseData {
                    payload: bytes::Bytes::new(),
                    metadata: tonic::metadata::MetadataMap::new(),
                })
            })
        }

        fn service_name(&self) -> &'static str {
            // Since we can't return a reference to self.0 with 'static lifetime,
            // we need to use a workaround. In real usage, service names should be static.
            "test.Service"
        }
    }

    #[test]
    fn test_grpc_config_default() {
        let config = GrpcConfig::default();
        assert!(config.enabled);
        assert_eq!(config.max_message_size, 4 * 1024 * 1024);
        assert!(config.enable_compression);
        assert!(config.request_timeout.is_none());
        assert_eq!(config.max_concurrent_streams, 100);
        assert!(config.enable_keepalive);
        assert_eq!(config.keepalive_interval, 75);
        assert_eq!(config.keepalive_timeout, 20);
    }

    #[test]
    fn test_grpc_config_serialization() {
        let config = GrpcConfig::default();
        let json = serde_json::to_string(&config).unwrap();
        let deserialized: GrpcConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(config.enabled, deserialized.enabled);
        assert_eq!(config.max_message_size, deserialized.max_message_size);
        assert_eq!(config.enable_compression, deserialized.enable_compression);
    }

    #[test]
    fn test_grpc_registry_new() {
        let registry = GrpcRegistry::new();
        assert!(registry.is_empty());
        assert_eq!(registry.len(), 0);
    }

    #[test]
    fn test_grpc_registry_register() {
        let mut registry = GrpcRegistry::new();
        let handler = Arc::new(TestHandler);

        registry.register("test.Service", "TestMethod", handler, RpcMode::Unary);

        assert!(!registry.is_empty());
        assert_eq!(registry.len(), 1);
        assert!(registry.contains("test.Service", "TestMethod"));
    }

    #[test]
    fn test_grpc_registry_get() {
        let mut registry = GrpcRegistry::new();
        let handler = Arc::new(TestHandler);

        registry.register("test.Service", "TestMethod", handler, RpcMode::Unary);

        let retrieved = registry.get("test.Service", "TestMethod");
        assert!(retrieved.is_some());
        let (handler, rpc_mode) = retrieved.unwrap();
        assert_eq!(handler.service_name(), "test.Service");
        assert_eq!(rpc_mode, RpcMode::Unary);
    }

    #[test]
    fn test_grpc_registry_get_nonexistent() {
        let registry = GrpcRegistry::new();
        let result = registry.get("nonexistent.Service", "MissingMethod");
        assert!(result.is_none());
    }

    #[test]
    fn test_grpc_registry_service_names() {
        let mut registry = GrpcRegistry::new();

        registry.register("service1", "Method1", Arc::new(TestHandler), RpcMode::Unary);
        registry.register("service2", "Method2", Arc::new(TestHandler), RpcMode::ServerStreaming);
        registry.register("service3", "Method3", Arc::new(TestHandler), RpcMode::Unary);

        let mut names = registry.service_names();
        names.sort();

        assert_eq!(names, vec!["service1", "service2", "service3"]);
    }

    #[test]
    fn test_grpc_registry_contains() {
        let mut registry = GrpcRegistry::new();
        registry.register("test.Service", "TestMethod", Arc::new(TestHandler), RpcMode::Unary);

        assert!(registry.contains("test.Service", "TestMethod"));
        assert!(!registry.contains("other.Service", "TestMethod"));
    }

    #[test]
    fn test_grpc_registry_multiple_services() {
        let mut registry = GrpcRegistry::new();

        registry.register("user.Service", "GetUser", Arc::new(TestHandler), RpcMode::Unary);
        registry.register(
            "post.Service",
            "ListPosts",
            Arc::new(TestHandler),
            RpcMode::ServerStreaming,
        );

        assert_eq!(registry.len(), 2);
        assert!(registry.contains("user.Service", "GetUser"));
        assert!(registry.contains("post.Service", "ListPosts"));
    }

    #[test]
    fn test_grpc_registry_clone() {
        let mut registry = GrpcRegistry::new();
        registry.register("test.Service", "TestMethod", Arc::new(TestHandler), RpcMode::Unary);

        let cloned = registry.clone();

        assert_eq!(cloned.len(), 1);
        assert!(cloned.contains("test.Service", "TestMethod"));
    }

    #[test]
    fn test_grpc_registry_default() {
        let registry = GrpcRegistry::default();
        assert!(registry.is_empty());
    }

    #[test]
    fn test_grpc_registry_rpc_mode_storage() {
        let mut registry = GrpcRegistry::new();

        registry.register("unary.Service", "UnaryMethod", Arc::new(TestHandler), RpcMode::Unary);
        registry.register(
            "server_stream.Service",
            "StreamMethod",
            Arc::new(TestHandler),
            RpcMode::ServerStreaming,
        );
        registry.register(
            "client_stream.Service",
            "UploadMethod",
            Arc::new(TestHandler),
            RpcMode::ClientStreaming,
        );
        registry.register(
            "bidi.Service",
            "ChatMethod",
            Arc::new(TestHandler),
            RpcMode::BidirectionalStreaming,
        );

        let (_, mode) = registry.get("unary.Service", "UnaryMethod").unwrap();
        assert_eq!(mode, RpcMode::Unary);

        let (_, mode) = registry.get("server_stream.Service", "StreamMethod").unwrap();
        assert_eq!(mode, RpcMode::ServerStreaming);

        let (_, mode) = registry.get("client_stream.Service", "UploadMethod").unwrap();
        assert_eq!(mode, RpcMode::ClientStreaming);

        let (_, mode) = registry.get("bidi.Service", "ChatMethod").unwrap();
        assert_eq!(mode, RpcMode::BidirectionalStreaming);
    }

    #[test]
    fn test_grpc_registry_service_fallback() {
        let mut registry = GrpcRegistry::new();
        registry.register_service("test.Service", Arc::new(TestHandler), RpcMode::Unary);

        assert!(registry.contains_service("test.Service"));
        assert!(registry.get("test.Service", "AnyMethod").is_some());
        assert!(registry.method_names("test.Service").is_empty());
    }

    #[test]
    fn test_grpc_registry_prefers_method_specific_handler() {
        struct MethodSpecificHandler;

        impl GrpcHandler for MethodSpecificHandler {
            fn call(&self, _request: GrpcRequestData) -> Pin<Box<dyn Future<Output = GrpcHandlerResult> + Send>> {
                Box::pin(async {
                    Ok(GrpcResponseData {
                        payload: bytes::Bytes::from("method-specific"),
                        metadata: tonic::metadata::MetadataMap::new(),
                    })
                })
            }

            fn service_name(&self) -> &str {
                "test.Service"
            }
        }

        let mut registry = GrpcRegistry::new();
        registry.register_service("test.Service", Arc::new(TestHandler), RpcMode::Unary);
        registry.register(
            "test.Service",
            "GetThing",
            Arc::new(MethodSpecificHandler),
            RpcMode::ServerStreaming,
        );

        let (_, mode) = registry.get("test.Service", "GetThing").unwrap();
        assert_eq!(mode, RpcMode::ServerStreaming);
        let (_, fallback_mode) = registry.get("test.Service", "OtherThing").unwrap();
        assert_eq!(fallback_mode, RpcMode::Unary);
    }
}