this-rs 0.0.9

Framework for building complex multi-entity REST and GraphQL APIs with many relationships
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
//! gRPC Event Service implementation — server-streaming real-time events
//!
//! Subscribes to the framework's `EventBus` (the same broadcast channel used by
//! WebSocket) and streams matching events to gRPC clients. Filters from the
//! `SubscribeRequest` are applied server-side (AND logic, absent = wildcard).
//!
//! ## Architecture
//!
//! ```text
//! REST/GraphQL Handler → EventBus::publish()
//!//!                      broadcast channel
//!                        ↓           ↓
//!              WebSocket Manager   EventServiceImpl::subscribe()
//!                                     ↓ (filter)
//!                                  gRPC stream → client
//! ```

use super::convert::json_to_struct;
use super::proto::{EventResponse, SubscribeRequest, event_service_server::EventService};
use crate::core::events::{EntityEvent, EventEnvelope, FrameworkEvent, LinkEvent};
use crate::server::host::ServerHost;
use std::pin::Pin;
use std::sync::Arc;
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;
use tonic::{Request, Response, Status};
use uuid::Uuid;

/// gRPC Event Service implementation
///
/// Subscribes to the framework's `EventBus` and streams events to gRPC clients.
/// Each `Subscribe` call creates an independent broadcast receiver, filters
/// events according to `SubscribeRequest`, and forwards matching events as
/// `EventResponse` messages on the server-streaming response.
pub struct EventServiceImpl {
    host: Arc<ServerHost>,
}

impl EventServiceImpl {
    /// Create a new `EventServiceImpl` from a `ServerHost`
    pub fn new(host: Arc<ServerHost>) -> Self {
        Self { host }
    }
}

// ---------------------------------------------------------------------------
// Filter logic
// ---------------------------------------------------------------------------

/// Check if an event matches the subscribe request filters.
///
/// All fields are AND conditions. An absent (empty) field means "match any".
fn matches_filter(event: &FrameworkEvent, filter: &SubscribeRequest) -> bool {
    // Filter by kind ("entity" or "link")
    if let Some(ref kind) = filter.kind
        && !kind.is_empty()
        && event.event_kind() != kind
    {
        return false;
    }

    // Filter by entity_type
    if let Some(ref entity_type) = filter.entity_type
        && !entity_type.is_empty()
    {
        match event.entity_type() {
            Some(et) if et == entity_type => {}
            Some(_) => return false,
            None => return false,
        }
    }

    // Filter by entity_id
    if let Some(ref entity_id) = filter.entity_id
        && !entity_id.is_empty()
    {
        let parsed = entity_id.parse::<Uuid>().ok();
        match (parsed, event.entity_id()) {
            (Some(filter_id), Some(event_id)) if filter_id == event_id => {}
            _ => return false,
        }
    }

    // Filter by event_type (action: "created", "updated", "deleted")
    if let Some(ref event_type) = filter.event_type
        && !event_type.is_empty()
        && event.action() != event_type
    {
        return false;
    }

    // Filter by link_type (only relevant for link events)
    if let Some(ref link_type) = filter.link_type
        && !link_type.is_empty()
    {
        match extract_link_type(event) {
            Some(lt) if lt == link_type => {}
            Some(_) => return false,
            None => return false,
        }
    }

    true
}

/// Extract the link_type from a `FrameworkEvent`, if it's a link event.
fn extract_link_type(event: &FrameworkEvent) -> Option<&str> {
    match event {
        FrameworkEvent::Link(link) => match link {
            LinkEvent::Created { link_type, .. } | LinkEvent::Deleted { link_type, .. } => {
                Some(link_type)
            }
        },
        FrameworkEvent::Entity(_) => None,
    }
}

// ---------------------------------------------------------------------------
// Envelope → EventResponse conversion
// ---------------------------------------------------------------------------

/// Convert an `EventEnvelope` into a proto `EventResponse`.
fn envelope_to_response(envelope: &EventEnvelope) -> EventResponse {
    let event = &envelope.event;

    let (entity_type, entity_id, link_type, source_id, target_id, data, metadata) = match event {
        FrameworkEvent::Entity(e) => match e {
            EntityEvent::Created {
                entity_type,
                entity_id,
                data,
            } => (
                entity_type.clone(),
                entity_id.to_string(),
                String::new(),
                String::new(),
                String::new(),
                Some(json_to_struct(data)),
                None,
            ),
            EntityEvent::Updated {
                entity_type,
                entity_id,
                data,
            } => (
                entity_type.clone(),
                entity_id.to_string(),
                String::new(),
                String::new(),
                String::new(),
                Some(json_to_struct(data)),
                None,
            ),
            EntityEvent::Deleted {
                entity_type,
                entity_id,
            } => (
                entity_type.clone(),
                entity_id.to_string(),
                String::new(),
                String::new(),
                String::new(),
                None,
                None,
            ),
        },
        FrameworkEvent::Link(l) => match l {
            LinkEvent::Created {
                link_type,
                link_id,
                source_id,
                target_id,
                metadata,
            } => (
                String::new(),
                link_id.to_string(),
                link_type.clone(),
                source_id.to_string(),
                target_id.to_string(),
                None,
                metadata.as_ref().map(json_to_struct),
            ),
            LinkEvent::Deleted {
                link_type,
                link_id,
                source_id,
                target_id,
            } => (
                String::new(),
                link_id.to_string(),
                link_type.clone(),
                source_id.to_string(),
                target_id.to_string(),
                None,
                None,
            ),
        },
    };

    EventResponse {
        event_id: envelope.id.to_string(),
        event_kind: event.event_kind().to_string(),
        event_type: event.action().to_string(),
        entity_type,
        entity_id,
        link_type,
        source_id,
        target_id,
        data,
        metadata,
        timestamp: envelope.timestamp.to_rfc3339(),
        seq_no: envelope.seq_no.unwrap_or(0),
    }
}

// ---------------------------------------------------------------------------
// gRPC trait implementation
// ---------------------------------------------------------------------------

type SubscribeStream =
    Pin<Box<dyn tokio_stream::Stream<Item = Result<EventResponse, Status>> + Send>>;

#[tonic::async_trait]
impl EventService for EventServiceImpl {
    type SubscribeStream = SubscribeStream;

    async fn subscribe(
        &self,
        request: Request<SubscribeRequest>,
    ) -> Result<Response<Self::SubscribeStream>, Status> {
        let filter = request.into_inner();

        // Get the EventBus — if not configured, streaming is unavailable
        let event_bus = self
            .host
            .event_bus()
            .ok_or_else(|| {
                Status::unavailable(
                    "EventBus not configured — real-time streaming is not available",
                )
            })?
            .clone();

        // Subscribe to the broadcast channel
        let mut rx = event_bus.subscribe();

        // Channel to stream events to the gRPC response
        // Buffer of 64 — enough headroom for bursts without excessive memory
        let (tx, client_rx) = mpsc::channel::<Result<EventResponse, Status>>(64);

        // Spawn background task: receive from broadcast → filter → send to gRPC stream
        tokio::spawn(async move {
            loop {
                match rx.recv().await {
                    Ok(envelope) => {
                        if matches_filter(&envelope.event, &filter) {
                            let response = envelope_to_response(&envelope);
                            // If the client disconnected, tx.send() returns Err → break
                            if tx.send(Ok(response)).await.is_err() {
                                tracing::debug!("gRPC event stream: client disconnected, closing");
                                break;
                            }
                        }
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(count)) => {
                        tracing::warn!("gRPC event stream: lagged by {} events, skipping", count);
                        // Continue — the client misses some events but the stream stays alive
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Closed) => {
                        tracing::info!("gRPC event stream: EventBus closed, ending stream");
                        break;
                    }
                }
            }
        });

        let stream = ReceiverStream::new(client_rx);
        Ok(Response::new(Box::pin(stream) as Self::SubscribeStream))
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::events::EventBus;
    use serde_json::json;

    // === Filter tests ===

    #[test]
    fn test_filter_empty_matches_everything() {
        let filter = SubscribeRequest {
            entity_type: None,
            entity_id: None,
            event_type: None,
            kind: None,
            link_type: None,
        };

        let entity = FrameworkEvent::Entity(EntityEvent::Created {
            entity_type: "user".to_string(),
            entity_id: Uuid::new_v4(),
            data: json!({}),
        });

        let link = FrameworkEvent::Link(LinkEvent::Created {
            link_type: "follow".to_string(),
            link_id: Uuid::new_v4(),
            source_id: Uuid::new_v4(),
            target_id: Uuid::new_v4(),
            metadata: None,
        });

        assert!(matches_filter(&entity, &filter));
        assert!(matches_filter(&link, &filter));
    }

    #[test]
    fn test_filter_by_entity_type() {
        let filter = SubscribeRequest {
            entity_type: Some("user".to_string()),
            entity_id: None,
            event_type: None,
            kind: None,
            link_type: None,
        };

        let user = FrameworkEvent::Entity(EntityEvent::Created {
            entity_type: "user".to_string(),
            entity_id: Uuid::new_v4(),
            data: json!({}),
        });

        let capture = FrameworkEvent::Entity(EntityEvent::Created {
            entity_type: "capture".to_string(),
            entity_id: Uuid::new_v4(),
            data: json!({}),
        });

        assert!(matches_filter(&user, &filter));
        assert!(!matches_filter(&capture, &filter));
    }

    #[test]
    fn test_filter_by_kind_entity() {
        let filter = SubscribeRequest {
            entity_type: None,
            entity_id: None,
            event_type: None,
            kind: Some("entity".to_string()),
            link_type: None,
        };

        let entity = FrameworkEvent::Entity(EntityEvent::Created {
            entity_type: "user".to_string(),
            entity_id: Uuid::new_v4(),
            data: json!({}),
        });

        let link = FrameworkEvent::Link(LinkEvent::Created {
            link_type: "follow".to_string(),
            link_id: Uuid::new_v4(),
            source_id: Uuid::new_v4(),
            target_id: Uuid::new_v4(),
            metadata: None,
        });

        assert!(matches_filter(&entity, &filter));
        assert!(!matches_filter(&link, &filter));
    }

    #[test]
    fn test_filter_by_kind_link() {
        let filter = SubscribeRequest {
            entity_type: None,
            entity_id: None,
            event_type: None,
            kind: Some("link".to_string()),
            link_type: None,
        };

        let entity = FrameworkEvent::Entity(EntityEvent::Created {
            entity_type: "user".to_string(),
            entity_id: Uuid::new_v4(),
            data: json!({}),
        });

        let link = FrameworkEvent::Link(LinkEvent::Created {
            link_type: "follow".to_string(),
            link_id: Uuid::new_v4(),
            source_id: Uuid::new_v4(),
            target_id: Uuid::new_v4(),
            metadata: None,
        });

        assert!(!matches_filter(&entity, &filter));
        assert!(matches_filter(&link, &filter));
    }

    #[test]
    fn test_filter_by_event_type() {
        let filter = SubscribeRequest {
            entity_type: None,
            entity_id: None,
            event_type: Some("deleted".to_string()),
            kind: None,
            link_type: None,
        };

        let created = FrameworkEvent::Entity(EntityEvent::Created {
            entity_type: "user".to_string(),
            entity_id: Uuid::new_v4(),
            data: json!({}),
        });

        let deleted = FrameworkEvent::Entity(EntityEvent::Deleted {
            entity_type: "user".to_string(),
            entity_id: Uuid::new_v4(),
        });

        assert!(!matches_filter(&created, &filter));
        assert!(matches_filter(&deleted, &filter));
    }

    #[test]
    fn test_filter_by_link_type() {
        let filter = SubscribeRequest {
            entity_type: None,
            entity_id: None,
            event_type: None,
            kind: None,
            link_type: Some("follow".to_string()),
        };

        let follow = FrameworkEvent::Link(LinkEvent::Created {
            link_type: "follow".to_string(),
            link_id: Uuid::new_v4(),
            source_id: Uuid::new_v4(),
            target_id: Uuid::new_v4(),
            metadata: None,
        });

        let like = FrameworkEvent::Link(LinkEvent::Created {
            link_type: "like".to_string(),
            link_id: Uuid::new_v4(),
            source_id: Uuid::new_v4(),
            target_id: Uuid::new_v4(),
            metadata: None,
        });

        // Entity events should NOT match a link_type filter
        let entity = FrameworkEvent::Entity(EntityEvent::Created {
            entity_type: "user".to_string(),
            entity_id: Uuid::new_v4(),
            data: json!({}),
        });

        assert!(matches_filter(&follow, &filter));
        assert!(!matches_filter(&like, &filter));
        assert!(!matches_filter(&entity, &filter));
    }

    #[test]
    fn test_filter_combined() {
        let filter = SubscribeRequest {
            entity_type: Some("user".to_string()),
            entity_id: None,
            event_type: Some("created".to_string()),
            kind: Some("entity".to_string()),
            link_type: None,
        };

        let user_created = FrameworkEvent::Entity(EntityEvent::Created {
            entity_type: "user".to_string(),
            entity_id: Uuid::new_v4(),
            data: json!({}),
        });

        let user_deleted = FrameworkEvent::Entity(EntityEvent::Deleted {
            entity_type: "user".to_string(),
            entity_id: Uuid::new_v4(),
        });

        let capture_created = FrameworkEvent::Entity(EntityEvent::Created {
            entity_type: "capture".to_string(),
            entity_id: Uuid::new_v4(),
            data: json!({}),
        });

        assert!(matches_filter(&user_created, &filter));
        assert!(!matches_filter(&user_deleted, &filter));
        assert!(!matches_filter(&capture_created, &filter));
    }

    #[test]
    fn test_filter_by_entity_id() {
        let target = Uuid::new_v4();
        let other = Uuid::new_v4();

        let filter = SubscribeRequest {
            entity_type: None,
            entity_id: Some(target.to_string()),
            event_type: None,
            kind: None,
            link_type: None,
        };

        let matching = FrameworkEvent::Entity(EntityEvent::Updated {
            entity_type: "user".to_string(),
            entity_id: target,
            data: json!({}),
        });

        let not_matching = FrameworkEvent::Entity(EntityEvent::Updated {
            entity_type: "user".to_string(),
            entity_id: other,
            data: json!({}),
        });

        assert!(matches_filter(&matching, &filter));
        assert!(!matches_filter(&not_matching, &filter));
    }

    // === Conversion tests ===

    #[test]
    fn test_envelope_to_response_entity_created() {
        let entity_id = Uuid::new_v4();
        let envelope = EventEnvelope::new(FrameworkEvent::Entity(EntityEvent::Created {
            entity_type: "user".to_string(),
            entity_id,
            data: json!({"name": "Alice"}),
        }));

        let resp = envelope_to_response(&envelope);

        assert_eq!(resp.event_id, envelope.id.to_string());
        assert_eq!(resp.event_kind, "entity");
        assert_eq!(resp.event_type, "created");
        assert_eq!(resp.entity_type, "user");
        assert_eq!(resp.entity_id, entity_id.to_string());
        assert!(resp.link_type.is_empty());
        assert!(resp.source_id.is_empty());
        assert!(resp.target_id.is_empty());
        assert!(resp.data.is_some());
        assert!(resp.metadata.is_none());
    }

    #[test]
    fn test_envelope_to_response_link_created() {
        let link_id = Uuid::new_v4();
        let source = Uuid::new_v4();
        let target = Uuid::new_v4();

        let envelope = EventEnvelope::new(FrameworkEvent::Link(LinkEvent::Created {
            link_type: "follow".to_string(),
            link_id,
            source_id: source,
            target_id: target,
            metadata: Some(json!({"via": "mobile"})),
        }));

        let resp = envelope_to_response(&envelope);

        assert_eq!(resp.event_kind, "link");
        assert_eq!(resp.event_type, "created");
        assert!(resp.entity_type.is_empty());
        assert_eq!(resp.entity_id, link_id.to_string());
        assert_eq!(resp.link_type, "follow");
        assert_eq!(resp.source_id, source.to_string());
        assert_eq!(resp.target_id, target.to_string());
        assert!(resp.data.is_none());
        assert!(resp.metadata.is_some());
    }

    #[test]
    fn test_envelope_to_response_entity_deleted() {
        let entity_id = Uuid::new_v4();
        let envelope = EventEnvelope::new(FrameworkEvent::Entity(EntityEvent::Deleted {
            entity_type: "capture".to_string(),
            entity_id,
        }));

        let resp = envelope_to_response(&envelope);

        assert_eq!(resp.event_kind, "entity");
        assert_eq!(resp.event_type, "deleted");
        assert_eq!(resp.entity_type, "capture");
        assert!(resp.data.is_none());
        assert!(resp.metadata.is_none());
    }

    // === Integration test — full subscribe flow ===

    #[tokio::test]
    async fn test_event_service_subscribe_receives_matching_events() {
        use crate::server::host::ServerHost;
        use tokio_stream::StreamExt;

        let event_bus = EventBus::new(64);

        // Create a minimal ServerHost with an EventBus
        let host = ServerHost::minimal_for_test().with_event_bus(event_bus.clone());
        let host = Arc::new(host);

        let svc = EventServiceImpl::new(host);

        // Subscribe to "user" entity events only
        let request = Request::new(SubscribeRequest {
            entity_type: Some("user".to_string()),
            entity_id: None,
            event_type: None,
            kind: None,
            link_type: None,
        });

        let response = svc.subscribe(request).await.unwrap();
        let mut stream = response.into_inner();

        // Publish a user event (should match)
        let user_id = Uuid::new_v4();
        event_bus.publish(FrameworkEvent::Entity(EntityEvent::Created {
            entity_type: "user".to_string(),
            entity_id: user_id,
            data: json!({"name": "Alice"}),
        }));

        // Publish a capture event (should NOT match)
        event_bus.publish(FrameworkEvent::Entity(EntityEvent::Created {
            entity_type: "capture".to_string(),
            entity_id: Uuid::new_v4(),
            data: json!({}),
        }));

        // Publish a link event (should NOT match)
        event_bus.publish(FrameworkEvent::Link(LinkEvent::Created {
            link_type: "follow".to_string(),
            link_id: Uuid::new_v4(),
            source_id: Uuid::new_v4(),
            target_id: Uuid::new_v4(),
            metadata: None,
        }));

        // Should receive exactly 1 event (the user one)
        let msg = tokio::time::timeout(std::time::Duration::from_millis(100), stream.next())
            .await
            .expect("timed out waiting for event")
            .expect("stream ended unexpectedly")
            .expect("received error");

        assert_eq!(msg.event_kind, "entity");
        assert_eq!(msg.event_type, "created");
        assert_eq!(msg.entity_type, "user");
        assert_eq!(msg.entity_id, user_id.to_string());

        // No more matching events should arrive
        let timeout_result =
            tokio::time::timeout(std::time::Duration::from_millis(50), stream.next()).await;
        assert!(
            timeout_result.is_err(),
            "should time out — no more matching events"
        );
    }

    #[tokio::test]
    async fn test_event_service_wildcard_receives_all() {
        use crate::server::host::ServerHost;
        use tokio_stream::StreamExt;

        let event_bus = EventBus::new(64);
        let host = Arc::new(ServerHost::minimal_for_test().with_event_bus(event_bus.clone()));

        let svc = EventServiceImpl::new(host);

        // Subscribe with no filters (wildcard)
        let request = Request::new(SubscribeRequest {
            entity_type: None,
            entity_id: None,
            event_type: None,
            kind: None,
            link_type: None,
        });

        let response = svc.subscribe(request).await.unwrap();
        let mut stream = response.into_inner();

        // Publish 2 events of different types
        event_bus.publish(FrameworkEvent::Entity(EntityEvent::Created {
            entity_type: "user".to_string(),
            entity_id: Uuid::new_v4(),
            data: json!({}),
        }));

        event_bus.publish(FrameworkEvent::Link(LinkEvent::Created {
            link_type: "follow".to_string(),
            link_id: Uuid::new_v4(),
            source_id: Uuid::new_v4(),
            target_id: Uuid::new_v4(),
            metadata: None,
        }));

        // Should receive both
        let msg1 = tokio::time::timeout(std::time::Duration::from_millis(100), stream.next())
            .await
            .expect("timed out")
            .expect("stream ended")
            .expect("error");
        assert_eq!(msg1.event_kind, "entity");

        let msg2 = tokio::time::timeout(std::time::Duration::from_millis(100), stream.next())
            .await
            .expect("timed out")
            .expect("stream ended")
            .expect("error");
        assert_eq!(msg2.event_kind, "link");
    }

    #[tokio::test]
    async fn test_event_service_client_disconnect_ends_task() {
        use crate::server::host::ServerHost;

        let event_bus = EventBus::new(64);
        let host = Arc::new(ServerHost::minimal_for_test().with_event_bus(event_bus.clone()));

        let svc = EventServiceImpl::new(host);

        let request = Request::new(SubscribeRequest {
            entity_type: None,
            entity_id: None,
            event_type: None,
            kind: None,
            link_type: None,
        });

        let response = svc.subscribe(request).await.unwrap();

        // Drop the stream to simulate client disconnect
        drop(response);

        // The spawned task should detect the closed mpsc and exit.
        // Publish an event to trigger the detection
        event_bus.publish(FrameworkEvent::Entity(EntityEvent::Created {
            entity_type: "user".to_string(),
            entity_id: Uuid::new_v4(),
            data: json!({}),
        }));

        // Give the task time to notice and exit
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        // If we get here without hanging, the task properly exited
    }
}