fraiseql-server 2.3.0

HTTP server for FraiseQL v2 GraphQL engine
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
mod broadcast_tests {
    #![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable

    use std::sync::Arc;

    use super::super::broadcast::*;

    #[tokio::test]
    async fn test_publish_creates_channel_on_demand() {
        let manager = BroadcastManager::new(BroadcastConfig::new());

        let receivers = manager
            .publish("chat:room1", "message".into(), serde_json::json!({"text": "hello"}))
            .await
            .unwrap();

        // No subscribers yet, so 0 receivers
        assert_eq!(receivers, 0);
        assert_eq!(manager.channel_count().await, 1);
    }

    #[tokio::test]
    async fn test_subscribe_then_publish() {
        let manager = Arc::new(BroadcastManager::new(BroadcastConfig::new()));

        let mut rx = manager.subscribe("chat:room1").await.unwrap();

        let receivers = manager
            .publish("chat:room1", "message".into(), serde_json::json!({"text": "hello"}))
            .await
            .unwrap();

        assert_eq!(receivers, 1);

        let msg = rx.recv().await.unwrap();
        assert_eq!(msg.channel, "chat:room1");
        assert_eq!(msg.event, "message");
        assert_eq!(msg.payload["text"], "hello");
    }

    #[tokio::test]
    async fn test_multiple_subscribers() {
        let manager = Arc::new(BroadcastManager::new(BroadcastConfig::new()));

        let mut rx1 = manager.subscribe("events").await.unwrap();
        let mut rx2 = manager.subscribe("events").await.unwrap();

        let receivers = manager
            .publish("events", "update".into(), serde_json::json!({"v": 1}))
            .await
            .unwrap();

        assert_eq!(receivers, 2);

        let msg1 = rx1.recv().await.unwrap();
        let msg2 = rx2.recv().await.unwrap();
        assert_eq!(msg1.payload, msg2.payload);
    }

    #[tokio::test]
    async fn test_payload_too_large() {
        let config = BroadcastConfig {
            max_message_bytes: 10,
            ..BroadcastConfig::new()
        };
        let manager = BroadcastManager::new(config);

        let result = manager
            .publish("ch", "e".into(), serde_json::json!({"big": "data that is too large"}))
            .await;

        assert!(result.is_err());
        assert_eq!(result.unwrap_err().status_code(), 413);
    }

    #[tokio::test]
    async fn test_too_many_channels() {
        let config = BroadcastConfig {
            max_channels: 2,
            ..BroadcastConfig::new()
        };
        let manager = BroadcastManager::new(config);

        manager.publish("ch1", "e".into(), serde_json::json!({})).await.unwrap();
        manager.publish("ch2", "e".into(), serde_json::json!({})).await.unwrap();
        let result = manager.publish("ch3", "e".into(), serde_json::json!({})).await;

        assert!(result.is_err());
        assert_eq!(result.unwrap_err().status_code(), 503);
    }

    #[tokio::test]
    async fn test_gc_empty_channels() {
        let manager = BroadcastManager::new(BroadcastConfig::new());

        // Create a channel with a subscriber
        let _rx = manager.subscribe("active").await.unwrap();
        // Create a channel with no subscribers
        manager.publish("orphan", "e".into(), serde_json::json!({})).await.unwrap();

        assert_eq!(manager.channel_count().await, 2);

        let removed = manager.gc_empty_channels().await;
        assert_eq!(removed, 1);
        assert_eq!(manager.channel_count().await, 1);
    }

    #[tokio::test]
    async fn test_stats() {
        let manager = Arc::new(BroadcastManager::new(BroadcastConfig::new()));

        let _rx = manager.subscribe("ch1").await.unwrap();
        manager.publish("ch1", "e".into(), serde_json::json!({})).await.unwrap();
        manager.publish("ch2", "e".into(), serde_json::json!({})).await.unwrap();

        let stats = manager.stats().await;
        assert_eq!(stats.messages_published, 2);
        assert_eq!(stats.active_channels, 2);
        assert_eq!(stats.active_receivers, 1);
    }

    #[tokio::test]
    async fn test_channel_isolation() {
        let manager = Arc::new(BroadcastManager::new(BroadcastConfig::new()));

        let mut rx_a = manager.subscribe("channel_a").await.unwrap();
        let _rx_b = manager.subscribe("channel_b").await.unwrap();

        manager
            .publish("channel_a", "event".into(), serde_json::json!({"for": "a"}))
            .await
            .unwrap();

        let msg = rx_a.recv().await.unwrap();
        assert_eq!(msg.payload["for"], "a");

        // channel_b subscriber should not have received anything
        // (try_recv would return Empty, not a message)
    }
}

mod event_bridge_tests {
    use std::sync::Arc;

    use fraiseql_core::{
        runtime::subscription::{SubscriptionManager, SubscriptionOperation},
        schema::CompiledSchema,
    };

    use super::super::event_bridge::*;

    #[test]
    fn test_event_bridge_creation() {
        let schema = Arc::new(CompiledSchema::new());
        let manager = Arc::new(SubscriptionManager::new(schema));
        let config = EventBridgeConfig::new();

        let bridge = EventBridge::new(manager, config);

        // Verify bridge is created
        assert!(
            bridge.sender().try_reserve().is_ok(),
            "event bridge channel should have capacity for at least one message"
        );
    }

    #[test]
    fn test_event_conversion_insert() {
        let entity_event = EntityEvent::new(
            "Order",
            "order_123",
            "INSERT",
            serde_json::json!({
                "id": "order_123",
                "status": "pending"
            }),
        );

        let subscription_event = EventBridge::convert_event(entity_event);

        assert_eq!(subscription_event.entity_type, "Order");
        assert_eq!(subscription_event.entity_id, "order_123");
        assert_eq!(subscription_event.operation, SubscriptionOperation::Create);
    }

    #[test]
    fn test_event_conversion_update() {
        let entity_event = EntityEvent::new(
            "Order",
            "order_123",
            "UPDATE",
            serde_json::json!({
                "id": "order_123",
                "status": "shipped"
            }),
        );

        let subscription_event = EventBridge::convert_event(entity_event);

        assert_eq!(subscription_event.operation, SubscriptionOperation::Update);
    }

    #[test]
    fn test_event_conversion_delete() {
        let entity_event = EntityEvent::new(
            "Order",
            "order_123",
            "DELETE",
            serde_json::json!({
                "id": "order_123"
            }),
        );

        let subscription_event = EventBridge::convert_event(entity_event);

        assert_eq!(subscription_event.operation, SubscriptionOperation::Delete);
    }

    #[test]
    fn test_event_conversion_with_old_data() {
        let entity_event = EntityEvent::new(
            "Order",
            "order_123",
            "UPDATE",
            serde_json::json!({
                "id": "order_123",
                "status": "shipped"
            }),
        )
        .with_old_data(serde_json::json!({
            "id": "order_123",
            "status": "pending"
        }));

        let subscription_event = EventBridge::convert_event(entity_event);

        assert!(
            subscription_event.old_data.is_some(),
            "update events should carry old_data for delta computation"
        );
    }

    #[tokio::test]
    async fn test_event_bridge_spawning() {
        let schema = Arc::new(CompiledSchema::new());
        let manager = Arc::new(SubscriptionManager::new(schema));
        let config = EventBridgeConfig::new();

        let bridge = EventBridge::new(manager, config);
        let handle = bridge.spawn();

        // Verify task was spawned
        assert!(!handle.is_finished());

        // Clean up
        handle.abort();
    }

    #[tokio::test]
    async fn test_event_bridge_end_to_end_forwarding() {
        let schema = Arc::new(CompiledSchema::new());
        let manager = Arc::new(SubscriptionManager::new(schema));
        let config = EventBridgeConfig::new();

        let bridge = EventBridge::new(manager, config);
        let sender = bridge.sender();
        let handle = bridge.spawn();

        // Send multiple events through the channel
        for i in 0..3 {
            let event = EntityEvent::new(
                "Order",
                format!("order_{i}"),
                "INSERT",
                serde_json::json!({"id": format!("order_{i}"), "total": 99.95}),
            );
            sender.send(event).await.expect("channel should be open");
        }

        // Yield to let the bridge task process events
        tokio::task::yield_now().await;

        // The bridge should still be running (didn't panic processing events)
        assert!(!handle.is_finished(), "bridge should still be running after processing events");

        handle.abort();
    }

    #[tokio::test]
    async fn test_event_bridge_sender_cloning() {
        let schema = Arc::new(CompiledSchema::new());
        let manager = Arc::new(SubscriptionManager::new(schema));
        let config = EventBridgeConfig::new();

        let bridge = EventBridge::new(manager, config);
        let sender1 = bridge.sender();
        let sender2 = bridge.sender();

        // Both senders should be usable (cloned from the same channel)
        assert!(sender1.try_reserve().is_ok());
        assert!(sender2.try_reserve().is_ok());
    }
}

mod lifecycle_tests {
    use super::super::lifecycle::*;

    #[tokio::test]
    async fn noop_lifecycle_accepts_connect() {
        let lifecycle = NoopLifecycle;
        let result = lifecycle.on_connect(&serde_json::json!({}), "conn-1").await;
        assert!(result.is_ok(), "noop lifecycle should accept any connection");
    }

    #[tokio::test]
    async fn noop_lifecycle_accepts_subscribe() {
        let lifecycle = NoopLifecycle;
        let result = lifecycle.on_subscribe("orderCreated", &serde_json::json!({}), "conn-1").await;
        assert!(result.is_ok(), "noop lifecycle should accept any subscription");
    }
}

mod presence_tests {
    #![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable

    use std::time::Duration;

    use super::super::presence::*;

    fn default_manager() -> PresenceManager {
        PresenceManager::new(PresenceConfig::new())
    }

    #[tokio::test]
    async fn test_join_returns_state_and_diff() {
        let mgr = default_manager();

        let (state, diff) = mgr
            .join("room1", "alice", serde_json::json!({"status": "online"}))
            .await
            .unwrap();

        assert_eq!(state.room, "room1");
        assert_eq!(state.members.len(), 1);
        assert_eq!(state.members[0].id, "alice");
        assert_eq!(diff.joins.len(), 1);
        assert!(diff.leaves.is_empty());
    }

    #[tokio::test]
    async fn test_multiple_members_in_room() {
        let mgr = default_manager();

        mgr.join("room1", "alice", serde_json::json!({})).await.unwrap();
        let (state, diff) = mgr.join("room1", "bob", serde_json::json!({})).await.unwrap();

        assert_eq!(state.members.len(), 2);
        assert_eq!(diff.joins.len(), 1);
        assert_eq!(diff.joins[0].id, "bob");
    }

    #[tokio::test]
    async fn test_leave_returns_diff() {
        let mgr = default_manager();
        mgr.join("room1", "alice", serde_json::json!({})).await.unwrap();

        let diff = mgr.leave("room1", "alice").await.unwrap();
        assert_eq!(diff.leaves, vec!["alice"]);
        assert!(diff.joins.is_empty());

        // Room should be cleaned up
        assert!(mgr.get_room("room1").await.is_none());
    }

    #[tokio::test]
    async fn test_leave_nonexistent_returns_none() {
        let mgr = default_manager();
        assert!(mgr.leave("room1", "alice").await.is_none());
    }

    #[tokio::test]
    async fn test_heartbeat() {
        let mgr = default_manager();
        mgr.join("room1", "alice", serde_json::json!({})).await.unwrap();

        assert!(mgr.heartbeat("room1", "alice").await);
        assert!(!mgr.heartbeat("room1", "nobody").await);
        assert!(!mgr.heartbeat("noroom", "alice").await);
    }

    #[tokio::test]
    async fn test_update_state() {
        let mgr = default_manager();
        mgr.join("room1", "alice", serde_json::json!({"status": "online"}))
            .await
            .unwrap();

        let diff = mgr
            .update_state("room1", "alice", serde_json::json!({"status": "away"}))
            .await
            .unwrap();

        assert_eq!(diff.joins.len(), 1);
        assert_eq!(diff.joins[0].state["status"], "away");

        let state = mgr.get_room("room1").await.unwrap();
        assert_eq!(state.members[0].state["status"], "away");
    }

    #[tokio::test(start_paused = true)]
    async fn test_evict_stale_members() {
        let config = PresenceConfig {
            heartbeat_timeout: Duration::from_millis(1),
            ..PresenceConfig::new()
        };
        let mgr = PresenceManager::new(config);

        mgr.join("room1", "alice", serde_json::json!({})).await.unwrap();
        mgr.join("room1", "bob", serde_json::json!({})).await.unwrap();

        // Advance past heartbeat timeout
        tokio::time::advance(Duration::from_millis(10)).await;

        let diffs = mgr.evict_stale().await;
        assert_eq!(diffs.len(), 1);
        assert_eq!(diffs[0].leaves.len(), 2);

        // Room should be cleaned up
        assert!(mgr.get_room("room1").await.is_none());
    }

    #[tokio::test(start_paused = true)]
    async fn test_heartbeat_prevents_eviction() {
        let config = PresenceConfig {
            heartbeat_timeout: Duration::from_millis(50),
            ..PresenceConfig::new()
        };
        let mgr = PresenceManager::new(config);

        mgr.join("room1", "alice", serde_json::json!({})).await.unwrap();
        mgr.join("room1", "bob", serde_json::json!({})).await.unwrap();

        // Advance time, then heartbeat only alice
        tokio::time::advance(Duration::from_millis(30)).await;
        mgr.heartbeat("room1", "alice").await;

        // Advance past bob's expiry but not alice's (she heartbeated at t=30)
        tokio::time::advance(Duration::from_millis(30)).await;

        let diffs = mgr.evict_stale().await;
        assert_eq!(diffs.len(), 1);
        assert_eq!(diffs[0].leaves, vec!["bob"]);

        // Alice should still be in the room
        let state = mgr.get_room("room1").await.unwrap();
        assert_eq!(state.members.len(), 1);
        assert_eq!(state.members[0].id, "alice");
    }

    #[tokio::test]
    async fn test_room_full() {
        let config = PresenceConfig {
            max_members_per_room: 2,
            ..PresenceConfig::new()
        };
        let mgr = PresenceManager::new(config);

        mgr.join("room1", "alice", serde_json::json!({})).await.unwrap();
        mgr.join("room1", "bob", serde_json::json!({})).await.unwrap();

        let result = mgr.join("room1", "charlie", serde_json::json!({})).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_too_many_rooms() {
        let config = PresenceConfig {
            max_rooms: 2,
            ..PresenceConfig::new()
        };
        let mgr = PresenceManager::new(config);

        mgr.join("room1", "a", serde_json::json!({})).await.unwrap();
        mgr.join("room2", "b", serde_json::json!({})).await.unwrap();

        let result = mgr.join("room3", "c", serde_json::json!({})).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_rejoin_same_member_updates_state() {
        let mgr = default_manager();

        mgr.join("room1", "alice", serde_json::json!({"v": 1})).await.unwrap();
        let (state, _) = mgr.join("room1", "alice", serde_json::json!({"v": 2})).await.unwrap();

        // Should still be 1 member, not 2
        assert_eq!(state.members.len(), 1);
        assert_eq!(state.members[0].state["v"], 2);
    }

    #[tokio::test]
    async fn test_stats() {
        let mgr = default_manager();
        mgr.join("room1", "alice", serde_json::json!({})).await.unwrap();
        mgr.join("room1", "bob", serde_json::json!({})).await.unwrap();
        mgr.join("room2", "charlie", serde_json::json!({})).await.unwrap();
        mgr.leave("room1", "alice").await;

        let stats = mgr.stats().await;
        assert_eq!(stats.active_rooms, 2);
        assert_eq!(stats.total_members, 2);
        assert_eq!(stats.joins_total, 3);
        assert_eq!(stats.leaves_total, 1);
    }

    #[tokio::test]
    async fn test_room_isolation() {
        let mgr = default_manager();
        mgr.join("room1", "alice", serde_json::json!({})).await.unwrap();
        mgr.join("room2", "bob", serde_json::json!({})).await.unwrap();

        let state1 = mgr.get_room("room1").await.unwrap();
        let state2 = mgr.get_room("room2").await.unwrap();

        assert_eq!(state1.members.len(), 1);
        assert_eq!(state1.members[0].id, "alice");
        assert_eq!(state2.members.len(), 1);
        assert_eq!(state2.members[0].id, "bob");
    }
}

mod protocol_tests {
    #![allow(clippy::unwrap_used)] // Reason: test code, panics acceptable
    #![allow(clippy::cast_precision_loss)] // Reason: test metrics reporting
    #![allow(clippy::cast_sign_loss)] // Reason: test data uses small positive integers
    #![allow(clippy::cast_possible_truncation)] // Reason: test data values are bounded
    #![allow(clippy::cast_possible_wrap)] // Reason: test data values are bounded
    #![allow(clippy::missing_panics_doc)] // Reason: test helpers
    #![allow(clippy::missing_errors_doc)] // Reason: test helpers
    #![allow(missing_docs)] // Reason: test code
    #![allow(clippy::items_after_statements)] // Reason: test helpers defined near use site

    use fraiseql_core::runtime::protocol::ServerMessage;

    use super::super::protocol::*;

    // ── WsProtocol::from_header ──────────────────────────────────

    #[test]
    fn from_header_transport_ws() {
        assert_eq!(
            WsProtocol::from_header(Some("graphql-transport-ws")),
            Some(WsProtocol::GraphqlTransportWs)
        );
    }

    #[test]
    fn from_header_legacy_ws() {
        assert_eq!(WsProtocol::from_header(Some("graphql-ws")), Some(WsProtocol::GraphqlWs));
    }

    #[test]
    fn from_header_multiple_prefers_first_known() {
        // Client may offer both; we pick the first recognised one.
        assert_eq!(
            WsProtocol::from_header(Some("graphql-ws, graphql-transport-ws")),
            Some(WsProtocol::GraphqlWs)
        );
        assert_eq!(
            WsProtocol::from_header(Some("graphql-transport-ws, graphql-ws")),
            Some(WsProtocol::GraphqlTransportWs)
        );
    }

    #[test]
    fn from_header_unknown_returns_none() {
        assert_eq!(WsProtocol::from_header(Some("unknown-protocol")), None);
    }

    #[test]
    fn from_header_none_returns_none() {
        assert_eq!(WsProtocol::from_header(None), None);
    }

    // ── ProtocolCodec::decode (modern) ───────────────────────────

    #[test]
    fn decode_transport_ws_subscribe() {
        let codec = ProtocolCodec::new(WsProtocol::GraphqlTransportWs);
        let raw = r#"{"type":"subscribe","id":"1","payload":{"query":"subscription { x }"}}"#;
        let msg = codec.decode(raw).unwrap();
        assert_eq!(msg.message_type, "subscribe");
        assert_eq!(msg.id, Some("1".to_string()));
    }

    #[test]
    fn decode_transport_ws_invalid_json() {
        let codec = ProtocolCodec::new(WsProtocol::GraphqlTransportWs);
        assert!(
            matches!(codec.decode("not json"), Err(ProtocolError::InvalidJson(_))),
            "expected InvalidJson error for malformed input, got: {:?}",
            codec.decode("not json")
        );
    }

    // ── ProtocolCodec::decode (legacy) ───────────────────────────

    #[test]
    fn decode_legacy_start_becomes_subscribe() {
        let codec = ProtocolCodec::new(WsProtocol::GraphqlWs);
        let raw = r#"{"type":"start","id":"1","payload":{"query":"subscription { x }"}}"#;
        let msg = codec.decode(raw).unwrap();
        assert_eq!(msg.message_type, "subscribe");
    }

    #[test]
    fn decode_legacy_stop_becomes_complete() {
        let codec = ProtocolCodec::new(WsProtocol::GraphqlWs);
        let raw = r#"{"type":"stop","id":"1"}"#;
        let msg = codec.decode(raw).unwrap();
        assert_eq!(msg.message_type, "complete");
    }

    #[test]
    fn decode_legacy_connection_init_unchanged() {
        let codec = ProtocolCodec::new(WsProtocol::GraphqlWs);
        let raw = r#"{"type":"connection_init"}"#;
        let msg = codec.decode(raw).unwrap();
        assert_eq!(msg.message_type, "connection_init");
    }

    // ── ProtocolCodec::encode (modern) ───────────────────────────

    #[test]
    fn encode_transport_ws_next() {
        let codec = ProtocolCodec::new(WsProtocol::GraphqlTransportWs);
        let msg = ServerMessage::next("1", serde_json::json!({"x": 1}));
        let json = codec.encode(&msg).unwrap().unwrap();
        assert!(json.contains("\"next\""));
    }

    #[test]
    fn encode_transport_ws_ping() {
        let codec = ProtocolCodec::new(WsProtocol::GraphqlTransportWs);
        let msg = ServerMessage::ping(None);
        let json = codec.encode(&msg).unwrap().unwrap();
        assert!(json.contains("\"ping\""));
    }

    // ── ProtocolCodec::encode (legacy) ───────────────────────────

    #[test]
    fn encode_legacy_next_becomes_data() {
        let codec = ProtocolCodec::new(WsProtocol::GraphqlWs);
        let msg = ServerMessage::next("1", serde_json::json!({"x": 1}));
        let json = codec.encode(&msg).unwrap().unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["type"], "data");
    }

    #[test]
    fn encode_legacy_ping_becomes_ka() {
        let codec = ProtocolCodec::new(WsProtocol::GraphqlWs);
        let msg = ServerMessage::ping(None);
        let json = codec.encode(&msg).unwrap().unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["type"], "ka");
        // ka has no payload or id
        assert!(parsed.get("payload").is_none() || parsed["payload"].is_null());
    }

    #[test]
    fn encode_legacy_pong_is_suppressed() {
        let codec = ProtocolCodec::new(WsProtocol::GraphqlWs);
        let msg = ServerMessage::pong(None);
        let result = codec.encode(&msg).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn encode_legacy_connection_ack_unchanged() {
        let codec = ProtocolCodec::new(WsProtocol::GraphqlWs);
        let msg = ServerMessage::connection_ack(None);
        let json = codec.encode(&msg).unwrap().unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["type"], "connection_ack");
    }

    #[test]
    fn encode_legacy_error_unchanged() {
        let codec = ProtocolCodec::new(WsProtocol::GraphqlWs);
        let msg = ServerMessage::error(
            "1",
            vec![fraiseql_core::runtime::protocol::GraphQLError::new("test")],
        );
        let json = codec.encode(&msg).unwrap().unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["type"], "error");
    }

    // ── uses_keepalive ───────────────────────────────────────────

    #[test]
    fn uses_keepalive_legacy() {
        let codec = ProtocolCodec::new(WsProtocol::GraphqlWs);
        assert!(codec.uses_keepalive());
    }

    #[test]
    fn uses_keepalive_modern() {
        let codec = ProtocolCodec::new(WsProtocol::GraphqlTransportWs);
        assert!(!codec.uses_keepalive());
    }
}

mod webhook_lifecycle_tests {
    #![allow(clippy::unwrap_used)] // Reason: test code, panics acceptable
    #![allow(clippy::cast_precision_loss)] // Reason: test metrics reporting
    #![allow(clippy::cast_sign_loss)] // Reason: test data uses small positive integers
    #![allow(clippy::cast_possible_truncation)] // Reason: test data values are bounded
    #![allow(clippy::cast_possible_wrap)] // Reason: test data values are bounded
    #![allow(clippy::missing_panics_doc)] // Reason: test helpers
    #![allow(clippy::missing_errors_doc)] // Reason: test helpers
    #![allow(missing_docs)] // Reason: test code
    #![allow(clippy::items_after_statements)] // Reason: test helpers defined near use site

    use std::time::Duration;

    use super::super::webhook_lifecycle::{MAX_WEBHOOK_RESPONSE_BYTES, WebhookLifecycle};

    #[test]
    fn from_schema_json_no_hooks() {
        let json = serde_json::json!({});
        assert!(WebhookLifecycle::from_schema_json(&json).is_none());
    }

    #[test]
    fn from_schema_json_empty_hooks() {
        let json = serde_json::json!({"hooks": {}});
        assert!(WebhookLifecycle::from_schema_json(&json).is_none());
    }

    #[test]
    fn from_schema_json_with_connect_url() {
        let json = serde_json::json!({
            "hooks": {
                "on_connect": "http://localhost:8001/hooks/ws-connect",
                "timeout_ms": 300
            }
        });
        let wh = WebhookLifecycle::from_schema_json(&json).unwrap();
        assert_eq!(wh.on_connect_url, Some("http://localhost:8001/hooks/ws-connect".to_string()));
        assert!(wh.on_disconnect_url.is_none());
        assert!(wh.on_subscribe_url.is_none());
        assert_eq!(wh.timeout, Duration::from_millis(300));
    }

    #[test]
    fn from_schema_json_default_timeout() {
        let json = serde_json::json!({
            "hooks": {
                "on_disconnect": "http://localhost:8001/hooks/ws-disconnect"
            }
        });
        let wh = WebhookLifecycle::from_schema_json(&json).unwrap();
        assert_eq!(wh.timeout, Duration::from_millis(500));
    }

    #[test]
    fn webhook_response_cap_constant_is_reasonable() {
        // 64 KiB: large enough for any human-readable error, small enough to prevent OOM.
        assert_eq!(MAX_WEBHOOK_RESPONSE_BYTES, 64 * 1024);
    }

    #[test]
    fn webhook_response_body_is_capped_at_limit() {
        // Simulate what on_connect / on_subscribe do: bytes → cap → lossy UTF-8.
        let oversized: Vec<u8> = vec![b'x'; MAX_WEBHOOK_RESPONSE_BYTES + 100];
        let capped = &oversized[..oversized.len().min(MAX_WEBHOOK_RESPONSE_BYTES)];
        let text = String::from_utf8_lossy(capped).into_owned();
        assert_eq!(text.len(), MAX_WEBHOOK_RESPONSE_BYTES);
    }
}