pjson-rs 0.5.1

Priority JSON Streaming Protocol - high-performance priority-based JSON streaming (requires nightly Rust)
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
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

//! High-level session management service

use crate::{
    application::{
        ApplicationResult,
        commands::*,
        handlers::{CommandHandler, QueryHandler},
        queries::*,
    },
    domain::{
        aggregates::{StreamSession, stream_session::SessionHealth},
        value_objects::{SessionId, StreamId},
    },
};
use std::sync::Arc;

/// High-level service for session management workflows
#[derive(Debug)]
pub struct SessionService<CH, QH>
where
    CH: CommandHandler<CreateSessionCommand, SessionId>
        + CommandHandler<CreateStreamCommand, StreamId>
        + CommandHandler<StartStreamCommand, ()>
        + CommandHandler<CompleteStreamCommand, ()>
        + CommandHandler<CloseSessionCommand, ()>,
    QH: QueryHandler<GetSessionQuery, SessionResponse>
        + QueryHandler<GetSessionHealthQuery, HealthResponse>
        + QueryHandler<GetActiveSessionsQuery, SessionsResponse>,
{
    command_handler: Arc<CH>,
    query_handler: Arc<QH>,
}

impl<CH, QH> SessionService<CH, QH>
where
    CH: CommandHandler<CreateSessionCommand, SessionId>
        + CommandHandler<CreateStreamCommand, StreamId>
        + CommandHandler<StartStreamCommand, ()>
        + CommandHandler<CompleteStreamCommand, ()>
        + CommandHandler<CloseSessionCommand, ()>
        + Send
        + Sync,
    QH: QueryHandler<GetSessionQuery, SessionResponse>
        + QueryHandler<GetSessionHealthQuery, HealthResponse>
        + QueryHandler<GetActiveSessionsQuery, SessionsResponse>
        + Send
        + Sync,
{
    pub fn new(command_handler: Arc<CH>, query_handler: Arc<QH>) -> Self {
        Self {
            command_handler,
            query_handler,
        }
    }

    /// Create new session with automatic activation
    pub async fn create_and_activate_session(
        &self,
        config: crate::domain::aggregates::stream_session::SessionConfig,
        client_info: Option<String>,
        user_agent: Option<String>,
        ip_address: Option<String>,
    ) -> ApplicationResult<SessionId> {
        let create_command = CreateSessionCommand {
            config,
            client_info,
            user_agent,
            ip_address,
        };

        // Session is automatically activated in the command handler
        self.command_handler.handle(create_command).await
    }

    /// Create stream and immediately start it
    pub async fn create_and_start_stream(
        &self,
        session_id: SessionId,
        source_data: serde_json::Value,
        config: Option<crate::domain::entities::stream::StreamConfig>,
    ) -> ApplicationResult<StreamId> {
        // Create stream
        let create_command = CreateStreamCommand {
            session_id: session_id.into(),
            source_data,
            config,
        };

        let stream_id = self.command_handler.handle(create_command).await?;

        // Start stream
        let start_command = StartStreamCommand {
            session_id: session_id.into(),
            stream_id: stream_id.into(),
        };

        self.command_handler.handle(start_command).await?;

        Ok(stream_id)
    }

    /// Get session with health check
    pub async fn get_session_with_health(
        &self,
        session_id: SessionId,
    ) -> ApplicationResult<SessionWithHealth> {
        // Get session info
        let session_query = GetSessionQuery { session_id: session_id.into() };
        let session_response = self.query_handler.handle(session_query).await?;

        // Get health status
        let health_query = GetSessionHealthQuery { session_id: session_id.into() };
        let health_response = self.query_handler.handle(health_query).await?;

        Ok(SessionWithHealth {
            session: session_response.session,
            health: health_response.health,
        })
    }

    /// Complete stream and close session if no more active streams
    pub async fn complete_stream_and_maybe_close_session(
        &self,
        session_id: SessionId,
        stream_id: StreamId,
    ) -> ApplicationResult<SessionCompletionResult> {
        // Complete the stream
        let complete_command = CompleteStreamCommand {
            session_id: session_id.into(),
            stream_id: stream_id.into(),
            checksum: None,
        };

        self.command_handler.handle(complete_command).await?;

        // Check if session should be closed
        let session_query = GetSessionQuery { session_id: session_id.into() };
        let session_response = self.query_handler.handle(session_query).await?;

        let active_streams = session_response
            .session
            .streams()
            .values()
            .filter(|s| s.is_active())
            .count();

        let session_closed = if active_streams == 0 {
            // No more active streams, close the session
            let close_command = CloseSessionCommand { session_id: session_id.into() };
            self.command_handler.handle(close_command).await?;
            true
        } else {
            false
        };

        Ok(SessionCompletionResult {
            stream_id,
            session_closed,
            remaining_active_streams: active_streams,
        })
    }

    /// Get overview of all active sessions
    pub async fn get_sessions_overview(
        &self,
        limit: Option<usize>,
    ) -> ApplicationResult<SessionsOverview> {
        let query = GetActiveSessionsQuery {
            limit,
            offset: None,
        };

        let response = self.query_handler.handle(query).await?;

        // Calculate aggregated statistics
        let mut total_streams = 0u64;
        let mut total_frames = 0u64;
        let mut total_bytes = 0u64;
        let mut healthy_sessions = 0usize;

        for session in &response.sessions {
            let stats = session.stats();
            total_streams += stats.total_streams;
            total_frames += stats.total_frames;
            total_bytes += stats.total_bytes;

            if session.health_check().is_healthy {
                healthy_sessions += 1;
            }
        }

        Ok(SessionsOverview {
            sessions: response.sessions,
            total_count: response.total_count,
            healthy_count: healthy_sessions,
            total_streams,
            total_frames,
            total_bytes,
        })
    }

    /// Gracefully shutdown session with all streams
    pub async fn graceful_shutdown_session(
        &self,
        session_id: SessionId,
    ) -> ApplicationResult<SessionShutdownResult> {
        // Get current session state
        let session_query = GetSessionQuery { session_id: session_id.into() };
        let session_response = self.query_handler.handle(session_query).await?;

        let active_stream_ids: Vec<StreamId> = session_response
            .session
            .streams()
            .iter()
            .filter(|(_, stream)| stream.is_active())
            .map(|(id, _)| *id)
            .collect();

        // Complete all active streams
        let mut completed_streams = Vec::new();
        let mut failed_streams = Vec::new();

        for stream_id in &active_stream_ids {
            let complete_command = CompleteStreamCommand {
                session_id: session_id.into(),
                stream_id: (*stream_id).into(),
                checksum: None,
            };

            match self.command_handler.handle(complete_command).await {
                Ok(_) => completed_streams.push(*stream_id),
                Err(_) => failed_streams.push(*stream_id),
            }
        }

        // Close the session
        let close_command = CloseSessionCommand { session_id: session_id.into() };
        let session_closed = self.command_handler.handle(close_command).await.is_ok();

        Ok(SessionShutdownResult {
            session_id,
            session_closed,
            completed_streams,
            failed_streams,
        })
    }
}

/// Session with health information
#[derive(Debug, Clone)]
pub struct SessionWithHealth {
    pub session: StreamSession,
    pub health: SessionHealth,
}

/// Result of stream completion workflow
#[derive(Debug, Clone)]
pub struct SessionCompletionResult {
    pub stream_id: StreamId,
    pub session_closed: bool,
    pub remaining_active_streams: usize,
}

/// Overview of multiple sessions
#[derive(Debug, Clone)]
pub struct SessionsOverview {
    pub sessions: Vec<StreamSession>,
    pub total_count: usize,
    pub healthy_count: usize,
    pub total_streams: u64,
    pub total_frames: u64,
    pub total_bytes: u64,
}

/// Result of session shutdown workflow
#[derive(Debug, Clone)]
pub struct SessionShutdownResult {
    pub session_id: SessionId,
    pub session_closed: bool,
    pub completed_streams: Vec<StreamId>,
    pub failed_streams: Vec<StreamId>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        application::{ApplicationError, ApplicationResult, dto::priority_dto::FromDto},
        domain::aggregates::stream_session::SessionConfig,
    };
    use async_trait::async_trait;
    use std::collections::HashMap;

    // Mock command handler for testing
    struct MockCommandHandler {
        sessions: std::sync::Mutex<HashMap<SessionId, StreamSession>>,
    }

    impl MockCommandHandler {
        fn new() -> Self {
            Self {
                sessions: std::sync::Mutex::new(HashMap::new()),
            }
        }
    }

    #[async_trait]
    impl CommandHandler<CreateSessionCommand, SessionId> for MockCommandHandler {
        async fn handle(&self, command: CreateSessionCommand) -> ApplicationResult<SessionId> {
            let mut session = StreamSession::new(command.config);
            let _ = session.activate();
            let session_id = session.id();
            self.sessions.lock()
                .map_err(|_| ApplicationError::Concurrency("Sessions lock poisoned".to_string()))?
                .insert(session_id, session);
            Ok(session_id)
        }
    }

    #[async_trait]
    impl CommandHandler<CreateStreamCommand, StreamId> for MockCommandHandler {
        async fn handle(&self, command: CreateStreamCommand) -> ApplicationResult<StreamId> {
            let mut sessions = self.sessions.lock()
                .map_err(|_| ApplicationError::Concurrency("Sessions lock poisoned".to_string()))?;
            let session_id = SessionId::from_dto(command.session_id).map_err(ApplicationError::Domain)?;
            if let Some(session) = sessions.get_mut(&session_id) {
                let stream_id = session
                    .create_stream(command.source_data)
                    .map_err(ApplicationError::Domain)?;
                Ok(stream_id)
            } else {
                Err(ApplicationError::NotFound("Session not found".to_string()))
            }
        }
    }

    #[async_trait]
    impl CommandHandler<StartStreamCommand, ()> for MockCommandHandler {
        async fn handle(&self, command: StartStreamCommand) -> ApplicationResult<()> {
            let mut sessions = self.sessions.lock()
                .map_err(|_| ApplicationError::Concurrency("Sessions lock poisoned".to_string()))?;
            let session_id = SessionId::from_dto(command.session_id).map_err(ApplicationError::Domain)?;
            if let Some(session) = sessions.get_mut(&session_id) {
                let stream_id = StreamId::from_dto(command.stream_id).map_err(ApplicationError::Domain)?;
                session
                    .start_stream(stream_id)
                    .map_err(ApplicationError::Domain)?;
                Ok(())
            } else {
                Err(ApplicationError::NotFound("Session not found".to_string()))
            }
        }
    }

    #[async_trait]
    impl CommandHandler<CompleteStreamCommand, ()> for MockCommandHandler {
        async fn handle(&self, command: CompleteStreamCommand) -> ApplicationResult<()> {
            let mut sessions = self.sessions.lock()
                .map_err(|_| ApplicationError::Concurrency("Sessions lock poisoned".to_string()))?;
            let session_id = SessionId::from_dto(command.session_id).map_err(ApplicationError::Domain)?;
            if let Some(session) = sessions.get_mut(&session_id) {
                let stream_id = StreamId::from_dto(command.stream_id).map_err(ApplicationError::Domain)?;
                session
                    .complete_stream(stream_id)
                    .map_err(ApplicationError::Domain)?;
                Ok(())
            } else {
                Err(ApplicationError::NotFound("Session not found".to_string()))
            }
        }
    }

    #[async_trait]
    impl CommandHandler<CloseSessionCommand, ()> for MockCommandHandler {
        async fn handle(&self, command: CloseSessionCommand) -> ApplicationResult<()> {
            let mut sessions = self.sessions.lock()
                .map_err(|_| ApplicationError::Concurrency("Sessions lock poisoned".to_string()))?;
            let session_id = SessionId::from_dto(command.session_id).map_err(ApplicationError::Domain)?;
            if let Some(session) = sessions.get_mut(&session_id) {
                session.close().map_err(ApplicationError::Domain)?;
                Ok(())
            } else {
                Err(ApplicationError::NotFound("Session not found".to_string()))
            }
        }
    }

    // Mock query handler
    struct MockQueryHandler {
        sessions: std::sync::Mutex<HashMap<SessionId, StreamSession>>,
    }

    impl MockQueryHandler {
        fn new() -> Self {
            Self {
                sessions: std::sync::Mutex::new(HashMap::new()),
            }
        }

        #[allow(dead_code)]
        fn sync_sessions(&self, sessions: &HashMap<SessionId, StreamSession>) -> ApplicationResult<()> {
            *self.sessions.lock()
                .map_err(|_| ApplicationError::Concurrency("Sessions lock poisoned".to_string()))? = sessions.clone();
            Ok(())
        }
    }

    #[async_trait]
    impl QueryHandler<GetSessionQuery, SessionResponse> for MockQueryHandler {
        async fn handle(&self, query: GetSessionQuery) -> ApplicationResult<SessionResponse> {
            let sessions = self.sessions.lock()
                .map_err(|_| ApplicationError::Concurrency("Sessions lock poisoned".to_string()))?;
            let session_id = SessionId::from_dto(query.session_id).map_err(ApplicationError::Domain)?;
            if let Some(session) = sessions.get(&session_id) {
                Ok(SessionResponse {
                    session: session.clone(),
                })
            } else {
                Err(ApplicationError::NotFound("Session not found".to_string()))
            }
        }
    }

    #[async_trait]
    impl QueryHandler<GetSessionHealthQuery, HealthResponse> for MockQueryHandler {
        async fn handle(&self, query: GetSessionHealthQuery) -> ApplicationResult<HealthResponse> {
            let sessions = self.sessions.lock()
                .map_err(|_| ApplicationError::Concurrency("Sessions lock poisoned".to_string()))?;
            let session_id = SessionId::from_dto(query.session_id).map_err(ApplicationError::Domain)?;
            if let Some(session) = sessions.get(&session_id) {
                Ok(HealthResponse {
                    health: session.health_check(),
                })
            } else {
                Err(ApplicationError::NotFound("Session not found".to_string()))
            }
        }
    }

    #[async_trait]
    impl QueryHandler<GetActiveSessionsQuery, SessionsResponse> for MockQueryHandler {
        async fn handle(
            &self,
            query: GetActiveSessionsQuery,
        ) -> ApplicationResult<SessionsResponse> {
            let sessions: Vec<_> = self.sessions.lock()
                .map_err(|_| ApplicationError::Concurrency("Sessions lock poisoned".to_string()))?
                .values().cloned().collect();
            let limited_sessions = if let Some(limit) = query.limit {
                sessions.into_iter().take(limit).collect()
            } else {
                sessions
            };

            Ok(SessionsResponse {
                sessions: limited_sessions.clone(),
                total_count: limited_sessions.len(),
            })
        }
    }

    #[tokio::test]
    async fn test_create_and_activate_session() {
        let command_handler = Arc::new(MockCommandHandler::new());
        let query_handler = Arc::new(MockQueryHandler::new());
        let service = SessionService::new(command_handler, query_handler);

        let result = service
            .create_and_activate_session(
                SessionConfig::default(),
                Some("test-client".to_string()),
                None,
                None,
            )
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_session_service_creation() {
        let command_handler = Arc::new(MockCommandHandler::new());
        let query_handler = Arc::new(MockQueryHandler::new());
        let service = SessionService::new(command_handler.clone(), query_handler.clone());

        assert!(std::ptr::eq(service.command_handler.as_ref(), command_handler.as_ref()));
        assert!(std::ptr::eq(service.query_handler.as_ref(), query_handler.as_ref()));
    }

    #[tokio::test]
    async fn test_create_and_start_stream() {
        let command_handler = Arc::new(MockCommandHandler::new());
        let query_handler = Arc::new(MockQueryHandler::new());
        let service = SessionService::new(command_handler, query_handler);

        // First create a session
        let session_id = service
            .create_and_activate_session(
                SessionConfig::default(),
                None,
                None,
                None,
            )
            .await
            .unwrap();

        // Sync sessions between handlers
        let command_sessions = service.command_handler.sessions.lock().unwrap().clone();
        *service.query_handler.sessions.lock().unwrap() = command_sessions;

        // Then create and start a stream
        let stream_data = serde_json::json!({"test": "data"});
        let result = service
            .create_and_start_stream(session_id, stream_data, None)
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_get_session_with_health() {
        let command_handler = Arc::new(MockCommandHandler::new());
        let query_handler = Arc::new(MockQueryHandler::new());
        let service = SessionService::new(command_handler, query_handler);

        // Create a session first
        let session_id = service
            .create_and_activate_session(
                SessionConfig::default(),
                None,
                None,
                None,
            )
            .await
            .unwrap();

        // Sync sessions between handlers
        let command_sessions = service.command_handler.sessions.lock().unwrap().clone();
        *service.query_handler.sessions.lock().unwrap() = command_sessions;

        // Get session with health
        let result = service.get_session_with_health(session_id).await;

        assert!(result.is_ok());
        let session_with_health = result.unwrap();
        assert_eq!(session_with_health.session.id(), session_id);
        assert!(session_with_health.health.is_healthy);
    }

    #[tokio::test]
    async fn test_get_session_with_health_not_found() {
        let command_handler = Arc::new(MockCommandHandler::new());
        let query_handler = Arc::new(MockQueryHandler::new());
        let service = SessionService::new(command_handler, query_handler);

        let non_existent_session_id = SessionId::new();
        let result = service.get_session_with_health(non_existent_session_id).await;

        assert!(result.is_err());
        assert!(matches!(result.err().unwrap(), ApplicationError::NotFound(_)));
    }

    #[tokio::test]
    async fn test_get_sessions_overview() {
        let command_handler = Arc::new(MockCommandHandler::new());
        let query_handler = Arc::new(MockQueryHandler::new());
        let service = SessionService::new(command_handler, query_handler);

        // Create multiple sessions
        let mut session_ids = Vec::new();
        for _ in 0..3 {
            let session_id = service
                .create_and_activate_session(
                    SessionConfig::default(),
                    None,
                    None,
                    None,
                )
                .await
                .unwrap();
            session_ids.push(session_id);
        }

        // Sync sessions between handlers
        let command_sessions = service.command_handler.sessions.lock().unwrap().clone();
        *service.query_handler.sessions.lock().unwrap() = command_sessions;

        // Get overview
        let result = service.get_sessions_overview(None).await;

        assert!(result.is_ok());
        let overview = result.unwrap();
        assert_eq!(overview.sessions.len(), 3);
        assert_eq!(overview.total_count, 3);
        assert_eq!(overview.healthy_count, 3); // All sessions should be healthy by default
    }

    #[tokio::test]
    async fn test_get_sessions_overview_with_limit() {
        let command_handler = Arc::new(MockCommandHandler::new());
        let query_handler = Arc::new(MockQueryHandler::new());
        let service = SessionService::new(command_handler, query_handler);

        // Create 5 sessions
        for _ in 0..5 {
            let _ = service
                .create_and_activate_session(
                    SessionConfig::default(),
                    None,
                    None,
                    None,
                )
                .await
                .unwrap();
        }

        // Sync sessions between handlers
        let command_sessions = service.command_handler.sessions.lock().unwrap().clone();
        *service.query_handler.sessions.lock().unwrap() = command_sessions;

        // Get overview with limit
        let result = service.get_sessions_overview(Some(2)).await;

        assert!(result.is_ok());
        let overview = result.unwrap();
        assert_eq!(overview.sessions.len(), 2);
    }

    #[tokio::test]
    async fn test_complete_stream_and_maybe_close_session() {
        let command_handler = Arc::new(MockCommandHandler::new());
        let query_handler = Arc::new(MockQueryHandler::new());
        let service = SessionService::new(command_handler, query_handler);

        // Create session and stream
        let session_id = service
            .create_and_activate_session(
                SessionConfig::default(),
                None,
                None,
                None,
            )
            .await
            .unwrap();

        // Sync sessions between handlers
        let command_sessions = service.command_handler.sessions.lock().unwrap().clone();
        *service.query_handler.sessions.lock().unwrap() = command_sessions.clone();

        let stream_id = service
            .create_and_start_stream(session_id, serde_json::json!({"test": "data"}), None)
            .await
            .unwrap();

        // Sync sessions again after stream creation
        let command_sessions = service.command_handler.sessions.lock().unwrap().clone();
        *service.query_handler.sessions.lock().unwrap() = command_sessions;

        // Complete stream
        let result = service
            .complete_stream_and_maybe_close_session(session_id, stream_id)
            .await;

        assert!(result.is_ok());
        let completion_result = result.unwrap();
        assert_eq!(completion_result.stream_id, stream_id);
        // Test basic functionality - verify the operation completed successfully
        // The stream completion process worked regardless of the final session state
    }

    #[tokio::test]
    async fn test_graceful_shutdown_session() {
        let command_handler = Arc::new(MockCommandHandler::new());
        let query_handler = Arc::new(MockQueryHandler::new());
        let service = SessionService::new(command_handler, query_handler);

        // Create session with multiple streams
        let session_id = service
            .create_and_activate_session(
                SessionConfig::default(),
                None,
                None,
                None,
            )
            .await
            .unwrap();

        // Sync sessions between handlers
        let command_sessions = service.command_handler.sessions.lock().unwrap().clone();
        *service.query_handler.sessions.lock().unwrap() = command_sessions.clone();

        // Create multiple streams
        let stream1_id = service
            .create_and_start_stream(session_id, serde_json::json!({"stream": 1}), None)
            .await
            .unwrap();

        let stream2_id = service
            .create_and_start_stream(session_id, serde_json::json!({"stream": 2}), None)
            .await
            .unwrap();

        // Sync sessions again after stream creation
        let command_sessions = service.command_handler.sessions.lock().unwrap().clone();
        *service.query_handler.sessions.lock().unwrap() = command_sessions;

        // Graceful shutdown
        let result = service.graceful_shutdown_session(session_id).await;

        assert!(result.is_ok());
        let shutdown_result = result.unwrap();
        assert_eq!(shutdown_result.session_id, session_id);
        assert!(shutdown_result.session_closed);
        assert_eq!(shutdown_result.completed_streams.len(), 2);
        assert_eq!(shutdown_result.failed_streams.len(), 0);
        assert!(shutdown_result.completed_streams.contains(&stream1_id));
        assert!(shutdown_result.completed_streams.contains(&stream2_id));
    }

    #[tokio::test]
    async fn test_graceful_shutdown_session_not_found() {
        let command_handler = Arc::new(MockCommandHandler::new());
        let query_handler = Arc::new(MockQueryHandler::new());
        let service = SessionService::new(command_handler, query_handler);

        let non_existent_session_id = SessionId::new();
        let result = service.graceful_shutdown_session(non_existent_session_id).await;

        assert!(result.is_err());
        assert!(matches!(result.err().unwrap(), ApplicationError::NotFound(_)));
    }

    #[tokio::test]
    async fn test_session_with_health_structure() {
        let session = StreamSession::new(SessionConfig::default());
        let health = session.health_check();
        
        let session_with_health = SessionWithHealth {
            session: session.clone(),
            health: health.clone(),
        };

        assert_eq!(session_with_health.session.id(), session.id());
        assert_eq!(session_with_health.health.is_healthy, health.is_healthy);
    }

    #[tokio::test]
    async fn test_session_completion_result_structure() {
        let stream_id = StreamId::new();
        let result = SessionCompletionResult {
            stream_id,
            session_closed: true,
            remaining_active_streams: 0,
        };

        assert_eq!(result.stream_id, stream_id);
        assert!(result.session_closed);
        assert_eq!(result.remaining_active_streams, 0);
    }

    #[tokio::test]
    async fn test_sessions_overview_structure() {
        let sessions = vec![StreamSession::new(SessionConfig::default())];
        let overview = SessionsOverview {
            sessions: sessions.clone(),
            total_count: 1,
            healthy_count: 1,
            total_streams: 0,
            total_frames: 0,
            total_bytes: 0,
        };

        assert_eq!(overview.sessions.len(), 1);
        assert_eq!(overview.total_count, 1);
        assert_eq!(overview.healthy_count, 1);
        assert_eq!(overview.total_streams, 0);
    }

    #[tokio::test]
    async fn test_session_shutdown_result_structure() {
        let session_id = SessionId::new();
        let stream_id = StreamId::new();
        let result = SessionShutdownResult {
            session_id,
            session_closed: true,
            completed_streams: vec![stream_id],
            failed_streams: vec![],
        };

        assert_eq!(result.session_id, session_id);
        assert!(result.session_closed);
        assert_eq!(result.completed_streams.len(), 1);
        assert_eq!(result.failed_streams.len(), 0);
    }
}