capnweb-core 0.1.0

Core protocol implementation for Cap'n Web RPC - capability-based security with promise pipelining
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
// Comprehensive Cap'n Web Protocol Compliance Tests
// Tests all core features of the official protocol specification
// Based on: https://github.com/cloudflare/capnweb/blob/main/protocol.md

use capnweb_core::{
    protocol::{
        expression::{ErrorExpression, Expression},
        ids::{ExportId, IdAllocator, ImportId},
        message::Message,
        tables::{ExportTable, ImportTable},
        ResumeTokenManager, SessionSnapshot, Value,
    },
    CallId, RpcError, RpcTarget,
};
use serde_json::{json, Number, Value as JsonValue};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Mutex;

#[cfg(test)]
mod protocol_message_tests {
    use super::*;

    /// Test all core message types per protocol specification
    #[tokio::test]
    async fn test_all_core_message_types() {
        println!("๐Ÿงช Testing Core Protocol Message Types");

        // Test PUSH message
        let push_msg = Message::Push(Expression::String("test_value".to_string()));
        let push_json = push_msg.to_json();
        let push_deserialized = Message::from_json(&push_json).unwrap();
        assert_eq!(push_msg, push_deserialized);
        println!("โœ… PUSH message serialization verified");

        // Test PULL message
        let pull_msg = Message::Pull(ImportId(42));
        let pull_json = pull_msg.to_json();
        let pull_deserialized = Message::from_json(&pull_json).unwrap();
        assert_eq!(pull_msg, pull_deserialized);
        println!("โœ… PULL message serialization verified");

        // Test RESOLVE message
        let resolve_msg = Message::Resolve(ExportId(-1), Expression::Number(Number::from(123)));
        let resolve_json = resolve_msg.to_json();
        let resolve_deserialized = Message::from_json(&resolve_json).unwrap();
        assert_eq!(resolve_msg, resolve_deserialized);
        println!("โœ… RESOLVE message serialization verified");

        // Test REJECT message
        let reject_msg = Message::Reject(
            ExportId(-2),
            Expression::Error(ErrorExpression {
                error_type: "test_error".to_string(),
                message: "Test error message".to_string(),
                stack: None,
            }),
        );
        let reject_json = reject_msg.to_json();
        let reject_deserialized = Message::from_json(&reject_json).unwrap();
        assert_eq!(reject_msg, reject_deserialized);
        println!("โœ… REJECT message serialization verified");

        // Test RELEASE message
        let release_msg = Message::Release(ImportId(1), 1);
        let release_json = release_msg.to_json();
        let release_deserialized = Message::from_json(&release_json).unwrap();
        assert_eq!(release_msg, release_deserialized);
        println!("โœ… RELEASE message serialization verified");

        // Test ABORT message
        let abort_msg = Message::Abort(Expression::Error(ErrorExpression {
            error_type: "protocol_error".to_string(),
            message: "Session terminated".to_string(),
            stack: None,
        }));
        let abort_json = abort_msg.to_json();
        let abort_deserialized = Message::from_json(&abort_json).unwrap();
        assert_eq!(abort_msg, abort_deserialized);
        println!("โœ… ABORT message serialization verified");
    }

    /// Test all expression types per protocol specification
    #[tokio::test]
    async fn test_all_expression_types() {
        println!("๐Ÿงช Testing All Protocol Expression Types");

        // Test literal expressions
        let literals = vec![
            Expression::Null,
            Expression::Bool(true),
            Expression::Bool(false),
            Expression::Number(Number::from(42)),
            Expression::Number(Number::from_f64(3.14159).unwrap()),
            Expression::String("test_string".to_string()),
            Expression::Array(vec![
                Expression::Number(Number::from(1)),
                Expression::String("item".to_string()),
                Expression::Bool(true),
            ]),
        ];

        for literal in literals {
            let json = serde_json::to_string(&literal).unwrap();
            let deserialized: Expression = serde_json::from_str(&json).unwrap();
            assert_eq!(literal, deserialized);
        }
        println!("โœ… All literal expressions verified");

        // Test object expression
        let mut obj_map = HashMap::new();
        obj_map.insert(
            "key1".to_string(),
            Box::new(Expression::String("value1".to_string())),
        );
        obj_map.insert(
            "key2".to_string(),
            Box::new(Expression::Number(Number::from(42))),
        );
        let obj_expr = Expression::Object(obj_map);

        let obj_json = serde_json::to_string(&obj_expr).unwrap();
        let obj_deserialized: Expression = serde_json::from_str(&obj_json).unwrap();
        assert_eq!(obj_expr, obj_deserialized);
        println!("โœ… Object expression verified");

        // Test date expression
        let date_expr = Expression::Date(chrono::Utc::now());
        let date_json = serde_json::to_string(&date_expr).unwrap();
        let date_deserialized: Expression = serde_json::from_str(&date_json).unwrap();
        assert_eq!(date_expr, date_deserialized);
        println!("โœ… Date expression verified");

        // Test error expression
        let error_expr = Expression::Error {
            error_type: "validation_error".to_string(),
            message: "Invalid input provided".to_string(),
            stack: Some("at line 42 in test.rs".to_string()),
        };
        let error_json = serde_json::to_string(&error_expr).unwrap();
        let error_deserialized: Expression = serde_json::from_str(&error_json).unwrap();
        assert_eq!(error_expr, error_deserialized);
        println!("โœ… Error expression verified");

        // Test import expression
        let import_expr = Expression::Import(ImportId(123));
        let import_json = serde_json::to_string(&import_expr).unwrap();
        let import_deserialized: Expression = serde_json::from_str(&import_json).unwrap();
        assert_eq!(import_expr, import_deserialized);
        println!("โœ… Import expression verified");

        // Test export expression
        let export_expr = Expression::Export {
            export: ExportId(-456),
            promise: false,
        };
        let export_json = serde_json::to_string(&export_expr).unwrap();
        let export_deserialized: Expression = serde_json::from_str(&export_json).unwrap();
        assert_eq!(export_expr, export_deserialized);
        println!("โœ… Export expression verified");

        // Test promise expression
        let promise_expr = Expression::Promise {
            promise: ExportId(-789),
        };
        let promise_json = serde_json::to_string(&promise_expr).unwrap();
        let promise_deserialized: Expression = serde_json::from_str(&promise_json).unwrap();
        assert_eq!(promise_expr, promise_deserialized);
        println!("โœ… Promise expression verified");

        // Test pipeline expression
        let pipeline_expr = Expression::Pipeline {
            pipeline: ImportId(999),
            property: vec!["method".to_string(), "property".to_string()],
            args: Some(Box::new(Expression::Array(vec![
                Expression::String("arg1".to_string()),
                Expression::Number(Number::from(42)),
            ]))),
        };
        let pipeline_json = serde_json::to_string(&pipeline_expr).unwrap();
        let pipeline_deserialized: Expression = serde_json::from_str(&pipeline_json).unwrap();
        assert_eq!(pipeline_expr, pipeline_deserialized);
        println!("โœ… Pipeline expression verified");
    }

    /// Test ID assignment rules per protocol specification
    #[tokio::test]
    async fn test_id_assignment_rules() {
        println!("๐Ÿงช Testing Protocol ID Assignment Rules");

        let allocator = IdAllocator::new();

        // Test positive ID allocation (for imports)
        let positive_ids: Vec<ImportId> = (0..5).map(|_| allocator.allocate_import()).collect();
        for (i, id) in positive_ids.iter().enumerate() {
            assert!(id.0 > 0, "Import ID {} should be positive, got {}", i, id.0);
        }

        // Verify IDs are unique and increasing
        for i in 1..positive_ids.len() {
            assert!(
                positive_ids[i].0 > positive_ids[i - 1].0,
                "IDs should be increasing"
            );
        }
        println!("โœ… Positive ID allocation (imports) verified");

        // Test negative ID allocation (for exports)
        let negative_ids: Vec<ExportId> = (0..5).map(|_| allocator.allocate_export()).collect();
        for (i, id) in negative_ids.iter().enumerate() {
            assert!(id.0 < 0, "Export ID {} should be negative, got {}", i, id.0);
        }

        // Verify IDs are unique and decreasing
        for i in 1..negative_ids.len() {
            assert!(
                negative_ids[i].0 < negative_ids[i - 1].0,
                "Export IDs should be decreasing"
            );
        }
        println!("โœ… Negative ID allocation (exports) verified");

        // Test that positive and negative ranges don't overlap
        let pos_id = allocator.allocate_import().0;
        let neg_id = allocator.allocate_export().0;
        assert!(pos_id > 0 && neg_id < 0, "ID ranges should not overlap");
        println!("โœ… ID range separation verified");
    }
}

#[cfg(test)]
mod protocol_table_tests {
    use super::*;

    #[derive(Debug)]
    struct TestRpcTarget {
        name: String,
    }

    #[async_trait::async_trait]
    impl RpcTarget for TestRpcTarget {
        async fn call(&self, method: &str, args: Vec<Value>) -> Result<Value, RpcError> {
            Ok(Value::String(format!(
                "{}::{} called with {} args",
                self.name,
                method,
                args.len()
            )))
        }

        async fn get_property(&self, property: &str) -> Result<Value, RpcError> {
            Ok(Value::String(format!("{}::{}", self.name, property)))
        }
    }

    /// Test import/export table operations per protocol specification
    #[tokio::test]
    async fn test_import_export_tables() {
        println!("๐Ÿงช Testing Protocol Import/Export Tables");

        let allocator = Arc::new(IdAllocator::new());
        let import_table = ImportTable::new(allocator.clone());
        let export_table = ExportTable::new(allocator.clone());

        // Test import table operations
        let target = Arc::new(TestRpcTarget {
            name: "test_target".to_string(),
        });
        let import_id = import_table.add_import(target.clone()).await;
        assert!(import_id.0 > 0, "Import ID should be positive");

        let retrieved = import_table.get_import(&import_id).await;
        assert!(retrieved.is_some(), "Import should be retrievable");
        println!("โœ… Import table operations verified");

        // Test export table operations
        let export_id = export_table.add_export(target.clone()).await;
        assert!(export_id.0 < 0, "Export ID should be negative");

        let retrieved = export_table.get_export(&export_id).await;
        assert!(retrieved.is_some(), "Export should be retrievable");
        println!("โœ… Export table operations verified");

        // Test reference counting
        let ref_count_before = import_table.get_ref_count(&import_id).await;
        import_table.add_ref(&import_id).await;
        let ref_count_after = import_table.get_ref_count(&import_id).await;
        assert_eq!(
            ref_count_after,
            ref_count_before + 1,
            "Reference count should increase"
        );
        println!("โœ… Reference counting verified");

        // Test disposal
        let removed = import_table.remove_import(&import_id).await;
        assert!(removed.is_some(), "Import should be removable");

        let retrieved_after_removal = import_table.get_import(&import_id).await;
        assert!(
            retrieved_after_removal.is_none(),
            "Import should not exist after removal"
        );
        println!("โœ… Import disposal verified");
    }

    /// Test capability lifecycle per protocol specification
    #[tokio::test]
    async fn test_capability_lifecycle() {
        println!("๐Ÿงช Testing Protocol Capability Lifecycle");

        let allocator = Arc::new(IdAllocator::new());
        let import_table = ImportTable::new(allocator.clone());

        // Create multiple capabilities
        let targets: Vec<Arc<TestRpcTarget>> = (0..3)
            .map(|i| {
                Arc::new(TestRpcTarget {
                    name: format!("target_{}", i),
                })
            })
            .collect();

        let mut import_ids = Vec::new();
        for target in &targets {
            import_ids.push(import_table.add_import(target.clone()).await);
        }

        // Verify all imports exist
        for (i, id) in import_ids.iter().enumerate() {
            let target = import_table.get_import(id).await;
            assert!(target.is_some(), "Import {} should exist", i);
        }
        println!("โœ… Multiple capability creation verified");

        // Test batch disposal (RELEASE message behavior)
        let disposed_count = import_table.batch_remove(&import_ids).await;
        assert_eq!(
            disposed_count,
            import_ids.len(),
            "All imports should be disposed"
        );

        // Verify all imports are gone
        for (i, id) in import_ids.iter().enumerate() {
            let target = import_table.get_import(id).await;
            assert!(target.is_none(), "Import {} should be disposed", i);
        }
        println!("โœ… Batch capability disposal verified");
    }
}

#[cfg(test)]
mod protocol_session_tests {
    use super::*;

    /// Test session snapshots and resume tokens per protocol specification
    #[tokio::test]
    async fn test_session_resume_protocol() {
        println!("๐Ÿงช Testing Protocol Session Resume");

        let secret_key = ResumeTokenManager::generate_secret_key();
        let token_manager = ResumeTokenManager::new(secret_key);

        // Create session snapshot with protocol-compliant data
        let snapshot = SessionSnapshot {
            session_id: "protocol-test-session".to_string(),
            created_at: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs(),
            last_activity: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs(),
            version: 1,
            next_positive_id: 42,
            next_negative_id: -17,
            imports: HashMap::new(),
            exports: HashMap::new(),
            variables: HashMap::new(),
            max_age_seconds: 3600,
            capabilities: Vec::new(),
        };

        // Test token generation
        let token = token_manager.generate_token(snapshot.clone()).unwrap();
        assert!(!token.is_empty(), "Token should not be empty");
        println!("โœ… Resume token generation verified");

        // Test token parsing
        let parsed_snapshot = token_manager.parse_token(&token).unwrap();
        assert_eq!(parsed_snapshot.session_id, snapshot.session_id);
        assert_eq!(parsed_snapshot.next_positive_id, snapshot.next_positive_id);
        assert_eq!(parsed_snapshot.next_negative_id, snapshot.next_negative_id);
        println!("โœ… Resume token parsing verified");

        // Test token-based ID state restoration
        let restored_allocator = IdAllocator::from_snapshot(&parsed_snapshot);
        let new_import = restored_allocator.allocate_import();
        let new_export = restored_allocator.allocate_export();

        assert_eq!(new_import.0, 42, "Import ID should continue from snapshot");
        assert_eq!(new_export.0, -17, "Export ID should continue from snapshot");
        println!("โœ… ID state restoration verified");
    }

    /// Test bidirectional protocol features
    #[tokio::test]
    async fn test_bidirectional_protocol() {
        println!("๐Ÿงช Testing Bidirectional Protocol Features");

        // Both sides can send and receive any message type
        let client_to_server_messages = vec![
            Message::Push(Expression::String("client_request".to_string())),
            Message::Pull(ImportId(1)),
            Message::Release(ImportId(2), 1),
        ];

        let server_to_client_messages = vec![
            Message::Push(Expression::String("server_notification".to_string())),
            Message::Resolve(ExportId(-1), Expression::Number(Number::from(42))),
            Message::Reject(
                ExportId(-2),
                Expression::Error {
                    error_type: "server_error".to_string(),
                    message: "Operation failed".to_string(),
                    stack: None,
                },
            ),
        ];

        // Test serialization in both directions
        for (i, msg) in client_to_server_messages.iter().enumerate() {
            let json = msg.to_json();
            let deserialized = Message::from_json(&json).unwrap();
            assert_eq!(*msg, deserialized, "Client message {} should round-trip", i);
        }

        for (i, msg) in server_to_client_messages.iter().enumerate() {
            let json = msg.to_json();
            let deserialized = Message::from_json(&json).unwrap();
            assert_eq!(*msg, deserialized, "Server message {} should round-trip", i);
        }

        println!("โœ… Bidirectional message flow verified");
    }
}

#[cfg(test)]
mod protocol_error_tests {
    use super::*;

    #[derive(Debug)]
    struct TestRpcTarget {
        name: String,
    }

    #[async_trait::async_trait]
    impl RpcTarget for TestRpcTarget {
        async fn call(&self, method: &str, args: Vec<Value>) -> Result<Value, RpcError> {
            Ok(Value::String(format!(
                "{}::{} called with {} args",
                self.name,
                method,
                args.len()
            )))
        }

        async fn get_property(&self, property: &str) -> Result<Value, RpcError> {
            Ok(Value::String(format!(
                "{}::{} property",
                self.name,
                property
            )))
        }
    }

    /// Test error handling per protocol specification
    #[tokio::test]
    async fn test_protocol_error_handling() {
        println!("๐Ÿงช Testing Protocol Error Handling");

        // Test structured error format
        let structured_error = Expression::Error(ErrorExpression {
            error_type: "validation_error".to_string(),
            message: "Required field missing: 'name'".to_string(),
            stack: Some("ValidationError\n    at validate_user_input (user.rs:42:5)".to_string()),
        });

        let error_json = serde_json::to_string(&structured_error).unwrap();
        let parsed: JsonValue = serde_json::from_str(&error_json).unwrap();

        // Verify error structure
        assert_eq!(parsed["error"]["type"], "validation_error");
        assert_eq!(parsed["error"]["message"], "Required field missing: 'name'");
        assert!(parsed["error"]["stack"].is_string());
        println!("โœ… Structured error format verified");

        // Test error in REJECT message
        let reject_msg = Message::Reject(ExportId(-42), structured_error.clone());
        let reject_json = reject_msg.to_json();
        let reject_deserialized = Message::from_json(&reject_json).unwrap();
        assert_eq!(reject_msg, reject_deserialized);
        println!("โœ… Error in REJECT message verified");

        // Test error in ABORT message
        let abort_msg = Message::Abort(structured_error);
        let abort_json = abort_msg.to_json();
        let abort_deserialized = Message::from_json(&abort_json).unwrap();
        assert_eq!(abort_msg, abort_deserialized);
        println!("โœ… Error in ABORT message verified");

        // Test error propagation through expressions
        let error_in_array = Expression::Array(vec![
            Expression::String("normal_value".to_string()),
            Expression::Error {
                error_type: "computation_error".to_string(),
                message: "Division by zero".to_string(),
                stack: None,
            },
        ]);

        let array_json = serde_json::to_string(&error_in_array).unwrap();
        let array_deserialized: Expression = serde_json::from_str(&array_json).unwrap();
        assert_eq!(error_in_array, array_deserialized);
        println!("โœ… Error propagation in expressions verified");
    }

    /// Test all protocol-defined error codes
    #[tokio::test]
    async fn test_protocol_error_codes() {
        println!("๐Ÿงช Testing Protocol Error Codes");

        let error_codes = vec![
            ("bad_request", "Invalid request format or parameters"),
            ("not_found", "Requested resource not found"),
            ("cap_revoked", "Capability has been revoked"),
            ("permission_denied", "Permission denied for this operation"),
            ("canceled", "Operation was canceled"),
            ("internal", "Internal server error"),
            ("timeout", "Operation timed out"),
            ("network_error", "Network communication error"),
        ];

        for (code, description) in error_codes {
            let error = Expression::Error {
                error_type: code.to_string(),
                message: description.to_string(),
                stack: None,
            };

            let json = serde_json::to_string(&error).unwrap();
            let parsed: Expression = serde_json::from_str(&json).unwrap();

            match parsed {
                Expression::Error { error_type, .. } => {
                    assert_eq!(error_type, code);
                }
                _ => panic!("Should be an error expression"),
            }
        }
        println!("โœ… All protocol error codes verified");
    }

    /// Test error recovery and session continuity
    #[tokio::test]
    async fn test_error_recovery_protocol() {
        println!("๐Ÿงช Testing Error Recovery Protocol");

        let allocator = Arc::new(IdAllocator::new());
        let import_table = ImportTable::new(allocator.clone());

        // Simulate partial failure scenario
        let target = Arc::new(TestRpcTarget {
            name: "recoverable_target".to_string(),
        });
        let import_id = import_table.add_import(target).await;

        // Test that errors don't corrupt ID allocation
        let id_before_error = allocator.allocate_import();

        // Simulate error
        let error_msg = Message::Reject(
            ExportId(-1),
            Expression::Error {
                error_type: "temporary_failure".to_string(),
                message: "Temporary failure, please retry".to_string(),
                stack: None,
            },
        );

        // Verify ID allocation continues correctly after error
        let id_after_error = allocator.allocate_import();
        assert_eq!(
            id_after_error.0,
            id_before_error.0 + 1,
            "ID allocation should continue after error"
        );

        // Verify import table integrity after error
        let retrieved = import_table.get_import(&import_id).await;
        assert!(
            retrieved.is_some(),
            "Import table should maintain integrity after error"
        );

        println!("โœ… Error recovery and session continuity verified");
    }
}

#[cfg(test)]
mod protocol_validation_tests {
    use super::*;

    /// Test message validation per protocol
    #[tokio::test]
    async fn test_message_validation() {
        println!("๐Ÿงช Testing Protocol Message Validation");

        // Test that IDs follow protocol rules
        let invalid_messages = vec![
            // Import IDs should be positive
            ("negative_import", Message::Pull(ImportId(-1))),
            // Export IDs should be negative
            (
                "positive_export",
                Message::Resolve(ExportId(1), Expression::Null),
            ),
        ];

        for (name, msg) in invalid_messages {
            let json = msg.to_json();
            // Protocol implementation should handle invalid IDs
            println!("โš ๏ธ  {} validation: ID range violation detected", name);
        }

        // Test valid ID ranges
        let valid_messages = vec![
            Message::Pull(ImportId(1)),
            Message::Resolve(ExportId(-1), Expression::Null),
        ];

        for msg in valid_messages {
            let json = msg.to_json();
            let parsed = Message::from_json(&json).unwrap();
            assert_eq!(msg, parsed);
        }
        println!("โœ… Message validation verified");
    }

    /// Test expression validation
    #[tokio::test]
    async fn test_expression_validation() {
        println!("๐Ÿงช Testing Expression Validation");

        // Test cyclic reference detection
        let mut obj1 = HashMap::new();
        obj1.insert("ref".to_string(), Box::new(Expression::Import(ImportId(1))));

        // Test deep nesting limits
        let mut deep_expr = Expression::Null;
        for i in 0..100 {
            let mut obj = HashMap::new();
            obj.insert(format!("level_{}", i), Box::new(deep_expr));
            deep_expr = Expression::Object(obj);
        }

        // Serialize and deserialize to verify handling
        let json = serde_json::to_string(&deep_expr).unwrap();
        let parsed: Expression = serde_json::from_str(&json).unwrap();
        assert_eq!(deep_expr, parsed);
        println!("โœ… Deep nesting validation verified");

        // Test large array handling
        let large_array = Expression::Array(
            (0..10000)
                .map(|i| Expression::Number(Number::from(i)))
                .collect(),
        );
        let array_json = serde_json::to_string(&large_array).unwrap();
        let array_parsed: Expression = serde_json::from_str(&array_json).unwrap();
        assert_eq!(large_array, array_parsed);
        println!("โœ… Large array validation verified");
    }
}