hyperi-rustlib 2.8.6

There's plenty of sage advice out there about how to run Rust services in production at scale — config cascades, structured logging, masking secrets, multi-backend secrets management, Prometheus, OpenTelemetry, Kafka transports, tiered disk-spillover sinks, adaptive worker pools, graceful shutdown — but almost none of it as code you can just install and use. This is that code. Opinionated, drop-in, working out of the box. The patterns from blog posts, watercooler chats and beers with your Google mates as actual library — not a framework you assemble from twenty crates and 8 weeks of munging.
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
// Project:   hyperi-rustlib
// File:      src/transport/factory.rs
// Purpose:   Transport factory -- create senders from config
// Language:  Rust
//
// License:   BUSL-1.1
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Transport factory for runtime transport selection.
//!
//! Creates transport senders from configuration, enabling apps to swap
//! between Kafka, gRPC, file, pipe, HTTP, or Redis via config change.
//!
//! # Usage
//!
//! ```yaml
//! # settings.yaml
//! transport:
//!   output:
//!     type: kafka
//!     kafka:
//!       brokers: ["kafka:9092"]
//! ```
//!
//! ```rust,ignore
//! use hyperi_rustlib::transport::factory::AnySender;
//!
//! let sender = AnySender::from_config("transport.output").await?;
//! sender.send("events.land", payload).await;
//! ```

use super::error::{TransportError, TransportResult};
use super::traits::{CommitToken, TransportBase, TransportReceiver, TransportSender};
use super::types::SendResult;
#[cfg(any(
    feature = "transport-kafka",
    feature = "transport-grpc",
    feature = "transport-memory",
    feature = "transport-pipe",
    feature = "transport-file",
    feature = "transport-http",
    feature = "transport-redis"
))]
use super::types::TransportType;
use super::work_batch::{Record, WorkBatch};

/// Type-erased transport sender.
///
/// Wraps any concrete transport sender behind an enum for runtime
/// dispatch. Created by the transport factory from config.
///
/// Uses enum dispatch (not trait objects) because `TransportSender`
/// has `impl Future` return types which prevent `dyn` dispatch.
pub enum AnySender {
    #[cfg(feature = "transport-kafka")]
    Kafka(super::kafka::KafkaTransport),

    #[cfg(feature = "transport-grpc")]
    Grpc(super::grpc::GrpcTransport),

    #[cfg(feature = "transport-memory")]
    Memory(super::memory::MemoryTransport),

    #[cfg(feature = "transport-pipe")]
    Pipe(super::pipe::PipeTransport),

    #[cfg(feature = "transport-file")]
    File(super::file::FileTransport),

    #[cfg(feature = "transport-http")]
    Http(super::http::HttpTransport),

    #[cfg(feature = "transport-redis")]
    Redis(super::redis_transport::RedisTransport),
}

impl TransportBase for AnySender {
    async fn close(&self) -> TransportResult<()> {
        match self {
            #[cfg(feature = "transport-kafka")]
            Self::Kafka(t) => t.close().await,
            #[cfg(feature = "transport-grpc")]
            Self::Grpc(t) => t.close().await,
            #[cfg(feature = "transport-memory")]
            Self::Memory(t) => t.close().await,
            #[cfg(feature = "transport-pipe")]
            Self::Pipe(t) => t.close().await,
            #[cfg(feature = "transport-file")]
            Self::File(t) => t.close().await,
            #[cfg(feature = "transport-http")]
            Self::Http(t) => t.close().await,
            #[cfg(feature = "transport-redis")]
            Self::Redis(t) => t.close().await,
            #[allow(unreachable_patterns)]
            _ => Err(TransportError::Config(
                "no transport variant enabled".into(),
            )),
        }
    }

    fn is_healthy(&self) -> bool {
        match self {
            #[cfg(feature = "transport-kafka")]
            Self::Kafka(t) => t.is_healthy(),
            #[cfg(feature = "transport-grpc")]
            Self::Grpc(t) => t.is_healthy(),
            #[cfg(feature = "transport-memory")]
            Self::Memory(t) => t.is_healthy(),
            #[cfg(feature = "transport-pipe")]
            Self::Pipe(t) => t.is_healthy(),
            #[cfg(feature = "transport-file")]
            Self::File(t) => t.is_healthy(),
            #[cfg(feature = "transport-http")]
            Self::Http(t) => t.is_healthy(),
            #[cfg(feature = "transport-redis")]
            Self::Redis(t) => t.is_healthy(),
            #[allow(unreachable_patterns)]
            _ => false,
        }
    }

    fn name(&self) -> &'static str {
        match self {
            #[cfg(feature = "transport-kafka")]
            Self::Kafka(t) => t.name(),
            #[cfg(feature = "transport-grpc")]
            Self::Grpc(t) => t.name(),
            #[cfg(feature = "transport-memory")]
            Self::Memory(t) => t.name(),
            #[cfg(feature = "transport-pipe")]
            Self::Pipe(t) => t.name(),
            #[cfg(feature = "transport-file")]
            Self::File(t) => t.name(),
            #[cfg(feature = "transport-http")]
            Self::Http(t) => t.name(),
            #[cfg(feature = "transport-redis")]
            Self::Redis(t) => t.name(),
            #[allow(unreachable_patterns)]
            _ => "none",
        }
    }
}

impl TransportSender for AnySender {
    #[cfg_attr(
        not(any(
            feature = "transport-kafka",
            feature = "transport-grpc",
            feature = "transport-memory",
            feature = "transport-pipe",
            feature = "transport-file",
            feature = "transport-http",
            feature = "transport-redis"
        )),
        allow(unused_variables)
    )]
    async fn send(&self, key: &str, payload: bytes::Bytes) -> SendResult {
        match self {
            #[cfg(feature = "transport-kafka")]
            Self::Kafka(t) => t.send(key, payload).await,
            #[cfg(feature = "transport-grpc")]
            Self::Grpc(t) => t.send(key, payload).await,
            #[cfg(feature = "transport-memory")]
            Self::Memory(t) => t.send(key, payload).await,
            #[cfg(feature = "transport-pipe")]
            Self::Pipe(t) => t.send(key, payload).await,
            #[cfg(feature = "transport-file")]
            Self::File(t) => t.send(key, payload).await,
            #[cfg(feature = "transport-http")]
            Self::Http(t) => t.send(key, payload).await,
            #[cfg(feature = "transport-redis")]
            Self::Redis(t) => t.send(key, payload).await,
            #[allow(unreachable_patterns)]
            _ => SendResult::Fatal(TransportError::Config(
                "no transport variant enabled".into(),
            )),
        }
    }

    /// Forward [`send_batch`](TransportSender::send_batch) to the active
    /// backend. gRPC uses its native single-RPC `RouteBatch` override; every
    /// other backend uses the trait's per-record default (see the at-least-once
    /// partial-send caveat on the trait method).
    #[cfg_attr(
        not(any(
            feature = "transport-kafka",
            feature = "transport-grpc",
            feature = "transport-memory",
            feature = "transport-pipe",
            feature = "transport-file",
            feature = "transport-http",
            feature = "transport-redis"
        )),
        allow(unused_variables)
    )]
    async fn send_batch(&self, records: &[Record]) -> SendResult {
        match self {
            #[cfg(feature = "transport-kafka")]
            Self::Kafka(t) => t.send_batch(records).await,
            #[cfg(feature = "transport-grpc")]
            Self::Grpc(t) => t.send_batch(records).await,
            #[cfg(feature = "transport-memory")]
            Self::Memory(t) => t.send_batch(records).await,
            #[cfg(feature = "transport-pipe")]
            Self::Pipe(t) => t.send_batch(records).await,
            #[cfg(feature = "transport-file")]
            Self::File(t) => t.send_batch(records).await,
            #[cfg(feature = "transport-http")]
            Self::Http(t) => t.send_batch(records).await,
            #[cfg(feature = "transport-redis")]
            Self::Redis(t) => t.send_batch(records).await,
            #[allow(unreachable_patterns)]
            _ => SendResult::Fatal(TransportError::Config(
                "no transport variant enabled".into(),
            )),
        }
    }
}

impl AnySender {
    /// Create a sender from config cascade.
    ///
    /// Reads the transport config from the given key in the config
    /// cascade and creates the appropriate sender.
    ///
    /// # Example config
    ///
    /// ```yaml
    /// transport:
    ///   output:
    ///     type: kafka
    ///     kafka:
    ///       brokers: ["kafka:9092"]
    /// ```
    ///
    /// ```rust,ignore
    /// let sender = AnySender::from_config("transport.output").await?;
    /// ```
    pub async fn from_config(key: &str) -> TransportResult<Self> {
        #[cfg(feature = "config")]
        let config = {
            let cfg = crate::config::try_get()
                .ok_or_else(|| TransportError::Config("config not initialised".into()))?;
            cfg.unmarshal_key::<super::TransportConfig>(key)
                .map_err(|e| TransportError::Config(format!("failed to read {key}: {e}")))?
        };

        #[cfg(not(feature = "config"))]
        let config = {
            let _ = key;
            super::TransportConfig::default()
        };

        Self::from_transport_config(&config).await
    }

    /// Create a sender from an explicit `TransportConfig`.
    pub async fn from_transport_config(config: &super::TransportConfig) -> TransportResult<Self> {
        match config.transport_type {
            #[cfg(feature = "transport-kafka")]
            TransportType::Kafka => {
                let kafka_config = config
                    .kafka
                    .as_ref()
                    .ok_or_else(|| TransportError::Config("kafka config missing".into()))?;
                let transport = super::kafka::KafkaTransport::new(kafka_config).await?;
                Ok(Self::Kafka(transport))
            }

            #[cfg(feature = "transport-grpc")]
            TransportType::Grpc => {
                let grpc_config = config
                    .grpc
                    .as_ref()
                    .ok_or_else(|| TransportError::Config("grpc config missing".into()))?;
                let transport = super::grpc::GrpcTransport::new(grpc_config).await?;
                Ok(Self::Grpc(transport))
            }

            #[cfg(feature = "transport-memory")]
            TransportType::Memory => {
                let memory_config = config.memory.clone().unwrap_or_default();
                let transport = super::memory::MemoryTransport::new(&memory_config)?;
                Ok(Self::Memory(transport))
            }

            #[cfg(feature = "transport-pipe")]
            TransportType::Pipe => {
                let pipe_config = config.pipe.clone().unwrap_or_default();
                let transport = super::pipe::PipeTransport::new(&pipe_config);
                Ok(Self::Pipe(transport))
            }

            #[cfg(feature = "transport-file")]
            TransportType::File => {
                let file_config = config
                    .file
                    .as_ref()
                    .ok_or_else(|| TransportError::Config("file config missing".into()))?;
                let transport = super::file::FileTransport::new(file_config).await?;
                Ok(Self::File(transport))
            }

            #[cfg(feature = "transport-http")]
            TransportType::Http => {
                let http_config = config
                    .http
                    .as_ref()
                    .ok_or_else(|| TransportError::Config("http config missing".into()))?;
                let transport = super::http::HttpTransport::new(http_config).await?;
                Ok(Self::Http(transport))
            }

            #[cfg(feature = "transport-redis")]
            TransportType::Redis => {
                let redis_config = config
                    .redis
                    .as_ref()
                    .ok_or_else(|| TransportError::Config("redis config missing".into()))?;
                let transport = super::redis_transport::RedisTransport::new(redis_config).await?;
                Ok(Self::Redis(transport))
            }

            // Transport types for modules not yet implemented
            #[allow(unreachable_patterns)]
            other => Err(TransportError::Config(format!(
                "transport type '{other}' is not available (feature not enabled or not yet implemented)"
            ))),
        }
    }
}

// ---------------------------------------------------------------------------
// AnyToken -- type-erased commit token, one variant per enabled backend.
// ---------------------------------------------------------------------------

/// Type-erased commit token produced by [`AnyReceiver`].
///
/// Wraps each backend's concrete token in a matching enum variant so that
/// `AnyReceiver::commit` can route tokens back to the correct backend without
/// heap allocation or trait objects.  The variant set mirrors the enabled
/// transport feature flags exactly.
///
/// Tokens are always produced by the same `AnyReceiver` that delivered the
/// messages, so the active variant and active receiver variant will always
/// agree.  `commit` skips tokens whose variant does not match the active
/// backend (defensive; should not occur in practice).
///
/// `#[non_exhaustive]`: adding a new backend variant later is not a breaking
/// change. Downstream crates that match on `AnyToken` must include a wildcard
/// arm.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum AnyToken {
    #[cfg(feature = "transport-kafka")]
    /// Kafka consumer offset token.
    Kafka(super::kafka::KafkaToken),

    #[cfg(feature = "transport-grpc")]
    /// gRPC no-op sequence token.
    Grpc(super::grpc::GrpcToken),

    #[cfg(feature = "transport-memory")]
    /// In-memory sequence token.
    Memory(super::memory::MemoryToken),

    #[cfg(feature = "transport-pipe")]
    /// Pipe sequence token.
    Pipe(super::pipe::PipeToken),

    #[cfg(feature = "transport-file")]
    /// File byte-offset token.
    File(super::file::FileToken),

    #[cfg(feature = "transport-http")]
    /// HTTP sequence token.
    Http(super::http::HttpToken),

    #[cfg(feature = "transport-redis")]
    /// Redis XACK entry token.
    Redis(super::redis_transport::RedisToken),
}

impl std::fmt::Display for AnyToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            #[cfg(feature = "transport-kafka")]
            Self::Kafka(t) => std::fmt::Display::fmt(t, f),
            #[cfg(feature = "transport-grpc")]
            Self::Grpc(t) => std::fmt::Display::fmt(t, f),
            #[cfg(feature = "transport-memory")]
            Self::Memory(t) => std::fmt::Display::fmt(t, f),
            #[cfg(feature = "transport-pipe")]
            Self::Pipe(t) => std::fmt::Display::fmt(t, f),
            #[cfg(feature = "transport-file")]
            Self::File(t) => std::fmt::Display::fmt(t, f),
            #[cfg(feature = "transport-http")]
            Self::Http(t) => std::fmt::Display::fmt(t, f),
            #[cfg(feature = "transport-redis")]
            Self::Redis(t) => std::fmt::Display::fmt(t, f),
            #[allow(unreachable_patterns)]
            _ => write!(f, "none"),
        }
    }
}

impl CommitToken for AnyToken {}

// ---------------------------------------------------------------------------
// AnyReceiver -- type-erased transport receiver, mirroring AnySender.
// ---------------------------------------------------------------------------

/// Type-erased transport receiver.
///
/// Wraps any concrete transport receiver behind an enum for runtime
/// dispatch. Created by the transport factory from config, mirroring
/// [`AnySender`].
///
/// Uses enum dispatch (not trait objects) because [`TransportReceiver`]
/// has `impl Future` return types and an associated `Token` type that
/// prevent `dyn` dispatch.
///
/// The [`AnyReceiver::recv`] method wraps each backend token in the
/// corresponding [`AnyToken`] variant.  [`AnyReceiver::commit`] extracts
/// the inner tokens for the active backend and forwards to that backend's
/// own `commit` -- tokens from a different variant are silently skipped
/// (they cannot legitimately appear but the code stays defensive).
pub enum AnyReceiver {
    #[cfg(feature = "transport-kafka")]
    Kafka(super::kafka::KafkaTransport),

    #[cfg(feature = "transport-grpc")]
    Grpc(super::grpc::GrpcTransport),

    #[cfg(feature = "transport-memory")]
    Memory(super::memory::MemoryTransport),

    #[cfg(feature = "transport-pipe")]
    Pipe(super::pipe::PipeTransport),

    #[cfg(feature = "transport-file")]
    File(super::file::FileTransport),

    #[cfg(feature = "transport-http")]
    Http(super::http::HttpTransport),

    #[cfg(feature = "transport-redis")]
    Redis(super::redis_transport::RedisTransport),
}

impl TransportBase for AnyReceiver {
    async fn close(&self) -> TransportResult<()> {
        match self {
            #[cfg(feature = "transport-kafka")]
            Self::Kafka(t) => t.close().await,
            #[cfg(feature = "transport-grpc")]
            Self::Grpc(t) => t.close().await,
            #[cfg(feature = "transport-memory")]
            Self::Memory(t) => t.close().await,
            #[cfg(feature = "transport-pipe")]
            Self::Pipe(t) => t.close().await,
            #[cfg(feature = "transport-file")]
            Self::File(t) => t.close().await,
            #[cfg(feature = "transport-http")]
            Self::Http(t) => t.close().await,
            #[cfg(feature = "transport-redis")]
            Self::Redis(t) => t.close().await,
            #[allow(unreachable_patterns)]
            _ => Err(TransportError::Config(
                "no transport variant enabled".into(),
            )),
        }
    }

    fn is_healthy(&self) -> bool {
        match self {
            #[cfg(feature = "transport-kafka")]
            Self::Kafka(t) => t.is_healthy(),
            #[cfg(feature = "transport-grpc")]
            Self::Grpc(t) => t.is_healthy(),
            #[cfg(feature = "transport-memory")]
            Self::Memory(t) => t.is_healthy(),
            #[cfg(feature = "transport-pipe")]
            Self::Pipe(t) => t.is_healthy(),
            #[cfg(feature = "transport-file")]
            Self::File(t) => t.is_healthy(),
            #[cfg(feature = "transport-http")]
            Self::Http(t) => t.is_healthy(),
            #[cfg(feature = "transport-redis")]
            Self::Redis(t) => t.is_healthy(),
            #[allow(unreachable_patterns)]
            _ => false,
        }
    }

    fn name(&self) -> &'static str {
        match self {
            #[cfg(feature = "transport-kafka")]
            Self::Kafka(t) => t.name(),
            #[cfg(feature = "transport-grpc")]
            Self::Grpc(t) => t.name(),
            #[cfg(feature = "transport-memory")]
            Self::Memory(t) => t.name(),
            #[cfg(feature = "transport-pipe")]
            Self::Pipe(t) => t.name(),
            #[cfg(feature = "transport-file")]
            Self::File(t) => t.name(),
            #[cfg(feature = "transport-http")]
            Self::Http(t) => t.name(),
            #[cfg(feature = "transport-redis")]
            Self::Redis(t) => t.name(),
            #[allow(unreachable_patterns)]
            _ => "none",
        }
    }
}

/// Map a backend's `WorkBatch<BackendToken>` into `WorkBatch<AnyToken>` using
/// the provided variant constructor.  Each `commit_tokens` entry is wrapped in
/// the matching [`AnyToken`] variant; `records` and `dlq_entries` move straight
/// through (the record payload `Bytes` is a refcount bump, never a copy).
#[cfg(any(
    feature = "transport-kafka",
    feature = "transport-grpc",
    feature = "transport-memory",
    feature = "transport-pipe",
    feature = "transport-file",
    feature = "transport-http",
    feature = "transport-redis"
))]
fn wrap_batch<B: CommitToken>(
    batch: WorkBatch<B>,
    wrap_token: impl Fn(B) -> AnyToken,
) -> WorkBatch<AnyToken> {
    let commit_tokens = batch.commit_tokens.into_iter().map(wrap_token).collect();
    WorkBatch::new(batch.records, commit_tokens).with_dlq_entries(batch.dlq_entries)
}

impl TransportReceiver for AnyReceiver {
    type Token = AnyToken;

    #[cfg_attr(
        not(any(
            feature = "transport-kafka",
            feature = "transport-grpc",
            feature = "transport-memory",
            feature = "transport-pipe",
            feature = "transport-file",
            feature = "transport-http",
            feature = "transport-redis"
        )),
        allow(unused_variables)
    )]
    async fn recv(&self, max: usize) -> TransportResult<WorkBatch<AnyToken>> {
        match self {
            #[cfg(feature = "transport-kafka")]
            Self::Kafka(t) => {
                let batch = t.recv(max).await?;
                Ok(wrap_batch(batch, AnyToken::Kafka))
            }
            #[cfg(feature = "transport-grpc")]
            Self::Grpc(t) => {
                let batch = t.recv(max).await?;
                Ok(wrap_batch(batch, AnyToken::Grpc))
            }
            #[cfg(feature = "transport-memory")]
            Self::Memory(t) => {
                let batch = t.recv(max).await?;
                Ok(wrap_batch(batch, AnyToken::Memory))
            }
            #[cfg(feature = "transport-pipe")]
            Self::Pipe(t) => {
                let batch = t.recv(max).await?;
                Ok(wrap_batch(batch, AnyToken::Pipe))
            }
            #[cfg(feature = "transport-file")]
            Self::File(t) => {
                let batch = t.recv(max).await?;
                Ok(wrap_batch(batch, AnyToken::File))
            }
            #[cfg(feature = "transport-http")]
            Self::Http(t) => {
                let batch = t.recv(max).await?;
                Ok(wrap_batch(batch, AnyToken::Http))
            }
            #[cfg(feature = "transport-redis")]
            Self::Redis(t) => {
                let batch = t.recv(max).await?;
                Ok(wrap_batch(batch, AnyToken::Redis))
            }
            #[allow(unreachable_patterns)]
            _ => Err(TransportError::Config(
                "no transport variant enabled".into(),
            )),
        }
    }

    /// Forward the byte-aware recv to each inner transport so the governed
    /// driver's byte budget reaches the transport that can honour it (Kafka's
    /// recv-arena). Transports without a byte-aware override fall back to the
    /// trait default (record-bounded `recv`), which is correct for the
    /// one-record-at-a-time channel/stream transports.
    #[cfg_attr(
        not(any(
            feature = "transport-kafka",
            feature = "transport-grpc",
            feature = "transport-memory",
            feature = "transport-pipe",
            feature = "transport-file",
            feature = "transport-http",
            feature = "transport-redis"
        )),
        allow(unused_variables)
    )]
    async fn recv_limited(
        &self,
        limits: super::traits::RecvLimits,
    ) -> TransportResult<WorkBatch<AnyToken>> {
        match self {
            #[cfg(feature = "transport-kafka")]
            Self::Kafka(t) => {
                let batch = t.recv_limited(limits).await?;
                Ok(wrap_batch(batch, AnyToken::Kafka))
            }
            #[cfg(feature = "transport-grpc")]
            Self::Grpc(t) => {
                let batch = t.recv_limited(limits).await?;
                Ok(wrap_batch(batch, AnyToken::Grpc))
            }
            #[cfg(feature = "transport-memory")]
            Self::Memory(t) => {
                let batch = t.recv_limited(limits).await?;
                Ok(wrap_batch(batch, AnyToken::Memory))
            }
            #[cfg(feature = "transport-pipe")]
            Self::Pipe(t) => {
                let batch = t.recv_limited(limits).await?;
                Ok(wrap_batch(batch, AnyToken::Pipe))
            }
            #[cfg(feature = "transport-file")]
            Self::File(t) => {
                let batch = t.recv_limited(limits).await?;
                Ok(wrap_batch(batch, AnyToken::File))
            }
            #[cfg(feature = "transport-http")]
            Self::Http(t) => {
                let batch = t.recv_limited(limits).await?;
                Ok(wrap_batch(batch, AnyToken::Http))
            }
            #[cfg(feature = "transport-redis")]
            Self::Redis(t) => {
                let batch = t.recv_limited(limits).await?;
                Ok(wrap_batch(batch, AnyToken::Redis))
            }
            #[allow(unreachable_patterns)]
            _ => Err(TransportError::Config(
                "no transport variant enabled".into(),
            )),
        }
    }

    #[cfg_attr(
        not(any(
            feature = "transport-kafka",
            feature = "transport-grpc",
            feature = "transport-memory",
            feature = "transport-pipe",
            feature = "transport-file",
            feature = "transport-http",
            feature = "transport-redis"
        )),
        allow(unused_variables)
    )]
    async fn commit(&self, tokens: &[AnyToken]) -> TransportResult<()> {
        // Each arm uses `match tok { Variant(x) => Some(x), #[allow(unreachable_patterns)] _ => None }`
        // rather than `if let`.  When only a single transport feature is enabled, the AnyToken enum
        // has a single variant, making an `if let` irrefutable (an error under -D warnings).
        // The explicit wildcard arm with `#[allow(unreachable_patterns)]` avoids that -- it is
        // genuinely unreachable in the single-feature case but legal.  Tokens from a non-matching
        // variant indicate a programming error; they are silently filtered out rather than panicking
        // (defensive behaviour, they cannot legitimately arise from this receiver's recv).
        match self {
            #[cfg(feature = "transport-kafka")]
            Self::Kafka(t) => {
                let inner: Vec<_> = tokens
                    .iter()
                    .filter_map(|tok| match tok {
                        AnyToken::Kafka(k) => Some(k.clone()),
                        #[allow(unreachable_patterns)]
                        _ => None,
                    })
                    .collect();
                t.commit(&inner).await
            }
            #[cfg(feature = "transport-grpc")]
            Self::Grpc(t) => {
                let inner: Vec<_> = tokens
                    .iter()
                    .filter_map(|tok| match tok {
                        AnyToken::Grpc(g) => Some(g.clone()),
                        #[allow(unreachable_patterns)]
                        _ => None,
                    })
                    .collect();
                t.commit(&inner).await
            }
            #[cfg(feature = "transport-memory")]
            Self::Memory(t) => {
                let inner: Vec<_> = tokens
                    .iter()
                    .filter_map(|tok| match tok {
                        AnyToken::Memory(m) => Some(*m),
                        #[allow(unreachable_patterns)]
                        _ => None,
                    })
                    .collect();
                t.commit(&inner).await
            }
            #[cfg(feature = "transport-pipe")]
            Self::Pipe(t) => {
                let inner: Vec<_> = tokens
                    .iter()
                    .filter_map(|tok| match tok {
                        AnyToken::Pipe(p) => Some(*p),
                        #[allow(unreachable_patterns)]
                        _ => None,
                    })
                    .collect();
                t.commit(&inner).await
            }
            #[cfg(feature = "transport-file")]
            Self::File(t) => {
                let inner: Vec<_> = tokens
                    .iter()
                    .filter_map(|tok| match tok {
                        AnyToken::File(f) => Some(*f),
                        #[allow(unreachable_patterns)]
                        _ => None,
                    })
                    .collect();
                t.commit(&inner).await
            }
            #[cfg(feature = "transport-http")]
            Self::Http(t) => {
                let inner: Vec<_> = tokens
                    .iter()
                    .filter_map(|tok| match tok {
                        AnyToken::Http(h) => Some(h.clone()),
                        #[allow(unreachable_patterns)]
                        _ => None,
                    })
                    .collect();
                t.commit(&inner).await
            }
            #[cfg(feature = "transport-redis")]
            Self::Redis(t) => {
                let inner: Vec<_> = tokens
                    .iter()
                    .filter_map(|tok| match tok {
                        AnyToken::Redis(r) => Some(r.clone()),
                        #[allow(unreachable_patterns)]
                        _ => None,
                    })
                    .collect();
                t.commit(&inner).await
            }
            #[allow(unreachable_patterns)]
            _ => Err(TransportError::Config(
                "no transport variant enabled".into(),
            )),
        }
    }
}

impl AnyReceiver {
    /// Create a receiver from the config cascade.
    ///
    /// Reads the transport config from the given key in the config
    /// cascade and creates the appropriate receiver.
    ///
    /// # Example config
    ///
    /// ```yaml
    /// transport:
    ///   input:
    ///     type: kafka
    ///     kafka:
    ///       brokers: ["kafka:9092"]
    ///       group_id: "my-consumer"
    /// ```
    ///
    /// ```rust,ignore
    /// let receiver = AnyReceiver::from_config("transport.input").await?;
    /// ```
    pub async fn from_config(key: &str) -> TransportResult<Self> {
        #[cfg(feature = "config")]
        let config = {
            let cfg = crate::config::try_get()
                .ok_or_else(|| TransportError::Config("config not initialised".into()))?;
            cfg.unmarshal_key::<super::TransportConfig>(key)
                .map_err(|e| TransportError::Config(format!("failed to read {key}: {e}")))?
        };

        #[cfg(not(feature = "config"))]
        let config = {
            let _ = key;
            super::TransportConfig::default()
        };

        Self::from_transport_config(&config).await
    }

    /// Create a receiver from an explicit `TransportConfig`.
    pub async fn from_transport_config(config: &super::TransportConfig) -> TransportResult<Self> {
        match config.transport_type {
            #[cfg(feature = "transport-kafka")]
            TransportType::Kafka => {
                let kafka_config = config
                    .kafka
                    .as_ref()
                    .ok_or_else(|| TransportError::Config("kafka config missing".into()))?;
                let transport = super::kafka::KafkaTransport::new(kafka_config).await?;
                Ok(Self::Kafka(transport))
            }

            #[cfg(feature = "transport-grpc")]
            TransportType::Grpc => {
                let grpc_config = config
                    .grpc
                    .as_ref()
                    .ok_or_else(|| TransportError::Config("grpc config missing".into()))?;
                let transport = super::grpc::GrpcTransport::new(grpc_config).await?;
                Ok(Self::Grpc(transport))
            }

            #[cfg(feature = "transport-memory")]
            TransportType::Memory => {
                let memory_config = config.memory.clone().unwrap_or_default();
                let transport = super::memory::MemoryTransport::new(&memory_config)?;
                Ok(Self::Memory(transport))
            }

            #[cfg(feature = "transport-pipe")]
            TransportType::Pipe => {
                let pipe_config = config.pipe.clone().unwrap_or_default();
                let transport = super::pipe::PipeTransport::new(&pipe_config);
                Ok(Self::Pipe(transport))
            }

            #[cfg(feature = "transport-file")]
            TransportType::File => {
                let file_config = config
                    .file
                    .as_ref()
                    .ok_or_else(|| TransportError::Config("file config missing".into()))?;
                let transport = super::file::FileTransport::new(file_config).await?;
                Ok(Self::File(transport))
            }

            #[cfg(feature = "transport-http")]
            TransportType::Http => {
                let http_config = config
                    .http
                    .as_ref()
                    .ok_or_else(|| TransportError::Config("http config missing".into()))?;
                let transport = super::http::HttpTransport::new(http_config).await?;
                Ok(Self::Http(transport))
            }

            #[cfg(feature = "transport-redis")]
            TransportType::Redis => {
                let redis_config = config
                    .redis
                    .as_ref()
                    .ok_or_else(|| TransportError::Config("redis config missing".into()))?;
                let transport = super::redis_transport::RedisTransport::new(redis_config).await?;
                Ok(Self::Redis(transport))
            }

            // Transport types for modules not yet implemented
            #[allow(unreachable_patterns)]
            other => Err(TransportError::Config(format!(
                "transport type '{other}' is not available (feature not enabled or not yet implemented)"
            ))),
        }
    }

    /// Create a governed receiver from the config cascade (`governor` feature).
    ///
    /// Identical to [`from_config`](Self::from_config) but threads the supplied
    /// [`SelfRegulationGovernor`](crate::SelfRegulationGovernor)'s pressure into
    /// the inbound brake of every backend that can honour it -- the Kafka
    /// pause-partitions gate and the HTTP/gRPC 503/`unavailable` shed -- so a
    /// factory-built receiver actually engages the default-on governor instead
    /// of silently dropping the inbound brake.
    ///
    /// Construction order: the `governor` (and its pressure) is built by the
    /// runtime BEFORE this call, so the pressure latch already exists and is
    /// merely cloned (cheap `Arc` bump) into each transport here.
    ///
    /// # Errors
    ///
    /// Same as [`from_config`](Self::from_config).
    #[cfg(feature = "governor")]
    pub async fn from_config_with_governor(
        key: &str,
        governor: &crate::SelfRegulationGovernor,
    ) -> TransportResult<Self> {
        #[cfg(feature = "config")]
        let config = {
            let cfg = crate::config::try_get()
                .ok_or_else(|| TransportError::Config("config not initialised".into()))?;
            cfg.unmarshal_key::<super::TransportConfig>(key)
                .map_err(|e| TransportError::Config(format!("failed to read {key}: {e}")))?
        };

        #[cfg(not(feature = "config"))]
        let config = {
            let _ = key;
            super::TransportConfig::default()
        };

        Self::from_transport_config_with_governor(&config, governor).await
    }

    /// Create a governed receiver from an explicit `TransportConfig`
    /// (`governor` feature).
    ///
    /// The governor-aware sibling of [`from_transport_config`](Self::from_transport_config).
    /// Backends that own an inbound brake are wired to the governor's shared
    /// pressure:
    ///
    /// - **Kafka**: the consumer's assigned partitions are paused/resumed via
    ///   [`SelfRegulationGovernor::attach_kafka_gate`](crate::SelfRegulationGovernor::attach_kafka_gate)
    ///   (the full `gate_actuator -> InboundGate -> with_inbound_gate` dance).
    /// - **HTTP / gRPC**: the embedded receive server is built with
    ///   `with_pressure(Some(governor.pressure()))`, so it sheds with 503 /
    ///   `Status::unavailable` while the pressure latch holds.
    ///
    /// Backends with no inbound brake (memory, pipe, file, redis) construct
    /// exactly as in [`from_transport_config`](Self::from_transport_config) --
    /// the byte-budget lever already reaches them through the governed driver.
    ///
    /// # Errors
    ///
    /// Same as [`from_transport_config`](Self::from_transport_config).
    #[cfg(feature = "governor")]
    pub async fn from_transport_config_with_governor(
        config: &super::TransportConfig,
        #[cfg_attr(
            not(any(
                feature = "transport-kafka",
                feature = "transport-grpc",
                feature = "transport-http"
            )),
            allow(unused_variables)
        )]
        governor: &crate::SelfRegulationGovernor,
    ) -> TransportResult<Self> {
        match config.transport_type {
            #[cfg(feature = "transport-kafka")]
            TransportType::Kafka => {
                let kafka_config = config
                    .kafka
                    .as_ref()
                    .ok_or_else(|| TransportError::Config("kafka config missing".into()))?;
                let transport = super::kafka::KafkaTransport::new(kafka_config).await?;
                // Attach the inbound gate over the governor's shared pressure:
                // pauses assigned partitions while the latch holds (member stays
                // in the group -- no rebalance).
                let transport = governor.attach_kafka_gate(transport);
                Ok(Self::Kafka(transport))
            }

            #[cfg(feature = "transport-grpc")]
            TransportType::Grpc => {
                let grpc_config = config
                    .grpc
                    .as_ref()
                    .ok_or_else(|| TransportError::Config("grpc config missing".into()))?;
                let transport = super::grpc::GrpcTransport::with_pressure(
                    grpc_config,
                    Some(governor.pressure()),
                )
                .await?;
                Ok(Self::Grpc(transport))
            }

            #[cfg(feature = "transport-http")]
            TransportType::Http => {
                let http_config = config
                    .http
                    .as_ref()
                    .ok_or_else(|| TransportError::Config("http config missing".into()))?;
                let transport = super::http::HttpTransport::with_pressure(
                    http_config,
                    Some(governor.pressure()),
                )
                .await?;
                Ok(Self::Http(transport))
            }

            // Backends with no inbound brake: construct identically to the
            // non-governor path. The byte-budget lever reaches these via the
            // governed driver, not an inbound gate.
            #[cfg(any(
                feature = "transport-memory",
                feature = "transport-pipe",
                feature = "transport-file",
                feature = "transport-redis"
            ))]
            _ => Self::from_transport_config(config).await,

            // No brakeable backend enabled at all: defer entirely to the
            // non-governor path (handles the "feature not enabled" error too).
            #[allow(unreachable_patterns)]
            _ => Self::from_transport_config(config).await,
        }
    }
}

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

#[cfg(all(test, feature = "transport-memory"))]
mod tests {
    use super::*;
    use crate::transport::memory::{MemoryConfig, MemoryTransport};
    use crate::transport::traits::TransportReceiver;

    /// End-to-end round-trip: inject a message, recv via `AnyReceiver`,
    /// assert token wrapping, then commit and verify the memory transport's
    /// committed sequence advances.
    ///
    /// This exercises the full token wrap + commit re-dispatch path.
    #[tokio::test]
    async fn any_receiver_memory_recv_commit_round_trip() {
        // Build the underlying transport and inject a message.
        let inner = MemoryTransport::new(&MemoryConfig::default())
            .expect("memory transport must construct with default config");
        inner
            .inject(Some("events.test"), b"hello from AnyReceiver".to_vec())
            .await
            .expect("inject must succeed");

        // Wrap in AnyReceiver.
        let receiver = AnyReceiver::Memory(inner);

        assert_eq!(receiver.name(), "memory");
        assert!(receiver.is_healthy());

        // Recv via AnyReceiver -- must yield a WorkBatch<AnyToken>.
        let batch = receiver.recv(10).await.expect("recv must succeed");
        assert_eq!(batch.records.len(), 1, "expected exactly one record");
        assert_eq!(batch.commit_tokens.len(), 1, "expected one commit token");
        assert!(batch.dlq_entries.is_empty(), "no DLQ entries expected");

        let record = &batch.records[0];
        assert_eq!(record.payload.as_ref(), b"hello from AnyReceiver");
        assert_eq!(record.key.as_deref(), Some("events.test"));

        // Token must be wrapped in the Memory variant.
        let token = &batch.commit_tokens[0];
        assert!(
            matches!(token, AnyToken::Memory(_)),
            "token variant must be AnyToken::Memory, got {token}"
        );

        // Display delegates to the inner MemoryToken (format: "memory:<seq>").
        let display = token.to_string();
        assert!(
            display.starts_with("memory:"),
            "Display must delegate to MemoryToken, got {display}"
        );

        // Commit the AnyToken slice -- routes back to the MemoryTransport.
        let tokens: Vec<AnyToken> = batch.commit_tokens;
        let seq_before = if let AnyReceiver::Memory(ref t) = receiver {
            t.committed_sequence()
        } else {
            panic!("must be Memory variant");
        };

        receiver.commit(&tokens).await.expect("commit must succeed");

        // The memory transport tracks the max committed seq; it must have advanced.
        if let AnyReceiver::Memory(ref t) = receiver {
            let seq_after = t.committed_sequence();
            assert!(
                seq_after > seq_before || seq_after == 0,
                "committed_sequence must advance after commit (before={seq_before}, after={seq_after})"
            );
        }
    }

    /// Tokens from the wrong variant are silently ignored by commit --
    /// commit must succeed without error even if no tokens match.
    #[tokio::test]
    async fn any_receiver_commit_ignores_mismatched_variants() {
        let inner = MemoryTransport::new(&MemoryConfig::default())
            .expect("memory transport must construct with default config");
        let receiver = AnyReceiver::Memory(inner);

        // A Pipe token delivered to a Memory receiver -- must not panic or error.
        #[cfg(feature = "transport-pipe")]
        {
            let alien_token = AnyToken::Pipe(crate::transport::pipe::PipeToken { seq: 99 });
            receiver
                .commit(&[alien_token])
                .await
                .expect("commit with mismatched variant must succeed without error");
        }

        // Zero tokens -- always a no-op.
        receiver
            .commit(&[])
            .await
            .expect("commit with empty slice must succeed");
    }
}

// ---------------------------------------------------------------------------
// Governor-aware factory tests (Remediation Phase 6).
//
// Prove `*_with_governor` actually threads the governor's inbound brake into
// the backends that own one, and that the non-governor path is unchanged.
// ---------------------------------------------------------------------------

#[cfg(all(test, feature = "governor"))]
mod governor_tests {
    #[cfg(any(
        feature = "transport-kafka",
        feature = "transport-grpc",
        feature = "transport-http",
        feature = "transport-memory"
    ))]
    use super::*;

    /// Build a [`SelfRegulationGovernor`] whose single HARD memory source is
    /// pinned ABOVE / BELOW `pause_above` (default 0.80) by sizing the guard.
    #[cfg(any(
        feature = "transport-kafka",
        feature = "transport-grpc",
        feature = "transport-http",
        feature = "transport-memory"
    ))]
    fn governor(pinned_high: bool) -> crate::SelfRegulationGovernor {
        use crate::memory::{MemoryGuard, MemoryGuardConfig};
        let guard = std::sync::Arc::new(MemoryGuard::new(MemoryGuardConfig {
            limit_bytes: 1000,
            pressure_threshold: 0.80,
            ..Default::default()
        }));
        if pinned_high {
            guard.add_bytes(950); // 95% -> well above pause_above
        } else {
            guard.add_bytes(10); // 1% -> well below resume_below
        }
        crate::SelfRegulationConfig::default()
            .build(guard)
            .expect("governor enabled by default")
    }

    /// A factory-built Kafka receiver MUST carry an inbound gate when a governor
    /// is supplied. Broker-free: `KafkaTransport::new` lazily connects and an
    /// empty topic list means no subscribe/poll happens at construction.
    #[cfg(feature = "transport-kafka")]
    #[tokio::test]
    async fn kafka_governed_receiver_has_inbound_gate() {
        let kafka = crate::transport::kafka::KafkaConfig::for_testing(
            "localhost:9092",
            "phase6-test",
            Vec::new(), // no topics -> no subscribe -> broker-free build
        );
        let cfg = crate::transport::TransportConfig {
            transport_type: crate::transport::types::TransportType::Kafka,
            kafka: Some(kafka),
            ..Default::default()
        };

        let gov = governor(false);
        let receiver = AnyReceiver::from_transport_config_with_governor(&cfg, &gov)
            .await
            .expect("governed kafka receiver must construct broker-free");

        match receiver {
            AnyReceiver::Kafka(ref t) => assert!(
                t.has_inbound_gate(),
                "factory-built Kafka receiver must have the governor's inbound gate attached"
            ),
            _ => panic!("expected Kafka variant"),
        }

        // The non-governor constructor must NOT attach a gate (byte-identical
        // to pre-Phase-6 behaviour).
        let plain = AnyReceiver::from_transport_config(&cfg)
            .await
            .expect("plain kafka receiver must construct broker-free");
        match plain {
            AnyReceiver::Kafka(ref t) => assert!(
                !t.has_inbound_gate(),
                "non-governor constructor must leave the inbound gate unattached"
            ),
            _ => panic!("expected Kafka variant"),
        }
    }

    /// A factory-built gRPC receiver MUST reject under pressure (governor pinned
    /// HIGH) with `Status::unavailable`, surfaced to the client as backpressure.
    #[cfg(feature = "transport-grpc")]
    #[tokio::test]
    async fn grpc_governed_receiver_sheds_under_pressure() {
        use crate::transport::traits::{TransportBase, TransportSender};
        use crate::transport::types::SendResult;

        let server_cfg = crate::transport::grpc::GrpcConfig::server("127.0.0.1:16188");
        let cfg = crate::transport::TransportConfig {
            transport_type: crate::transport::types::TransportType::Grpc,
            grpc: Some(server_cfg),
            ..Default::default()
        };

        let gov = governor(true);
        assert!(
            gov.pressure().should_hold(),
            "pinned-high governor must hold"
        );

        let server = AnyReceiver::from_transport_config_with_governor(&cfg, &gov)
            .await
            .expect("governed grpc receiver must construct");
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let client = crate::transport::grpc::GrpcTransport::new(
            &crate::transport::grpc::GrpcConfig::client("http://127.0.0.1:16188"),
        )
        .await
        .expect("grpc client");
        let result = client
            .send("events", bytes::Bytes::from_static(b"{\"x\":1}"))
            .await;
        assert!(
            matches!(result, SendResult::Backpressured),
            "push under pressure must surface as backpressure, got {result:?}"
        );

        client.close().await.unwrap();
        server.close().await.unwrap();
    }

    /// A factory-built HTTP receiver MUST shed with 503 under pressure (governor
    /// pinned HIGH); the shed request never reaches the queue.
    #[cfg(feature = "transport-http")]
    #[tokio::test]
    async fn http_governed_receiver_sheds_under_pressure() {
        use crate::transport::traits::{TransportBase, TransportReceiver};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        drop(listener);

        let http_cfg = crate::transport::http::HttpTransportConfig {
            listen: Some(addr.to_string()),
            recv_timeout_ms: 200,
            ..Default::default()
        };
        let cfg = crate::transport::TransportConfig {
            transport_type: crate::transport::types::TransportType::Http,
            http: Some(http_cfg),
            ..Default::default()
        };

        let gov = governor(true);
        assert!(
            gov.pressure().should_hold(),
            "pinned-high governor must hold"
        );

        let receiver = AnyReceiver::from_transport_config_with_governor(&cfg, &gov)
            .await
            .expect("governed http receiver must construct");
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let client = reqwest::Client::new();
        let resp = client
            .post(format!("http://127.0.0.1:{}/ingest", addr.port()))
            .body(b"{\"msg\":\"shed\"}".to_vec())
            .send()
            .await
            .unwrap();
        assert_eq!(
            resp.status(),
            reqwest::StatusCode::SERVICE_UNAVAILABLE,
            "factory-built HTTP receiver under pressure must shed with 503"
        );

        let records = receiver.recv(10).await.unwrap().records;
        assert!(records.is_empty(), "shed request must not be queued");
        receiver.close().await.unwrap();
    }

    /// Backends with no inbound brake (memory) construct identically through the
    /// governor-aware path -- the receiver still works as a plain receiver.
    #[cfg(feature = "transport-memory")]
    #[tokio::test]
    async fn memory_governed_receiver_is_plain() {
        use crate::transport::traits::TransportReceiver;

        let cfg = crate::transport::TransportConfig {
            transport_type: crate::transport::types::TransportType::Memory,
            memory: Some(crate::transport::memory::MemoryConfig::default()),
            ..Default::default()
        };

        let gov = governor(false);
        let receiver = AnyReceiver::from_transport_config_with_governor(&cfg, &gov)
            .await
            .expect("governed memory receiver must construct");

        assert_eq!(receiver.name(), "memory");
        // No gate concept for memory -- recv just returns an empty batch.
        let batch = receiver.recv(1).await.expect("recv must succeed");
        assert!(batch.records.is_empty(), "no records injected");
    }
}