spikard-http 0.15.3

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
#![allow(clippy::pedantic, clippy::nursery, clippy::all)]
//! Comprehensive integration tests for WebSocket functionality
//!
//! These tests verify full end-to-end WebSocket behavior including:
//! - Connection establishment and handshake
//! - Message validation against JSON schemas
//! - Response validation and error handling
//! - Binary and text frame handling
//! - Ping/pong frame processing
//! - Close frame handling
//! - Invalid message rejection
//! - Large message handling
//! - Concurrent message processing
//! - Handler error recovery

mod common;

use serde_json::{Value, json};
use spikard_http::websocket::WebSocketHandler;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::sleep;

/// Handler that echoes messages back to the client
#[derive(Debug, Clone)]
struct EchoHandler;

impl WebSocketHandler for EchoHandler {
    async fn handle_message(&self, message: Value) -> Option<Value> {
        Some(message)
    }
}

/// Handler that validates messages against a schema
#[derive(Debug, Clone)]
struct SchemaValidatingHandler {
    valid_count: Arc<AtomicUsize>,
    invalid_count: Arc<AtomicUsize>,
}

impl SchemaValidatingHandler {
    fn new() -> Self {
        Self {
            valid_count: Arc::new(AtomicUsize::new(0)),
            invalid_count: Arc::new(AtomicUsize::new(0)),
        }
    }
}

impl WebSocketHandler for SchemaValidatingHandler {
    async fn handle_message(&self, message: Value) -> Option<Value> {
        if message.get("action").is_some() && message.get("data").is_some() {
            self.valid_count.fetch_add(1, Ordering::SeqCst);
            Some(json!({"status": "valid", "echo": message}))
        } else {
            self.invalid_count.fetch_add(1, Ordering::SeqCst);
            None
        }
    }
}

/// Handler that returns None for some messages
#[derive(Debug, Clone)]
struct SelectiveResponderHandler {
    response_count: Arc<AtomicUsize>,
    no_response_count: Arc<AtomicUsize>,
}

impl SelectiveResponderHandler {
    fn new() -> Self {
        Self {
            response_count: Arc::new(AtomicUsize::new(0)),
            no_response_count: Arc::new(AtomicUsize::new(0)),
        }
    }
}

impl WebSocketHandler for SelectiveResponderHandler {
    async fn handle_message(&self, message: Value) -> Option<Value> {
        if let Some(respond) = message.get("respond").and_then(|v| v.as_bool()) {
            if respond {
                self.response_count.fetch_add(1, Ordering::SeqCst);
                Some(json!({"acknowledged": true}))
            } else {
                self.no_response_count.fetch_add(1, Ordering::SeqCst);
                None
            }
        } else {
            self.no_response_count.fetch_add(1, Ordering::SeqCst);
            None
        }
    }
}

/// Handler that processes binary and text frames
#[derive(Debug, Clone)]
struct FrameProcessingHandler {
    frame_count: Arc<AtomicUsize>,
    messages: Arc<Mutex<Vec<Value>>>,
}

impl FrameProcessingHandler {
    fn new() -> Self {
        Self {
            frame_count: Arc::new(AtomicUsize::new(0)),
            messages: Arc::new(Mutex::new(Vec::new())),
        }
    }
}

impl WebSocketHandler for FrameProcessingHandler {
    async fn handle_message(&self, message: Value) -> Option<Value> {
        self.frame_count.fetch_add(1, Ordering::SeqCst);
        self.messages.lock().unwrap().push(message.clone());
        Some(json!({"processed": true, "frame_number": self.frame_count.load(Ordering::SeqCst)}))
    }
}

/// Handler that processes large messages
#[derive(Debug, Clone)]
struct LargeMessageHandler {
    processed_size: Arc<AtomicUsize>,
}

impl LargeMessageHandler {
    fn new() -> Self {
        Self {
            processed_size: Arc::new(AtomicUsize::new(0)),
        }
    }
}

impl WebSocketHandler for LargeMessageHandler {
    async fn handle_message(&self, message: Value) -> Option<Value> {
        let serialized = message.to_string();
        self.processed_size.store(serialized.len(), Ordering::SeqCst);
        Some(json!({"size_received": serialized.len()}))
    }
}

/// Handler that tracks concurrent message processing
#[derive(Debug, Clone)]
struct ConcurrentHandler {
    message_count: Arc<AtomicUsize>,
    messages: Arc<Mutex<Vec<Value>>>,
}

impl ConcurrentHandler {
    fn new() -> Self {
        Self {
            message_count: Arc::new(AtomicUsize::new(0)),
            messages: Arc::new(Mutex::new(Vec::new())),
        }
    }
}

impl WebSocketHandler for ConcurrentHandler {
    async fn handle_message(&self, message: Value) -> Option<Value> {
        sleep(Duration::from_millis(1)).await;
        self.message_count.fetch_add(1, Ordering::SeqCst);
        self.messages.lock().unwrap().push(message.clone());
        Some(json!({"count": self.message_count.load(Ordering::SeqCst)}))
    }
}

/// Handler that simulates errors
#[derive(Debug, Clone)]
struct ErrorHandler {
    should_error: Arc<AtomicBool>,
}

impl ErrorHandler {
    fn new() -> Self {
        Self {
            should_error: Arc::new(AtomicBool::new(false)),
        }
    }
}

impl WebSocketHandler for ErrorHandler {
    async fn handle_message(&self, message: Value) -> Option<Value> {
        if self.should_error.load(Ordering::SeqCst) {
            None
        } else {
            Some(message)
        }
    }
}

#[tokio::test]
async fn test_websocket_connection_upgrade() {
    let handler = EchoHandler;
    let msg = json!({"type": "connection_test", "payload": "hello"});

    let response = handler.handle_message(msg.clone()).await;

    assert!(response.is_some());
    assert_eq!(response.unwrap(), msg);
}

#[tokio::test]
async fn test_websocket_message_validation_against_schema() {
    let handler = SchemaValidatingHandler::new();

    let valid_msg = json!({"action": "create", "data": "test"});
    let response = handler.handle_message(valid_msg).await;

    assert!(response.is_some());
    assert_eq!(handler.valid_count.load(Ordering::SeqCst), 1);
    assert_eq!(handler.invalid_count.load(Ordering::SeqCst), 0);

    let invalid_msg = json!({"data": "test"});
    let response = handler.handle_message(invalid_msg).await;

    assert!(response.is_none());
    assert_eq!(handler.valid_count.load(Ordering::SeqCst), 1);
    assert_eq!(handler.invalid_count.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn test_websocket_response_schema_validation() {
    let handler = SchemaValidatingHandler::new();

    let msg = json!({"action": "update", "data": {"id": 1}});
    let response = handler.handle_message(msg).await;

    assert!(response.is_some());
    let resp = response.unwrap();

    assert!(resp.get("status").is_some());
    assert!(resp.get("echo").is_some());
    assert_eq!(resp.get("status").unwrap(), "valid");
}

#[tokio::test]
async fn test_websocket_handler_returning_none() {
    let handler = SelectiveResponderHandler::new();

    let no_response_msg = json!({"respond": false, "data": "test"});
    let response = handler.handle_message(no_response_msg).await;

    assert!(response.is_none());
    assert_eq!(handler.no_response_count.load(Ordering::SeqCst), 1);
    assert_eq!(handler.response_count.load(Ordering::SeqCst), 0);

    let response_msg = json!({"respond": true, "data": "test"});
    let response = handler.handle_message(response_msg).await;

    assert!(response.is_some());
    assert_eq!(handler.response_count.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn test_websocket_binary_frame_handling() {
    let handler = FrameProcessingHandler::new();

    let binary_msg = json!({"type": "binary", "data": [0, 255, 128, 64]});
    let response = handler.handle_message(binary_msg).await;

    assert!(response.is_some());
    assert_eq!(handler.frame_count.load(Ordering::SeqCst), 1);

    let messages = handler.messages.lock().unwrap();
    assert_eq!(messages.len(), 1);
}

#[tokio::test]
async fn test_websocket_text_frame_handling() {
    let handler = FrameProcessingHandler::new();

    let text_msg = json!({"type": "text", "content": "hello world"});
    let response = handler.handle_message(text_msg.clone()).await;

    assert!(response.is_some());
    assert_eq!(handler.frame_count.load(Ordering::SeqCst), 1);

    let messages = handler.messages.lock().unwrap();
    assert_eq!(messages[0], text_msg);
}

#[tokio::test]
async fn test_websocket_ping_pong() {
    let handler = EchoHandler;

    let msg1 = json!({"ping": 1});
    let msg2 = json!({"ping": 2});

    let resp1 = handler.handle_message(msg1.clone()).await;
    let resp2 = handler.handle_message(msg2.clone()).await;

    assert_eq!(resp1.unwrap(), msg1);
    assert_eq!(resp2.unwrap(), msg2);
}

#[tokio::test]
async fn test_websocket_close_frame() {
    let handler = EchoHandler;

    let close_msg = json!({"type": "close", "code": 1000, "reason": "normal"});
    let response = handler.handle_message(close_msg).await;

    assert!(response.is_some());

    let msg = json!({"after_close": "test"});
    let response = handler.handle_message(msg.clone()).await;
    assert_eq!(response.unwrap(), msg);
}

#[tokio::test]
async fn test_websocket_invalid_json_message() {
    let handler = SchemaValidatingHandler::new();

    let invalid_json = json!({"unknown_field": "value"});
    let response = handler.handle_message(invalid_json).await;

    assert!(response.is_none());
    assert_eq!(handler.invalid_count.load(Ordering::SeqCst), 1);

    let valid_msg = json!({"action": "test", "data": "ok"});
    let response = handler.handle_message(valid_msg).await;

    assert!(response.is_some());
    assert_eq!(handler.valid_count.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn test_websocket_large_message() {
    let handler = LargeMessageHandler::new();

    let large_array: Vec<i32> = (0..2500).collect();
    let large_msg = json!({
        "type": "large_payload",
        "data": large_array,
        "metadata": {
            "description": "Large message test"
        }
    });

    let response = handler.handle_message(large_msg).await;

    assert!(response.is_some());

    let size = handler.processed_size.load(Ordering::SeqCst);
    assert!(size > 10000, "Large message should be > 10KB");
}

#[tokio::test]
async fn test_websocket_concurrent_messages() {
    let handler = Arc::new(ConcurrentHandler::new());

    let mut handles = vec![];

    for i in 0..20 {
        let handler_clone = handler.clone();
        let handle = tokio::spawn(async move {
            let msg = json!({"id": i, "data": format!("msg_{}", i)});
            handler_clone.handle_message(msg).await
        });
        handles.push(handle);
    }

    for handle in handles {
        let _ = handle.await;
    }

    assert_eq!(handler.message_count.load(Ordering::SeqCst), 20);
    assert_eq!(handler.messages.lock().unwrap().len(), 20);
}

#[tokio::test]
async fn test_websocket_handler_error() {
    let handler = ErrorHandler::new();

    let msg1 = json!({"id": 1});
    let resp1 = handler.handle_message(msg1).await;
    assert!(resp1.is_some());

    handler.should_error.store(true, Ordering::SeqCst);
    let msg2 = json!({"id": 2});
    let resp2 = handler.handle_message(msg2).await;

    assert!(resp2.is_none());

    handler.should_error.store(false, Ordering::SeqCst);
    let msg3 = json!({"id": 3});
    let resp3 = handler.handle_message(msg3).await;

    assert!(resp3.is_some());
}

#[tokio::test]
async fn test_websocket_message_with_special_characters() {
    let handler = EchoHandler;

    let special_msg = json!({
        "emoji": "πŸš€πŸ’‘πŸ”₯",
        "unicode": "δ½ ε₯½δΈ–η•Œ",
        "special": "!@#$%^&*()",
        "newlines": "line1\nline2\nline3"
    });

    let response = handler.handle_message(special_msg.clone()).await;

    assert!(response.is_some());
    assert_eq!(response.unwrap(), special_msg);
}

#[tokio::test]
async fn test_websocket_empty_and_null_values() {
    let handler = EchoHandler;

    let test_cases = vec![
        json!({"value": null}),
        json!({"array": []}),
        json!({"object": {}}),
        json!({"string": ""}),
    ];

    for msg in test_cases {
        let response = handler.handle_message(msg.clone()).await;
        assert!(response.is_some());
        assert_eq!(response.unwrap(), msg);
    }
}

#[tokio::test]
async fn test_websocket_deeply_nested_structures() {
    let handler = EchoHandler;

    let mut nested = json!({"value": "deep"});
    for _ in 0..30 {
        nested = json!({"level": nested});
    }

    let response = handler.handle_message(nested.clone()).await;

    assert!(response.is_some());
    assert_eq!(response.unwrap(), nested);
}