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
//! JSON-RPC HTTP handler for processing JSON-RPC requests over HTTP
//!
//! This module provides the HTTP endpoint handler that accepts JSON-RPC requests
//! and routes them through the JSON-RPC router. It handles single and batch requests,
//! validates content-type headers, and returns properly formatted JSON-RPC responses.
//!
//! # Request Processing
//!
//! The handler:
//! 1. Validates that the Content-Type header is `application/json`
//! 2. Parses the request body as JSON-RPC 2.0 (single or batch)
//! 3. Routes requests through the JsonRpcRouter
//! 4. Returns HTTP 200 with JSON-RPC responses
//! 5. Returns appropriate HTTP error codes for non-JSON-RPC errors
//!
//! # Response Codes
//!
//! - HTTP 200: Valid JSON-RPC request (even if the response contains an error)
//! - HTTP 400: Parse error or invalid request format
//! - HTTP 415: Invalid Content-Type header
//!
//! # Example
//!
//! ```ignore
//! use axum::{
//!     routing::post,
//!     Router,
//! };
//! use std::sync::Arc;
//! use spikard_http::jsonrpc::{JsonRpcRouter, JsonRpcMethodRegistry};
//!
//! let registry = Arc::new(JsonRpcMethodRegistry::new());
//! let router = Arc::new(JsonRpcRouter::new(registry, true, 100));
//! let state = Arc::new(JsonRpcState { router });
//!
//! let app = Router::new()
//!     .route("/rpc", post(handle_jsonrpc))
//!     .with_state(state);
//! ```

use super::router::{JsonRpcRequestOrBatch, JsonRpcRouter};
use crate::handler_trait::RequestData;
use crate::server::request_extraction::extract_headers;
use axum::{
    body::Body,
    extract::State,
    http::{HeaderMap, Request, StatusCode, header},
    response::{IntoResponse, Response as AxumResponse},
};
use std::collections::HashMap;
use std::sync::Arc;

/// State passed to the JSON-RPC HTTP handler
///
/// Contains the shared JSON-RPC router instance that dispatches requests
/// to registered method handlers.
#[derive(Clone)]
pub struct JsonRpcState {
    /// The JSON-RPC router for handling requests
    pub router: Arc<JsonRpcRouter>,
}

/// Main JSON-RPC HTTP handler
///
/// Accepts POST requests with JSON-RPC 2.0 payloads (single or batch).
/// Always returns HTTP 200 for valid JSON-RPC requests, with JSON-RPC error
/// codes in the response body if the method invocation failed.
///
/// # Arguments
///
/// * `state` - The application state containing the JSON-RPC router
/// * `headers` - HTTP request headers (used for Content-Type validation)
/// * `uri` - HTTP request URI (used for extracting path and query params)
/// * `body` - The raw request body as a string
///
/// # Returns
///
/// An Axum response with:
/// - HTTP 200 and JSON-RPC response for valid JSON-RPC requests
/// - HTTP 415 if Content-Type is not application/json
/// - HTTP 400 if the request body cannot be parsed as JSON-RPC
///
/// # Example
///
/// Valid single request:
/// ```text
/// POST /rpc HTTP/1.1
/// Content-Type: application/json
///
/// {"jsonrpc":"2.0","method":"add","params":[1,2],"id":1}
/// ```
///
/// Valid batch request:
/// ```text
/// POST /rpc HTTP/1.1
/// Content-Type: application/json
///
/// [{"jsonrpc":"2.0","method":"add","params":[1,2],"id":1},
///  {"jsonrpc":"2.0","method":"multiply","params":[3,4],"id":2}]
/// ```
pub async fn handle_jsonrpc(
    State(state): State<Arc<JsonRpcState>>,
    headers: HeaderMap,
    uri: axum::http::Uri,
    body: String,
) -> AxumResponse {
    if !validate_content_type(&headers) {
        return create_error_response(
            StatusCode::UNSUPPORTED_MEDIA_TYPE,
            "Content-Type must be application/json",
        );
    }

    let request = match JsonRpcRouter::parse_request(&body) {
        Ok(req) => req,
        Err(error_response) => {
            let json = serde_json::to_string(&error_response).expect("Error serialization should never fail");
            return create_jsonrpc_response(json);
        }
    };

    let request_data = create_jsonrpc_request_data(&headers, &uri);

    let http_request = Request::builder()
        .method("POST")
        .uri(uri.clone())
        .body(Body::empty())
        .unwrap_or_else(|_| Request::builder().method("POST").uri("/").body(Body::empty()).unwrap());

    let response = match request {
        JsonRpcRequestOrBatch::Single(req) => {
            let response = state.router.route_single(req, http_request, &request_data).await;
            serde_json::to_string(&response).expect("Response serialization should never fail")
        }
        JsonRpcRequestOrBatch::Batch(batch) => {
            let http_request = Request::builder()
                .method("POST")
                .uri(uri.clone())
                .body(Body::empty())
                .unwrap_or_else(|_| Request::builder().method("POST").uri("/").body(Body::empty()).unwrap());
            match state.router.route_batch(batch, http_request, &request_data).await {
                Ok(responses) => {
                    serde_json::to_string(&responses).expect("Batch response serialization should never fail")
                }
                Err(error_response) => {
                    serde_json::to_string(&error_response).expect("Error serialization should never fail")
                }
            }
        }
    };

    create_jsonrpc_response(response)
}

/// Helper function to create RequestData from JSON-RPC HTTP context
///
/// Creates a minimal RequestData with headers and path info extracted from the HTTP request.
/// Query parameters are extracted from the URI.
fn create_jsonrpc_request_data(headers: &HeaderMap, uri: &axum::http::Uri) -> RequestData {
    RequestData {
        path_params: Arc::new(HashMap::new()),
        query_params: Arc::new(serde_json::json!({})),
        validated_params: None,
        raw_query_params: Arc::new(HashMap::new()),
        body: Arc::new(serde_json::json!({})),
        raw_body: None,
        headers: Arc::new(extract_headers(headers)),
        cookies: Arc::new(HashMap::new()),
        method: "POST".to_string(),
        path: uri.path().to_string(),
        #[cfg(feature = "di")]
        dependencies: None,
    }
}

/// Validates that the Content-Type header is application/json
///
/// Performs case-insensitive matching per HTTP specification.
///
/// # Arguments
///
/// * `headers` - The HTTP headers to validate
///
/// # Returns
///
/// `true` if Content-Type is application/json or absent (defaults to JSON),
/// `false` if Content-Type is present but not JSON
fn validate_content_type(headers: &HeaderMap) -> bool {
    match headers.get(header::CONTENT_TYPE) {
        None => true,
        Some(value) => {
            if let Ok(ct) = value.to_str() {
                ct.to_lowercase().contains("application/json")
            } else {
                false
            }
        }
    }
}

/// Creates a JSON-RPC response with proper HTTP headers
///
/// Returns HTTP 200 OK with Content-Type: application/json
///
/// # Arguments
///
/// * `json` - The JSON response body as a string
///
/// # Returns
///
/// An Axum response ready to send to the client
fn create_jsonrpc_response(json: String) -> AxumResponse {
    (StatusCode::OK, [(header::CONTENT_TYPE, "application/json")], json).into_response()
}

/// Creates a generic error response for HTTP-level errors
///
/// Returns an appropriate HTTP status code with plain text error message.
/// Used for Content-Type validation failures and other HTTP-level errors.
///
/// # Arguments
///
/// * `status` - The HTTP status code
/// * `message` - The error message as plain text
///
/// # Returns
///
/// An Axum response ready to send to the client
fn create_error_response(status: StatusCode, message: &str) -> AxumResponse {
    (
        status,
        [(header::CONTENT_TYPE, "text/plain; charset=utf-8")],
        message.to_string(),
    )
        .into_response()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::jsonrpc::{method_registry::JsonRpcMethodRegistry, router::JsonRpcRouter};
    use serde_json::json;

    /// Helper to create a test state
    fn create_test_state() -> Arc<JsonRpcState> {
        let registry = Arc::new(JsonRpcMethodRegistry::new());
        let router = Arc::new(JsonRpcRouter::new(registry, true, 100));
        Arc::new(JsonRpcState { router })
    }

    /// Helper to create headers with JSON content type
    fn create_json_headers() -> HeaderMap {
        let mut headers = HeaderMap::new();
        headers.insert(header::CONTENT_TYPE, "application/json".parse().unwrap());
        headers
    }

    /// Helper to create headers with wrong content type
    fn create_wrong_content_type_headers() -> HeaderMap {
        let mut headers = HeaderMap::new();
        headers.insert(header::CONTENT_TYPE, "text/plain".parse().unwrap());
        headers
    }

    /// Helper to create empty headers
    fn create_empty_headers() -> HeaderMap {
        HeaderMap::new()
    }

    /// Helper to create a test URI
    fn create_test_uri() -> axum::http::Uri {
        axum::http::Uri::from_static("/rpc")
    }

    #[tokio::test]
    async fn test_handle_jsonrpc_single_request() {
        let state = create_test_state();
        let headers = create_json_headers();
        let uri = create_test_uri();
        let body = r#"{"jsonrpc":"2.0","method":"test.method","params":{},"id":1}"#.to_string();

        let response = handle_jsonrpc(State(state), headers, uri, body).await;

        assert_eq!(response.status(), StatusCode::OK);

        let content_type = response.headers().get(header::CONTENT_TYPE).unwrap().to_str().unwrap();
        assert!(content_type.contains("application/json"));
    }

    #[tokio::test]
    async fn test_handle_jsonrpc_batch_request() {
        let state = create_test_state();
        let headers = create_json_headers();
        let uri = create_test_uri();
        let body = r#"[
            {"jsonrpc":"2.0","method":"test.method","params":{},"id":1},
            {"jsonrpc":"2.0","method":"test.method","params":{},"id":2}
        ]"#
        .to_string();

        let response = handle_jsonrpc(State(state), headers, uri, body).await;

        assert_eq!(response.status(), StatusCode::OK);

        let content_type = response.headers().get(header::CONTENT_TYPE).unwrap().to_str().unwrap();
        assert!(content_type.contains("application/json"));
    }

    #[tokio::test]
    async fn test_invalid_content_type() {
        let state = create_test_state();
        let headers = create_wrong_content_type_headers();
        let uri = create_test_uri();
        let body = r#"{"jsonrpc":"2.0","method":"test","id":1}"#.to_string();

        let response = handle_jsonrpc(State(state), headers, uri, body).await;

        assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);

        let content_type = response.headers().get(header::CONTENT_TYPE).unwrap().to_str().unwrap();
        assert!(content_type.contains("text/plain"));
    }

    #[tokio::test]
    async fn test_missing_content_type_defaults_to_json() {
        let state = create_test_state();
        let headers = create_empty_headers();
        let uri = create_test_uri();
        let body = r#"{"jsonrpc":"2.0","method":"test.method","params":{},"id":1}"#.to_string();

        let response = handle_jsonrpc(State(state), headers, uri, body).await;

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_invalid_json_parse_error() {
        let state = create_test_state();
        let headers = create_json_headers();
        let uri = create_test_uri();
        let body = r#"{"invalid json"}"#.to_string();

        let response = handle_jsonrpc(State(state), headers, uri, body).await;

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_notification_in_batch() {
        let state = create_test_state();
        let headers = create_json_headers();
        let uri = create_test_uri();
        let body = r#"[
            {"jsonrpc":"2.0","method":"test","params":{},"id":1},
            {"jsonrpc":"2.0","method":"test","params":{}},
            {"jsonrpc":"2.0","method":"test","params":{},"id":2}
        ]"#
        .to_string();

        let response = handle_jsonrpc(State(state), headers, uri, body).await;

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[test]
    fn test_validate_content_type_valid() {
        let mut headers = HeaderMap::new();
        headers.insert(header::CONTENT_TYPE, "application/json".parse().unwrap());
        assert!(validate_content_type(&headers));
    }

    #[test]
    fn test_validate_content_type_valid_with_charset() {
        let mut headers = HeaderMap::new();
        headers.insert(header::CONTENT_TYPE, "application/json; charset=utf-8".parse().unwrap());
        assert!(validate_content_type(&headers));
    }

    #[test]
    fn test_validate_content_type_invalid() {
        let mut headers = HeaderMap::new();
        headers.insert(header::CONTENT_TYPE, "text/plain".parse().unwrap());
        assert!(!validate_content_type(&headers));
    }

    #[test]
    fn test_validate_content_type_missing() {
        let headers = HeaderMap::new();
        assert!(validate_content_type(&headers));
    }

    #[test]
    fn test_create_jsonrpc_response() {
        let json = r#"{"jsonrpc":"2.0","result":42,"id":1}"#.to_string();
        let response = create_jsonrpc_response(json);

        assert_eq!(response.status(), StatusCode::OK);
        let content_type = response.headers().get(header::CONTENT_TYPE).unwrap().to_str().unwrap();
        assert_eq!(content_type, "application/json");
    }

    #[test]
    fn test_create_error_response() {
        let response = create_error_response(StatusCode::UNSUPPORTED_MEDIA_TYPE, "Invalid content type");

        assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
        let content_type = response.headers().get(header::CONTENT_TYPE).unwrap().to_str().unwrap();
        assert!(content_type.contains("text/plain"));
    }

    #[tokio::test]
    async fn test_method_not_found_in_single_request() {
        let state = create_test_state();
        let headers = create_json_headers();
        let uri = create_test_uri();
        let body = r#"{"jsonrpc":"2.0","method":"nonexistent.method","params":{},"id":1}"#.to_string();

        let response = handle_jsonrpc(State(state), headers, uri, body).await;

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_batch_disabled() {
        let registry = Arc::new(JsonRpcMethodRegistry::new());
        let router = Arc::new(JsonRpcRouter::new(registry, false, 100));
        let state = Arc::new(JsonRpcState { router });
        let headers = create_json_headers();
        let uri = create_test_uri();
        let body = r#"[
            {"jsonrpc":"2.0","method":"test","params":{},"id":1}
        ]"#
        .to_string();

        let response = handle_jsonrpc(State(state), headers, uri, body).await;

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_batch_size_exceeded() {
        let registry = Arc::new(JsonRpcMethodRegistry::new());
        let router = Arc::new(JsonRpcRouter::new(registry, true, 2));
        let state = Arc::new(JsonRpcState { router });
        let headers = create_json_headers();
        let uri = create_test_uri();
        let body = r#"[
            {"jsonrpc":"2.0","method":"test","params":{},"id":1},
            {"jsonrpc":"2.0","method":"test","params":{},"id":2},
            {"jsonrpc":"2.0","method":"test","params":{},"id":3}
        ]"#
        .to_string();

        let response = handle_jsonrpc(State(state), headers, uri, body).await;

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_empty_batch() {
        let state = create_test_state();
        let headers = create_json_headers();
        let uri = create_test_uri();
        let body = r#"[]"#.to_string();

        let response = handle_jsonrpc(State(state), headers, uri, body).await;

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_response_with_params() {
        let state = create_test_state();
        let headers = create_json_headers();
        let uri = create_test_uri();
        let params = json!({"key": "value", "number": 42});
        let body = serde_json::to_string(&json!({
            "jsonrpc": "2.0",
            "method": "test.method",
            "params": params,
            "id": 1
        }))
        .unwrap();

        let response = handle_jsonrpc(State(state), headers, uri, body).await;

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_content_type_case_insensitive() {
        let state = create_test_state();
        let mut headers = HeaderMap::new();
        headers.insert(header::CONTENT_TYPE, "Application/JSON".parse().unwrap());
        let uri = create_test_uri();
        let body = r#"{"jsonrpc":"2.0","method":"test","id":1}"#.to_string();

        let response = handle_jsonrpc(State(state), headers, uri, body).await;

        assert_eq!(response.status(), StatusCode::OK);
    }
}