dynamo-runtime 1.6.1

Dynamo Runtime Library
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
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Network layer for distributed communication
//!
//! Provides request distribution across multiple transport protocols:
//! - HTTP/2 for standard deployments
//! - TCP with length-prefixed protocol for high-performance scenarios
//! - NATS for legacy/messaging-based deployments

pub mod codec;
pub mod egress;
pub mod ingress;
pub mod manager;
pub mod quic_response;
pub mod tcp;

use crate::SystemHealth;
use crate::error::{DynamoError, ErrorType};
use crate::traits::DistributedRuntimeProvider;
use std::sync::{Arc, OnceLock};

use anyhow::Result;
use async_trait::async_trait;
use bytes::Bytes;
use codec::{TwoPartCodec, TwoPartMessage, TwoPartMessageType};
use derive_builder::Builder;
use futures::StreamExt;
// io::Cursor, TryStreamExt
use super::{AsyncEngine, AsyncEngineContext, AsyncEngineContextProvider, ResponseStream};
use serde::{Deserialize, Serialize, de::DeserializeOwned};

use super::{
    AsyncTransportEngine, Context, Data, Error, ManyIn, ManyOut, PipelineError, PipelineIO,
    SegmentSource, ServiceBackend, ServiceEngine, SingleIn, Source, context,
};
use crate::metrics::MetricsHierarchy;
use crate::metrics::prometheus_names::work_handler;
use crate::protocols::maybe_error::MaybeError;
use crate::telemetry::LifecycleOperationRole;
use ingress::push_handler::WorkHandlerMetrics;
use prometheus::{CounterVec, Histogram, IntCounter, IntCounterVec, IntGauge};

/// Shared default maximum TCP message size across request-plane components.
pub(crate) const DEFAULT_TCP_MAX_MESSAGE_SIZE: usize = 32 * 1024 * 1024;

/// Prefix a request-plane server writes on the request connection to reject a request it cannot
/// serve. The client matches on it to classify the reply as a rejection rather than the success
/// ACK; anything it does not recognise is read as the ACK and it waits for a response stream.
/// Both ends must use this constant.
pub(crate) const ACK_UNAVAILABLE_PREFIX: &str = "Server unavailable:";

static REQUEST_PLANE_PAYLOAD_CODEC: OnceLock<RequestPlanePayloadCodec> = OnceLock::new();
static RESPONSE_PLANE_MODE: OnceLock<ResponsePlaneMode> = OnceLock::new();

/// Process-wide response transport. Frontends and workers must use the same mode.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ResponsePlaneMode {
    #[default]
    Tcp,
    Quic,
}

impl ResponsePlaneMode {
    pub fn configured() -> Result<Self> {
        if let Some(mode) = RESPONSE_PLANE_MODE.get() {
            return Ok(*mode);
        }
        let value =
            std::env::var(crate::config::environment_names::response_plane::DYN_RESPONSE_PLANE)
                .ok();
        let mode = Self::from_config_value(value.as_deref())?;
        Ok(*RESPONSE_PLANE_MODE.get_or_init(|| mode))
    }

    fn from_config_value(value: Option<&str>) -> Result<Self> {
        match value {
            None | Some("tcp") => Ok(Self::Tcp),
            Some("quic") => Ok(Self::Quic),
            Some(other) => anyhow::bail!(
                "invalid {} value '{other}'; expected 'tcp' or 'quic'",
                crate::config::environment_names::response_plane::DYN_RESPONSE_PLANE
            ),
        }
    }

    pub fn from_transport_name(transport: &str) -> Result<Self> {
        match transport {
            "tcp_server" => Ok(Self::Tcp),
            quic_response::TRANSPORT_NAME => Ok(Self::Quic),
            other => anyhow::bail!("unsupported response transport '{other}'"),
        }
    }

    pub const fn name(self) -> &'static str {
        match self {
            Self::Tcp => "tcp",
            Self::Quic => "quic",
        }
    }
}

crate::env_config! {
    /// Read the configured TCP max message size once and share it across client,
    /// server, and zero-copy decoder code paths.
    pub(crate) fn get_tcp_max_message_size() -> usize =
        crate::config::environment_names::request_plane::DYN_TCP_MAX_MESSAGE_SIZE,
        default = DEFAULT_TCP_MAX_MESSAGE_SIZE;
}

#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RequestPlanePayloadCodec {
    /// The serde default deliberately remains JSON for wire compatibility with
    /// control messages produced before the payload codec field existed.
    #[default]
    Json,
    Msgpack,
}

impl RequestPlanePayloadCodec {
    pub fn configured() -> Self {
        *REQUEST_PLANE_PAYLOAD_CODEC.get_or_init(Self::from_env)
    }

    fn from_env() -> Self {
        let value =
            std::env::var(crate::config::environment_names::request_plane::DYN_REQUEST_PLANE_CODEC)
                .ok();
        Self::from_config_value(value.as_deref())
    }

    fn from_config_value(value: Option<&str>) -> Self {
        match value {
            None | Some("") | Some("msgpack") => Self::Msgpack,
            Some("json") => Self::Json,
            Some(other) => {
                tracing::warn!(
                    env_var =
                        crate::config::environment_names::request_plane::DYN_REQUEST_PLANE_CODEC,
                    value = other,
                    "invalid request plane payload codec, defaulting to msgpack"
                );
                Self::Msgpack
            }
        }
    }

    pub fn name(&self) -> &'static str {
        match self {
            Self::Json => "json",
            Self::Msgpack => "msgpack",
        }
    }

    pub fn encode<T: Serialize>(&self, value: &T) -> Result<Vec<u8>> {
        match self {
            Self::Json => Ok(serde_json::to_vec(value)?),
            Self::Msgpack => Ok(rmp_serde::to_vec_named(value)?),
        }
    }

    /// Encode into a caller-owned writer, so a hot path can reuse one buffer
    /// across frames instead of allocating per frame.
    ///
    /// Emits the same bytes as [`Self::encode`], which
    /// `encode_into_matches_encode_byte_for_byte` pins for both codecs.
    pub fn encode_into<T, W>(&self, value: &T, writer: &mut W) -> Result<()>
    where
        T: Serialize + ?Sized,
        W: std::io::Write,
    {
        match self {
            Self::Json => Ok(serde_json::to_writer(writer, value)?),
            Self::Msgpack => Ok(rmp_serde::encode::write_named(writer, value)?),
        }
    }

    pub fn decode<T: DeserializeOwned>(&self, bytes: &[u8]) -> Result<T> {
        match self {
            Self::Json => Ok(serde_json::from_slice(bytes)?),
            Self::Msgpack => Ok(rmp_serde::from_slice(bytes)?),
        }
    }
}

/// Starting capacity for a buffer that one response frame is encoded into.
///
/// Matches `serde_json::to_vec`'s own default so msgpack — which otherwise
/// starts at zero — stops regrowing its buffer on every streamed frame.
pub const RESPONSE_ENCODE_CAPACITY_HINT: usize = 128;

pub trait Codable: PipelineIO + Serialize + for<'de> Deserialize<'de> {}
impl<T: PipelineIO + Serialize + for<'de> Deserialize<'de>> Codable for T {}

/// `WorkQueueConsumer` is a generic interface for a work queue that can be used to send and receive
#[async_trait]
pub trait WorkQueueConsumer {
    async fn dequeue(&self) -> Result<Bytes, String>;
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum StreamType {
    Request,
    Response,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum RequestType {
    SingleIn,
    ManyIn,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ResponseType {
    SingleOut,
    ManyOut,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct RequestControlMessage {
    pub(crate) id: String,
    pub(crate) request_type: RequestType,
    pub(crate) response_type: ResponseType,
    #[serde(default)]
    pub(crate) payload_codec: RequestPlanePayloadCodec,
    pub(crate) connection_info: ConnectionInfo,
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub(crate) metadata: std::collections::BTreeMap<String, String>,
    /// Wall-clock send timestamp (nanos since UNIX epoch) for transport latency breakdown.
    /// Uses `SystemTime` so accuracy depends on NTP sync between frontend and backend hosts.
    /// Reliable for single-machine profiling; treat cross-host values as approximate.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) frontend_send_ts_ns: Option<u64>,
    /// For bidirectional dispatch (`request_type == ManyIn`): connection info the
    /// worker dials back to in order to receive subsequent request frames. `None`
    /// for the unary path, which is the wire-compatible default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) request_stream_connection_info: Option<ConnectionInfo>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ControlMessage {
    Stop,
    Kill,
    Sentinel,
}

/// This is the first message in a `ResponseStream`. This is not a message that gets process
/// by the general pipeline, but is a control message that is awaited before the
/// [`AsyncEngine::generate`] method is allowed to return.
///
/// If an error is present, the [`AsyncEngine::generate`] method will return the error instead
/// of returning the `ResponseStream`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ResponseStreamPrologue {
    error: Option<String>,

    /// The same failure as `error`, but keeping the worker's
    /// [`crate::error::ErrorType`] instead of only its display text, so the
    /// frontend can classify a
    /// pre-stream failure (for example, a backend refusing a request it can
    /// never serve) rather than guessing from a message.
    ///
    /// `Option` plus `#[serde(default)]` is a compatibility requirement, not a
    /// convenience: worker and frontend are deployed independently, so during a
    /// rolling upgrade an old worker sends a prologue without this field and a
    /// new worker sends one an old frontend does not know. A required field
    /// would break the handshake in both directions; an absent field or unrecognized legacy
    /// `error_type` decodes to `None` and the frontend falls back to the untyped behavior.
    /// A payload with the semantic `class` field uses `DynamoError`'s fail-closed policy.
    #[serde(
        default,
        deserialize_with = "deserialize_typed_error",
        skip_serializing_if = "Option::is_none"
    )]
    typed_error: Option<DynamoError>,
}

fn deserialize_typed_error<'de, D>(deserializer: D) -> Result<Option<DynamoError>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let typed_error = Option::<serde_json::Value>::deserialize(deserializer)?;
    Ok(typed_error.and_then(|typed_error| {
        // The legacy enum decoder rejected future variants. ErrorClass is tolerant, so
        // compare the raw value with its canonical round trip to preserve that fallback.
        if typed_error.get("class").is_none()
            && let Some(wire_error_type) = typed_error.get("error_type")
        {
            let round_trip = serde_json::from_value::<ErrorType>(wire_error_type.clone())
                .ok()
                .and_then(|error_type| serde_json::to_value(error_type).ok());
            if round_trip.as_ref() != Some(wire_error_type) {
                return None;
            }
        }
        serde_json::from_value(typed_error).ok()
    }))
}

/// A pre-stream failure as it reaches the requesting side of the transport.
///
/// `message` is the display text the prologue has always carried.
/// `typed_error` is the worker's own [`DynamoError`] when the worker was new
/// enough to send one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StreamPrologueError {
    pub message: String,
    pub typed_error: Option<DynamoError>,
}

impl StreamPrologueError {
    /// A failure detected by the transport itself, with no worker error behind it.
    pub fn from_message(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            typed_error: None,
        }
    }

    /// A worker failure, keeping the display text the prologue has always
    /// carried alongside the worker's typed error.
    pub fn new(message: impl Into<String>, typed_error: DynamoError) -> Self {
        Self {
            message: message.into(),
            typed_error: Some(typed_error),
        }
    }
}

impl std::fmt::Display for StreamPrologueError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

/// Derefs to the message so code written against the previous `String` error
/// keeps working: `err.contains(..)`, `err.len()`, `&err[..]` all still resolve.
/// Only an explicit `String` type annotation or signature needs updating.
impl std::ops::Deref for StreamPrologueError {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.message
    }
}

impl AsRef<str> for StreamPrologueError {
    fn as_ref(&self) -> &str {
        &self.message
    }
}

impl From<String> for StreamPrologueError {
    fn from(message: String) -> Self {
        Self::from_message(message)
    }
}

impl From<&str> for StreamPrologueError {
    fn from(message: &str) -> Self {
        Self::from_message(message)
    }
}

/// Resolves once the worker's response stream is established, or with a
/// [`StreamPrologueError`] carrying both the failure's display text and, when
/// the worker sent one, its [`crate::error::ErrorType`], so the requesting side
/// can classify a pre-stream failure without parsing the message.
pub type StreamProvider<T> = tokio::sync::oneshot::Receiver<Result<T, StreamPrologueError>>;

/// Owning `Drop` here (rather than on `RegisteredStream`) lets `into_parts()`
/// move the public fields out by plain destructure.
struct Cleanup(Option<Box<dyn FnOnce() + Send + 'static>>);

impl Drop for Cleanup {
    fn drop(&mut self) {
        if let Some(f) = self.0.take() {
            f();
        }
    }
}

/// Awaitable handle for a stream sender or receiver. Dropping the handle without
/// a successful `wait()` or a call to `into_parts()` runs the optional cleanup
/// closure, removing the registration from the stream server's maps.
pub struct RegisteredStream<T> {
    pub connection_info: ConnectionInfo,
    pub stream_provider: StreamProvider<T>,
    registration_id: Option<uuid::Uuid>,
    cleanup: Cleanup,
}

impl<T> std::fmt::Debug for RegisteredStream<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RegisteredStream")
            .field("connection_info", &self.connection_info)
            .finish_non_exhaustive()
    }
}

impl<T> RegisteredStream<T> {
    pub(crate) fn new(connection_info: ConnectionInfo, stream_provider: StreamProvider<T>) -> Self {
        Self {
            connection_info,
            stream_provider,
            registration_id: None,
            cleanup: Cleanup(None),
        }
    }

    pub(crate) fn with_registration_id(mut self, registration_id: uuid::Uuid) -> Self {
        self.registration_id = Some(registration_id);
        self
    }

    pub(crate) fn registration_id(&self) -> Option<uuid::Uuid> {
        self.registration_id
    }

    pub(crate) fn with_cleanup<F>(mut self, cleanup: F) -> Self
    where
        F: FnOnce() + Send + 'static,
    {
        self.cleanup.0 = Some(Box::new(cleanup));
        self
    }

    /// Consume the registration, disarming the RAII cleanup. Caller takes
    /// responsibility for cleanup if the stream provider is never awaited.
    pub fn into_parts(self) -> (ConnectionInfo, StreamProvider<T>) {
        let Self {
            connection_info,
            stream_provider,
            registration_id: _,
            mut cleanup,
        } = self;
        cleanup.0.take();
        (connection_info, stream_provider)
    }

    /// Await the stream provider, keeping registration cleanup armed until success.
    ///
    /// An error or a dropped future removes the registration from the transport.
    /// Once the stream is established, cleanup is disarmed and the transport owns
    /// the stream's remaining lifecycle.
    pub async fn wait(
        mut self,
    ) -> Result<Result<T, StreamPrologueError>, tokio::sync::oneshot::error::RecvError> {
        let result = (&mut self.stream_provider).await;
        if matches!(result, Ok(Ok(_))) {
            self.cleanup.0.take();
        }
        result
    }
}

/// After registering a stream, the [`PendingConnections`] object is returned to the caller. This
/// object can be used to await the connection to be established.
pub struct PendingConnections {
    pub send_stream: Option<RegisteredStream<StreamSender>>,
    pub recv_stream: Option<RegisteredStream<StreamReceiver>>,
}

impl PendingConnections {
    pub fn into_parts(
        self,
    ) -> (
        Option<RegisteredStream<StreamSender>>,
        Option<RegisteredStream<StreamReceiver>>,
    ) {
        (self.send_stream, self.recv_stream)
    }
}

/// A [`ResponseService`] implements a services in which a context a specific subject with will
/// be associated with a stream of responses.
#[async_trait::async_trait]
pub trait ResponseService {
    async fn register(&self, options: StreamOptions) -> PendingConnections;
}

#[cfg(test)]
mod registered_stream_tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, Ordering};

    fn dummy_conn_info() -> ConnectionInfo {
        ConnectionInfo {
            transport: "test".to_string(),
            info: "{}".to_string(),
        }
    }

    /// Drop without `into_parts()` must run the cleanup closure.
    #[test]
    fn drop_runs_cleanup() {
        let flag = Arc::new(AtomicBool::new(false));
        let flag_clone = flag.clone();

        let (_tx, rx) = tokio::sync::oneshot::channel::<Result<(), StreamPrologueError>>();
        let stream = RegisteredStream::new(dummy_conn_info(), rx).with_cleanup(move || {
            flag_clone.store(true, Ordering::SeqCst);
        });

        drop(stream);
        assert!(
            flag.load(Ordering::SeqCst),
            "cleanup must fire when RegisteredStream is dropped"
        );
    }

    /// `into_parts()` must disarm the cleanup. After the call, dropping the
    /// returned halves must NOT trigger the closure -- the caller has taken
    /// ownership of cleanup responsibility.
    #[test]
    fn into_parts_disarms_cleanup() {
        let flag = Arc::new(AtomicBool::new(false));
        let flag_clone = flag.clone();

        let (_tx, rx) = tokio::sync::oneshot::channel::<Result<(), StreamPrologueError>>();
        let stream = RegisteredStream::new(dummy_conn_info(), rx).with_cleanup(move || {
            flag_clone.store(true, Ordering::SeqCst);
        });

        let (conn, provider) = stream.into_parts();
        drop(conn);
        drop(provider);

        assert!(
            !flag.load(Ordering::SeqCst),
            "into_parts() must disarm the cleanup closure"
        );
    }

    #[tokio::test]
    async fn successful_wait_disarms_cleanup() {
        let flag = Arc::new(AtomicBool::new(false));
        let flag_clone = flag.clone();
        let (tx, rx) = tokio::sync::oneshot::channel();
        let stream = RegisteredStream::new(dummy_conn_info(), rx).with_cleanup(move || {
            flag_clone.store(true, Ordering::SeqCst);
        });

        tx.send(Ok(42)).unwrap();
        assert_eq!(stream.wait().await.unwrap().unwrap(), 42);
        assert!(
            !flag.load(Ordering::SeqCst),
            "successful wait must disarm cleanup"
        );
    }

    #[tokio::test]
    async fn failed_prologue_wait_runs_cleanup() {
        let flag = Arc::new(AtomicBool::new(false));
        let flag_clone = flag.clone();
        let (tx, rx) = tokio::sync::oneshot::channel::<Result<(), StreamPrologueError>>();
        let stream = RegisteredStream::new(dummy_conn_info(), rx).with_cleanup(move || {
            flag_clone.store(true, Ordering::SeqCst);
        });
        let error = StreamPrologueError::from_message("worker rejected request");

        tx.send(Err(error.clone())).unwrap();
        assert_eq!(stream.wait().await.unwrap().unwrap_err(), error);
        assert!(
            flag.load(Ordering::SeqCst),
            "failed prologue must run cleanup"
        );
    }

    #[tokio::test]
    async fn closed_provider_wait_runs_cleanup() {
        let flag = Arc::new(AtomicBool::new(false));
        let flag_clone = flag.clone();
        let (tx, rx) = tokio::sync::oneshot::channel::<Result<(), StreamPrologueError>>();
        let stream = RegisteredStream::new(dummy_conn_info(), rx).with_cleanup(move || {
            flag_clone.store(true, Ordering::SeqCst);
        });

        drop(tx);
        assert!(stream.wait().await.is_err());
        assert!(
            flag.load(Ordering::SeqCst),
            "closed provider must run cleanup"
        );
    }

    /// `RegisteredStream` with no cleanup configured must drop cleanly.
    #[test]
    fn drop_without_cleanup_is_a_noop() {
        let (_tx, rx) = tokio::sync::oneshot::channel::<Result<(), StreamPrologueError>>();
        let stream: RegisteredStream<()> = RegisteredStream::new(dummy_conn_info(), rx);
        drop(stream); // must not panic; nothing observable to assert beyond that
    }
}

// #[derive(Debug, Clone, Serialize, Deserialize)]
// struct Handshake {
//     request_id: String,
//     worker_id: Option<String>,
//     error: Option<String>,
// }

// impl Handshake {
//     pub fn validate(&self) -> Result<(), String> {
//         if let Some(e) = &self.error {
//             return Err(e.clone());
//         }
//         Ok(())
//     }
// }

// this probably needs to be come a ResponseStreamSender
// since the prologue in this scenario sender telling the receiver
// that all is good and it's ready to send
//
// in the RequestStreamSender, the prologue would be coming from the
// receiver, so the sender would have to await the prologue which if
// was not an error, would indicate the RequestStreamReceiver is read
// to receive data.
pub struct StreamSender {
    tx: tokio::sync::mpsc::Sender<TwoPartMessage>,
    prologue: Option<ResponseStreamPrologue>,
}

impl StreamSender {
    pub async fn send(&self, data: Bytes) -> Result<()> {
        Ok(self.tx.send(TwoPartMessage::from_data(data)).await?)
    }

    pub async fn send_control(&self, control: ControlMessage) -> Result<()> {
        let bytes = serde_json::to_vec(&control)?;
        Ok(self
            .tx
            .send(TwoPartMessage::from_header(bytes.into()))
            .await?)
    }

    /// Send the prologue, reporting an untyped failure.
    ///
    /// A caller holding the worker's typed error uses
    /// [`Self::send_prologue_typed`] instead, which keeps that type on the wire.
    pub async fn send_prologue(&mut self, error: Option<String>) -> Result<(), String> {
        self.send_prologue_typed(error.map(StreamPrologueError::from_message))
            .await
    }

    pub async fn send_prologue_typed(
        &mut self,
        error: Option<StreamPrologueError>,
    ) -> Result<(), String> {
        // leaving the original logic in place for now
        if let Some(_prologue) = self.prologue.take() {
            let (error, typed_error) = match error {
                Some(StreamPrologueError {
                    message,
                    typed_error,
                }) => (Some(message), typed_error),
                None => (None, None),
            };
            let prologue = ResponseStreamPrologue { error, typed_error };
            let header_bytes: Bytes = match serde_json::to_vec(&prologue) {
                Ok(b) => b.into(),
                Err(err) => {
                    tracing::error!(%err, "send_prologue: ResponseStreamPrologue did not serialize to a JSON array");
                    return Err("Invalid prologue".to_string());
                }
            };
            self.tx
                .send(TwoPartMessage::from_header(header_bytes))
                .await
                .map_err(|e| e.to_string())?;
        } else {
            panic!("Prologue already sent; or not set; logic error");
        }
        Ok(())
    }
}

pub struct StreamReceiver {
    rx: tokio::sync::mpsc::Receiver<Bytes>,
}

/// Connection Info is encoded as JSON and then again serialized has part of the Transport
/// Layer. The double serialization is not performance critical as it is only done once per
/// connection. The primary reason storing the ConnecitonInfo has a JSON string is for type
/// erasure. The Transport Layer will check the [`ConnectionInfo::transport`] type and then
/// route it to the appropriate instance of the Transport, which will then deserialize the
/// [`ConnectionInfo::info`] field to its internal connection info object.
///
/// Optionally, this object could become strongly typed for which all possible combinations
/// of transport and connection info would need to be enumerated.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionInfo {
    pub transport: String,
    pub info: String,
}

/// Default number of frames buffered between the data-plane socket task and the
/// engine consumer/producer for a single stream. Preserves the historically
/// hard-coded mpsc channel capacity used by the TCP transport.
pub const DEFAULT_SEND_BUFFER_COUNT: usize = 64;

/// When registering a new TransportStream on the server, the caller specifies if the
/// stream is a sender, receiver or both.
///
/// Senders and Receivers are with share a Context, but result in separate tcp socket
/// connections to the server. Internally, we may use bcast channels to coordinate the
/// internal control messages between the sender and receiver socket connections.
#[derive(Clone, Builder)]
pub struct StreamOptions {
    /// Context
    pub context: Arc<dyn AsyncEngineContext>,

    /// Register with the server that this connection will have a server-side Sender
    /// that can be picked up by the Request/Forward pipeline. The downstream side
    /// dials in via [`crate::pipeline::network::tcp::client::TcpClient::create_request_stream`]
    /// to receive the frames the server pushes.
    pub enable_request_stream: bool,

    /// Register with the server that this connection will have a server-side Receiver
    /// that can be picked up by the Response/Reverse pipeline
    pub enable_response_stream: bool,

    /// Preserve guarded dispatch setup until the worker sends its prologue.
    #[builder(default)]
    pub defer_cancellation_until_prologue: bool,

    /// The number of frames buffered between the data-plane socket task and the
    /// engine consumer/producer before backpressure kicks in. Drives the mpsc
    /// channel capacity for the per-stream buffer in the TCP transport.
    #[builder(default = "DEFAULT_SEND_BUFFER_COUNT")]
    pub send_buffer_count: usize,

    /// The number of messages to buffer before blocking
    #[builder(default = "8")]
    pub recv_buffer_count: usize,
}

impl StreamOptions {
    pub fn builder() -> StreamOptionsBuilder {
        StreamOptionsBuilder::default()
    }
}

pub struct Egress<Req: PipelineIO, Resp: PipelineIO> {
    transport_engine: Arc<dyn AsyncTransportEngine<Req, Resp>>,
}

#[cfg(test)]
mod tests {
    use super::{
        DEFAULT_SEND_BUFFER_COUNT, Ingress, IngressResponseEncoder, ManyOut, NetworkStreamWrapper,
        RequestControlMessage, RequestPlanePayloadCodec, RequestType, ResponsePlaneMode,
        ResponseStreamPrologue, ResponseType, SerdeIngressPayloadAdapter, SingleIn, StreamOptions,
        StreamPrologueError,
    };
    use crate::engine::AsyncEngineContextProvider;
    use crate::error::{BackendError, DynamoError, ErrorType};
    use crate::pipeline::Context;
    use crate::protocols::annotated::Annotated;
    use crate::telemetry::LifecycleOperationRole;
    use serde::{Deserialize, Serialize};
    use std::sync::{Arc, OnceLock};

    #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
    struct TestPayload {
        id: u64,
        text: String,
        tokens: Vec<u32>,
    }

    #[test]
    fn prologue_without_typed_error_field_still_decodes() {
        let legacy = br#"{"error":"Generate Error: something went wrong"}"#;
        let prologue: ResponseStreamPrologue =
            serde_json::from_slice(legacy).expect("a prologue without the typed field must decode");

        assert_eq!(
            prologue.error.as_deref(),
            Some("Generate Error: something went wrong")
        );
        assert!(
            prologue.typed_error.is_none(),
            "an absent typed error must decode to None, not fail"
        );
    }

    /// Pins the `String` compat shim on the widened `StreamProvider` error:
    /// `str` methods and `String` conversion must keep resolving without a
    /// field access, or the source break gets wider than intended.
    #[test]
    fn stream_prologue_error_substitutes_for_the_previous_string() {
        let err = StreamPrologueError::from_message("malformed prologue: bad header");

        assert!(err.contains("malformed prologue"));
        assert!(err.starts_with("malformed"));
        assert_eq!(err.len(), "malformed prologue: bad header".len());
        assert_eq!(&err[..9], "malformed");
        assert_eq!(err.as_ref() as &str, "malformed prologue: bad header");

        let converted: StreamPrologueError = "from a &str".into();
        assert_eq!(converted.message, "from a &str");
        assert!(converted.typed_error.is_none());

        let converted: StreamPrologueError = String::from("from a String").into();
        assert_eq!(converted.message, "from a String");
    }

    #[test]
    fn prologue_round_trips_the_typed_error() {
        let prologue = ResponseStreamPrologue {
            error: Some("Generate Error: unsupported input".to_string()),
            typed_error: Some(
                DynamoError::builder()
                    .error_type(ErrorType::Backend(BackendError::InvalidArgument))
                    .message("unsupported input")
                    .build(),
            ),
        };

        let encoded = serde_json::to_vec(&prologue).expect("prologue should serialize");
        let decoded: ResponseStreamPrologue =
            serde_json::from_slice(&encoded).expect("prologue should deserialize");

        assert_eq!(decoded, prologue);
        assert_eq!(
            decoded.typed_error.map(|e| e.error_type()),
            Some(ErrorType::Backend(BackendError::InvalidArgument))
        );
    }

    #[test]
    fn prologue_accepts_a_known_legacy_typed_error() {
        let legacy = br#"{
            "error":"Generate Error: unsupported input",
            "typed_error":{"error_type":"InvalidArgument","message":"unsupported input"}
        }"#;
        let prologue: ResponseStreamPrologue =
            serde_json::from_slice(legacy).expect("a known legacy typed error must decode");
        let error = prologue
            .typed_error
            .expect("a known legacy typed error must remain typed");

        assert_eq!(error.error_type(), ErrorType::InvalidArgument);
        assert_eq!(error.class(), ErrorType::InvalidRequest);
        assert_eq!(error.reason().as_str(), "request.invalid_argument");
    }

    #[test]
    fn prologue_ignores_a_future_legacy_typed_error() {
        let future = br#"{
            "error":"Generate Error: future failure",
            "typed_error":{"error_type":"VariantFromTheFuture","message":"future failure"}
        }"#;
        let prologue: ResponseStreamPrologue = serde_json::from_slice(future)
            .expect("a future legacy typed error must not reject the prologue");

        assert!(prologue.typed_error.is_none());
    }

    #[test]
    fn prologue_fails_closed_for_a_future_semantic_class() {
        let future = br#"{
            "error":"Generate Error: future failure",
            "typed_error":{
                "class":"FutureErrorClass",
                "reason":"runtime.internal",
                "public":{"type":"message","message":"must not escape"}
            }
        }"#;
        let prologue: ResponseStreamPrologue = serde_json::from_slice(future)
            .expect("a future semantic class must not reject the prologue");
        let error = prologue
            .typed_error
            .expect("semantic errors use the DynamoError fail-closed identity");

        assert_eq!(error.class(), ErrorType::Internal);
        assert_eq!(error.reason().as_str(), "runtime.invalid_error");
        assert!(error.public_details().is_none());
    }

    #[test]
    fn response_plane_mode_parses_supported_values() {
        assert_eq!(
            ResponsePlaneMode::from_config_value(None).unwrap(),
            ResponsePlaneMode::Tcp
        );
        assert_eq!(
            ResponsePlaneMode::from_config_value(Some("tcp")).unwrap(),
            ResponsePlaneMode::Tcp
        );
        assert_eq!(
            ResponsePlaneMode::from_config_value(Some("quic")).unwrap(),
            ResponsePlaneMode::Quic
        );
        assert!(ResponsePlaneMode::from_config_value(Some("")).is_err());
        assert!(ResponsePlaneMode::from_config_value(Some("invalid")).is_err());
    }

    #[test]
    fn encode_into_matches_encode_byte_for_byte() {
        let payload = NetworkStreamWrapper {
            data: Some(TestPayload {
                id: 7,
                text: "hello".to_string(),
                tokens: vec![1, 200, 70_000],
            }),
            complete_final: false,
        };

        for codec in [
            RequestPlanePayloadCodec::Json,
            RequestPlanePayloadCodec::Msgpack,
        ] {
            let expected = codec.encode(&payload).expect("encode");
            let mut actual = Vec::new();
            codec
                .encode_into(&payload, &mut actual)
                .expect("encode_into");
            assert_eq!(expected, actual, "codec={}", codec.name());
        }
    }

    #[test]
    fn stream_options_send_buffer_count_defaults_to_64() {
        let context = Context::new(());
        let options = StreamOptions::builder()
            .context(context.context())
            .enable_request_stream(true)
            .enable_response_stream(true)
            .build()
            .expect("stream options should build");

        assert_eq!(DEFAULT_SEND_BUFFER_COUNT, 64);
        assert_eq!(options.send_buffer_count, DEFAULT_SEND_BUFFER_COUNT);
    }

    #[test]
    fn stream_options_send_buffer_count_overrides_default() {
        let context = Context::new(());
        let options = StreamOptions::builder()
            .context(context.context())
            .enable_request_stream(true)
            .enable_response_stream(true)
            .send_buffer_count(128)
            .build()
            .expect("stream options should build");

        assert_eq!(options.send_buffer_count, 128);
    }

    #[test]
    fn ingress_observes_lifecycle_role_set_after_binding() {
        let ingress = Ingress::<SingleIn<String>, ManyOut<String>>::new();
        let endpoint_role = Arc::new(OnceLock::new());

        ingress
            .lifecycle_operation_role
            .set(endpoint_role.clone())
            .expect("new ingress lifecycle role source must be empty");
        assert_eq!(ingress.registered_lifecycle_role(), None);

        endpoint_role
            .set(LifecycleOperationRole::Prefill)
            .expect("new endpoint lifecycle role cell must be empty");
        assert_eq!(
            ingress.registered_lifecycle_role(),
            Some(LifecycleOperationRole::Prefill)
        );
    }

    #[test]
    fn legacy_frontend_control_message_defaults_payload_codec_to_json() {
        let json = r#"{
            "id": "request-123",
            "request_type": "single_in",
            "response_type": "many_out",
            "connection_info": {
                "transport": "tcp",
                "info": "{}"
            }
        }"#;

        let message: RequestControlMessage =
            serde_json::from_str(json).expect("control message should deserialize");

        assert_eq!(message.id, "request-123");
        assert!(matches!(message.request_type, RequestType::SingleIn));
        assert!(matches!(message.response_type, ResponseType::ManyOut));
        assert_eq!(message.payload_codec, RequestPlanePayloadCodec::Json);
        assert_eq!(message.connection_info.transport, "tcp");
        assert_eq!(message.connection_info.info, "{}");
        assert!(message.metadata.is_empty());
        assert!(message.frontend_send_ts_ns.is_none());

        let payload = br#"{"id":7,"text":"legacy","tokens":[1,2]}"#;
        let decoded: TestPayload = message
            .payload_codec
            .decode(payload)
            .expect("worker should decode the legacy frontend's JSON payload");
        assert_eq!(
            decoded,
            TestPayload {
                id: 7,
                text: "legacy".to_string(),
                tokens: vec![1, 2],
            }
        );
    }

    #[test]
    fn request_control_message_decodes_msgpack_payload_codec() {
        let json = r#"{
            "id": "request-123",
            "request_type": "single_in",
            "response_type": "many_out",
            "payload_codec": "msgpack",
            "connection_info": {
                "transport": "tcp",
                "info": "{}"
            }
        }"#;

        let message: RequestControlMessage =
            serde_json::from_str(json).expect("control message should deserialize");

        assert_eq!(message.payload_codec, RequestPlanePayloadCodec::Msgpack);
    }

    #[test]
    fn request_plane_payload_codec_configuration_defaults_to_msgpack() {
        assert_eq!(
            RequestPlanePayloadCodec::from_config_value(None),
            RequestPlanePayloadCodec::Msgpack
        );
        assert_eq!(
            RequestPlanePayloadCodec::from_config_value(Some("")),
            RequestPlanePayloadCodec::Msgpack
        );
        assert_eq!(
            RequestPlanePayloadCodec::from_config_value(Some("invalid")),
            RequestPlanePayloadCodec::Msgpack
        );
    }

    #[test]
    fn request_plane_payload_codec_configuration_honors_explicit_overrides() {
        assert_eq!(
            RequestPlanePayloadCodec::from_config_value(Some("json")),
            RequestPlanePayloadCodec::Json
        );
        assert_eq!(
            RequestPlanePayloadCodec::from_config_value(Some("msgpack")),
            RequestPlanePayloadCodec::Msgpack
        );
    }

    #[test]
    fn request_plane_payload_codec_round_trips_response_wrapper_json_and_msgpack() {
        let wrapper = NetworkStreamWrapper {
            data: Some(TestPayload {
                id: 42,
                text: "line\nquote\"slash\\unicode 中".to_string(),
                tokens: vec![1, 2, 3, 65535],
            }),
            complete_final: false,
        };

        for codec in [
            RequestPlanePayloadCodec::Json,
            RequestPlanePayloadCodec::Msgpack,
        ] {
            let encoded = codec.encode(&wrapper).expect("wrapper should encode");
            let decoded: NetworkStreamWrapper<TestPayload> =
                codec.decode(&encoded).expect("wrapper should decode");
            assert_eq!(decoded, wrapper);
        }
    }

    /// `encode_into` must stay byte-compatible with `encode` for both codecs.
    #[tokio::test]
    async fn serde_ingress_encoder_matches_encode_byte_for_byte() {
        let data = Annotated::from_data(serde_json::json!({
            "token_ids": [128, 9001],
            "index": 3,
        }));
        let error = Annotated::<serde_json::Value>::from_error("engine failed");

        for codec in [
            RequestPlanePayloadCodec::Json,
            RequestPlanePayloadCodec::Msgpack,
        ] {
            for (case, response, complete_final, expect_error) in [
                ("data frame", Some(data.clone()), false, false),
                ("error frame", Some(error.clone()), false, true),
                ("complete final", None, true, false),
            ] {
                let expected = codec
                    .encode(&NetworkStreamWrapper {
                        data: response.clone(),
                        complete_final,
                    })
                    .expect("reference encode");

                let frame = SerdeIngressPayloadAdapter
                    .encode_response(codec, response, complete_final)
                    .await
                    .expect("adapter encode");

                assert_eq!(
                    frame.bytes.as_ref(),
                    expected.as_slice(),
                    "codec={} case={case}",
                    codec.name()
                );
                assert_eq!(
                    frame.is_error,
                    expect_error,
                    "codec={} case={case}",
                    codec.name()
                );
                assert!(!frame.stop_stream, "codec={} case={case}", codec.name());
            }
        }
    }
}

#[async_trait]
impl<T: Data, U: Data> AsyncEngine<SingleIn<T>, ManyOut<U>, Error>
    for Egress<SingleIn<T>, ManyOut<U>>
where
    T: Data + Serialize,
    U: for<'de> Deserialize<'de> + Data,
{
    async fn generate(&self, request: SingleIn<T>) -> Result<ManyOut<U>, Error> {
        self.transport_engine.generate(request).await
    }
}

/// Result of encoding one response item for the request plane.
pub struct EncodedResponseFrame {
    pub bytes: Bytes,
    pub is_error: bool,
    /// Stop consuming the engine stream after publishing this frame. The
    /// normal complete-final frame is still sent.
    pub stop_stream: bool,
}

/// Converts request-plane bytes into the item consumed by an ingress engine.
pub trait IngressRequestDecoder<T>: Send + Sync + 'static
where
    T: Data,
{
    fn decode_request(
        &self,
        payload_codec: RequestPlanePayloadCodec,
        bytes: Bytes,
    ) -> impl std::future::Future<Output = std::result::Result<T, PipelineError>> + Send;
}

/// Converts an ingress engine response into its complete on-wire frame.
pub trait IngressResponseEncoder<U>: Send + Sync + 'static
where
    U: Data,
{
    fn encode_response(
        &self,
        payload_codec: RequestPlanePayloadCodec,
        response: Option<U>,
        complete_final: bool,
    ) -> impl std::future::Future<Output = std::result::Result<EncodedResponseFrame, PipelineError>> + Send;
}

/// Complete request/response payload adapter for an ingress engine.
pub trait IngressPayloadAdapter<T, U>:
    IngressRequestDecoder<T> + IngressResponseEncoder<U>
where
    T: Data,
    U: Data,
{
}

impl<T, U, Adapter> IngressPayloadAdapter<T, U> for Adapter
where
    T: Data,
    U: Data,
    Adapter: IngressRequestDecoder<T> + IngressResponseEncoder<U>,
{
}

/// Default adapter for ordinary Rust request and response types.
#[derive(Debug, Default)]
pub struct SerdeIngressPayloadAdapter;

impl<T> IngressRequestDecoder<T> for SerdeIngressPayloadAdapter
where
    T: Data + DeserializeOwned,
{
    #[inline]
    fn decode_request(
        &self,
        payload_codec: RequestPlanePayloadCodec,
        bytes: Bytes,
    ) -> impl std::future::Future<Output = std::result::Result<T, PipelineError>> + Send {
        let decoded = payload_codec.decode(&bytes).map_err(|err| {
            PipelineError::DeserializationError(format!(
                "Failed deserializing {} request payload: {}",
                payload_codec.name(),
                err
            ))
        });
        std::future::ready(decoded)
    }
}

impl<U> IngressResponseEncoder<U> for SerdeIngressPayloadAdapter
where
    U: Data + Serialize + MaybeError,
{
    #[inline]
    fn encode_response(
        &self,
        payload_codec: RequestPlanePayloadCodec,
        response: Option<U>,
        complete_final: bool,
    ) -> impl std::future::Future<Output = std::result::Result<EncodedResponseFrame, PipelineError>> + Send
    {
        let is_error = response
            .as_ref()
            .is_some_and(|response| response.err().is_some());
        let wrapper = NetworkStreamWrapper {
            data: response,
            complete_final,
        };
        let mut bytes = Vec::with_capacity(RESPONSE_ENCODE_CAPACITY_HINT);
        let encoded = payload_codec
            .encode_into(&wrapper, &mut bytes)
            .map(|()| bytes)
            .map_err(|err| {
                PipelineError::SerializationError(format!(
                    "Failed serializing {} request-plane response: {}",
                    payload_codec.name(),
                    err
                ))
            });
        std::future::ready(encoded.map(|bytes| EncodedResponseFrame {
            bytes: bytes.into(),
            is_error,
            stop_stream: false,
        }))
    }
}

pub struct Ingress<Req: PipelineIO, Resp: PipelineIO, Adapter = SerdeIngressPayloadAdapter> {
    segment: OnceLock<Arc<SegmentSource<Req, Resp>>>,
    metrics: OnceLock<Arc<WorkHandlerMetrics>>,
    /// Endpoint-specific notifier for health check timer resets
    endpoint_health_check_notifier: OnceLock<Arc<tokio::sync::Notify>>,
    /// Resolved response transport of the bound endpoint's runtime.
    response_plane: OnceLock<ResponsePlaneMode>,
    quic_response_client_pool: OnceLock<Arc<quic_response::QuicResponseClientPool>>,
    payload_adapter: Arc<Adapter>,
    lifecycle_operation_role: OnceLock<Arc<OnceLock<LifecycleOperationRole>>>,
}

impl<Req: PipelineIO + Sync, Resp: PipelineIO> Ingress<Req, Resp> {
    pub fn new() -> Arc<Self> {
        Ingress::new_with_adapter(SerdeIngressPayloadAdapter)
    }

    pub fn link(segment: Arc<SegmentSource<Req, Resp>>) -> Result<Arc<Self>> {
        let ingress = Ingress::new();
        ingress.attach(segment)?;
        Ok(ingress)
    }

    pub fn for_pipeline(segment: Arc<SegmentSource<Req, Resp>>) -> Result<Arc<Self>> {
        let ingress = Ingress::new();
        ingress.attach(segment)?;
        Ok(ingress)
    }

    pub fn for_engine(engine: ServiceEngine<Req, Resp>) -> Result<Arc<Self>> {
        Self::for_engine_with_adapter(engine, SerdeIngressPayloadAdapter)
    }

    /// Build a worker ingress with the role fixed by its startup configuration.
    pub fn for_engine_with_lifecycle_role(
        engine: ServiceEngine<Req, Resp>,
        role: LifecycleOperationRole,
    ) -> Result<Arc<Self>> {
        Self::for_engine_with_adapter_and_lifecycle_role(engine, SerdeIngressPayloadAdapter, role)
    }
}

impl<Req, Resp, Adapter> Ingress<Req, Resp, Adapter>
where
    Req: PipelineIO + Sync,
    Resp: PipelineIO,
    Adapter: Send + Sync + 'static,
{
    pub fn new_with_adapter(payload_adapter: Adapter) -> Arc<Self> {
        Arc::new(Self {
            segment: OnceLock::new(),
            metrics: OnceLock::new(),
            endpoint_health_check_notifier: OnceLock::new(),
            response_plane: OnceLock::new(),
            quic_response_client_pool: OnceLock::new(),
            payload_adapter: Arc::new(payload_adapter),
            lifecycle_operation_role: OnceLock::new(),
        })
    }

    fn new_with_adapter_and_lifecycle_role(
        payload_adapter: Adapter,
        lifecycle_operation_role: LifecycleOperationRole,
    ) -> Arc<Self> {
        let ingress = Self::new_with_adapter(payload_adapter);
        let role = Arc::new(OnceLock::new());
        role.set(lifecycle_operation_role)
            .expect("new lifecycle role cell must be empty");
        ingress
            .lifecycle_operation_role
            .set(role)
            .expect("new ingress lifecycle role source must be empty");
        ingress
    }

    pub fn attach(&self, segment: Arc<SegmentSource<Req, Resp>>) -> Result<()> {
        self.segment
            .set(segment)
            .map_err(|_| anyhow::anyhow!("Segment already set"))
    }

    pub(crate) fn set_quic_response_client_pool(
        &self,
        pool: Arc<quic_response::QuicResponseClientPool>,
    ) -> Result<()> {
        self.quic_response_client_pool
            .set(pool)
            .map_err(|_| anyhow::anyhow!("QUIC response client pool already set"))
    }

    pub(crate) fn quic_response_client_pool(
        &self,
    ) -> Result<Arc<quic_response::QuicResponseClientPool>, PipelineError> {
        if let Some(pool) = self.quic_response_client_pool.get() {
            return Ok(pool.clone());
        }
        let pool = quic_response::process_client_pool_from_env()?;
        Ok(self.quic_response_client_pool.get_or_init(|| pool).clone())
    }

    pub fn add_metrics(
        &self,
        endpoint: &crate::component::Endpoint,
        metrics_labels: Option<&[(&str, &str)]>,
    ) -> Result<()> {
        let metrics = WorkHandlerMetrics::from_endpoint(endpoint, metrics_labels)
            .map_err(|e| anyhow::anyhow!("Failed to create work handler metrics: {}", e))?;

        // Register global transport breakdown metrics (idempotent)
        crate::metrics::work_handler_perf::ensure_work_handler_perf_metrics_registered(
            endpoint.get_metrics_registry(),
        );

        // Register worker-pool saturation metrics (idempotent). These are
        // process-global and shared across all endpoints attached to the
        // same shared TCP server.
        crate::metrics::work_handler_pool::ensure_work_handler_pool_metrics_registered(
            endpoint.get_metrics_registry(),
        );

        self.metrics
            .set(Arc::new(metrics))
            .map_err(|_| anyhow::anyhow!("Metrics already set"))
    }

    pub fn for_engine_with_adapter(
        engine: ServiceEngine<Req, Resp>,
        payload_adapter: Adapter,
    ) -> Result<Arc<Self>> {
        let frontend = SegmentSource::<Req, Resp>::new();
        let backend = ServiceBackend::from_engine(engine);
        let pipeline = frontend.link(backend)?.link_terminal(frontend)?;
        let ingress = Ingress::new_with_adapter(payload_adapter);
        ingress.attach(pipeline)?;
        Ok(ingress)
    }

    pub fn for_engine_with_adapter_and_lifecycle_role(
        engine: ServiceEngine<Req, Resp>,
        payload_adapter: Adapter,
        role: LifecycleOperationRole,
    ) -> Result<Arc<Self>> {
        let frontend = SegmentSource::<Req, Resp>::new();
        let backend = ServiceBackend::from_engine(engine);

        let pipeline = frontend.link(backend)?.link_terminal(frontend)?;

        let ingress = Ingress::new_with_adapter_and_lifecycle_role(payload_adapter, role);
        ingress.attach(pipeline)?;

        Ok(ingress)
    }

    /// Helper method to access metrics if available
    fn metrics(&self) -> Option<&Arc<WorkHandlerMetrics>> {
        self.metrics.get()
    }

    fn registered_lifecycle_role(&self) -> Option<LifecycleOperationRole> {
        self.lifecycle_operation_role
            .get()
            .and_then(|role| role.get())
            .copied()
    }

    fn bind_endpoint_config(&self, endpoint: &crate::component::Endpoint) {
        let _ = self.response_plane.set(endpoint.drt().response_plane());
        // Keep an explicitly constructed ingress role; otherwise observe model
        // registration even when it happens after the endpoint starts serving.
        let _ = self
            .lifecycle_operation_role
            .set(endpoint.lifecycle_operation_role());
    }
}

#[async_trait]
pub trait PushWorkHandler: Send + Sync {
    /// Bind endpoint identity independently of metrics registration.
    fn bind_endpoint(&self, _endpoint: &crate::component::Endpoint) {}

    async fn handle_payload(
        &self,
        payload: Bytes,
        request_id: Option<String>,
    ) -> Result<(), PipelineError>;

    /// Add metrics to the handler
    fn add_metrics(
        &self,
        endpoint: &crate::component::Endpoint,
        metrics_labels: Option<&[(&str, &str)]>,
    ) -> Result<()>;

    /// Set the endpoint-specific notifier for health check timer resets
    fn set_endpoint_health_check_notifier(
        &self,
        _notifier: Arc<tokio::sync::Notify>,
    ) -> Result<()> {
        // Default implementation for backwards compatibility
        Ok(())
    }
}

/*
/// `NetworkStreamWrapper` is a simple wrapper used to detect proper stream termination
/// in network communication between ingress and egress components.
///
/// **Purpose**: This wrapper solves the problem of detecting whether a stream ended
/// gracefully or was cut off prematurely (e.g., due to network issues).
///
/// **Design Rationale**:
/// - Cannot use `Annotated` directly because the generic type `U` varies:
///   - Sometimes `U = Annotated<...>`
///   - Sometimes `U = LLMEngineOutput<...>`
/// - Using `Annotated` would require double-wrapping like `Annotated<Annotated<...>>`
/// - A simple wrapper is cleaner and more straightforward
///
/// **Stream Flow**:
/// ```
/// At AsyncEngine:
///   response 1 -> response 2 -> response 3 -> <end>
///
/// Between ingress/egress:
///   response 1 <end=false> -> response 2 <end=false> -> response 3 <end=false> -> (null) <end=true>
///
/// At client:
///   response 1 -> response 2 -> response 3 -> <end>
/// ```
///
/// **Error Handling**:
/// If the stream is cut off before proper termination, the egress is responsible for
/// injecting an error response to communicate the incomplete stream to the client:
/// ```
/// At AsyncEngine:
///   response 1 -> ... <without end flag>
///
/// At egress:
///   response 1 <end=false> -> <stream ended without end flag -> convert to error>
///
/// At client:
///   response 1 -> error response
/// ```
///
/// The detection must be done at egress level because premature stream termination
/// can be due to network issues that only the egress component can detect.
*/
/// TODO: Detect end-of-stream using Server-Sent Events (SSE). This will be removed.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct NetworkStreamWrapper<U> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<U>,
    pub complete_final: bool,
}