server.rs 28.4 KB
Newer Older
1
2
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
Ryan Olson's avatar
Ryan Olson committed
3
4

use core::panic;
5
6
7
use socket2::{Domain, SockAddr, Socket, Type};
use std::{
    collections::HashMap,
8
    net::{IpAddr, SocketAddr, TcpListener},
9
10
11
    os::fd::{AsFd, FromRawFd},
    sync::Arc,
};
Ryan Olson's avatar
Ryan Olson committed
12
13
14
15
use tokio::sync::Mutex;

use bytes::Bytes;
use derive_builder::Builder;
16
use futures::{SinkExt, StreamExt};
17
use local_ip_address::{Error, list_afinet_netifas, local_ip, local_ipv6};
18

Ryan Olson's avatar
Ryan Olson committed
19
20
21
22
use serde::{Deserialize, Serialize};
use tokio::{
    io::AsyncWriteExt,
    sync::{mpsc, oneshot},
23
    time,
Ryan Olson's avatar
Ryan Olson committed
24
25
26
27
};
use tokio_util::codec::{FramedRead, FramedWrite};

use super::{
28
29
    CallHomeHandshake, ControlMessage, PendingConnections, RegisteredStream, StreamOptions,
    StreamReceiver, StreamSender, TcpStreamConnectionInfo, TwoPartCodec,
Ryan Olson's avatar
Ryan Olson committed
30
31
32
};
use crate::engine::AsyncEngineContext;
use crate::pipeline::{
33
    PipelineError,
Ryan Olson's avatar
Ryan Olson committed
34
    network::{
35
        ResponseService, ResponseStreamPrologue,
Ryan Olson's avatar
Ryan Olson committed
36
37
38
39
        codec::{TwoPartMessage, TwoPartMessageType},
        tcp::StreamType,
    },
};
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use anyhow::{Context, Result, anyhow as error};

// Trait for IP address resolution - allows dependency injection for testing
pub trait IpResolver {
    fn local_ip(&self) -> Result<std::net::IpAddr, Error>;
    fn local_ipv6(&self) -> Result<std::net::IpAddr, Error>;
}

// Default implementation using the real local_ip_address crate
pub struct DefaultIpResolver;

impl IpResolver for DefaultIpResolver {
    fn local_ip(&self) -> Result<std::net::IpAddr, Error> {
        local_ip()
    }

    fn local_ipv6(&self) -> Result<std::net::IpAddr, Error> {
        local_ipv6()
    }
}
Ryan Olson's avatar
Ryan Olson committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

#[allow(dead_code)]
type ResponseType = TwoPartMessage;

#[derive(Debug, Serialize, Deserialize, Clone, Builder, Default)]
pub struct ServerOptions {
    #[builder(default = "0")]
    pub port: u16,

    #[builder(default)]
    pub interface: Option<String>,
}

impl ServerOptions {
    pub fn builder() -> ServerOptionsBuilder {
        ServerOptionsBuilder::default()
    }
}

/// A [`TcpStreamServer`] is a TCP service that listens on a port for incoming response connections.
/// A Response connection is a connection that is established by a client with the intention of sending
Graham King's avatar
Graham King committed
81
/// specific data back to the server.
Ryan Olson's avatar
Ryan Olson committed
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
pub struct TcpStreamServer {
    local_ip: String,
    local_port: u16,
    state: Arc<Mutex<State>>,
}

// pub struct TcpStreamReceiver {
//     address: TcpStreamConnectionInfo,
//     state: Arc<Mutex<State>>,
//     rx: mpsc::Receiver<ResponseType>,
// }

#[allow(dead_code)]
struct RequestedSendConnection {
    context: Arc<dyn AsyncEngineContext>,
    connection: oneshot::Sender<Result<StreamSender, String>>,
}

struct RequestedRecvConnection {
    context: Arc<dyn AsyncEngineContext>,
    connection: oneshot::Sender<Result<StreamReceiver, String>>,
}

// /// When registering a new TcpStream on the server, the registration method will return a [`Connections`] object.
// /// This [`Connections`] object will have two [`oneshot::Receiver`] objects, one for the [`TcpStreamSender`] and one for the [`TcpStreamReceiver`].
// /// The [`Connections`] object can be awaited to get the [`TcpStreamSender`] and [`TcpStreamReceiver`] objects; these objects will
// /// be made available when the matching Client has connected to the server.
// pub struct Connections {
//     pub address: TcpStreamConnectionInfo,

//     /// The [`oneshot::Receiver`] for the [`TcpStreamSender`]. Awaiting this object will return the [`TcpStreamSender`] object once
//     /// the client has connected to the server.
//     pub sender: Option<oneshot::Receiver<StreamSender>>,

//     /// The [`oneshot::Receiver`] for the [`TcpStreamReceiver`]. Awaiting this object will return the [`TcpStreamReceiver`] object once
//     /// the client has connected to the server.
//     pub receiver: Option<oneshot::Receiver<StreamReceiver>>,
// }

#[derive(Default)]
struct State {
    tx_subjects: HashMap<String, RequestedSendConnection>,
    rx_subjects: HashMap<String, RequestedRecvConnection>,
125
    handle: Option<tokio::task::JoinHandle<Result<()>>>,
Ryan Olson's avatar
Ryan Olson committed
126
127
128
129
130
131
132
133
}

impl TcpStreamServer {
    pub fn options_builder() -> ServerOptionsBuilder {
        ServerOptionsBuilder::default()
    }

    pub async fn new(options: ServerOptions) -> Result<Arc<Self>, PipelineError> {
134
135
136
137
138
139
140
        Self::new_with_resolver(options, DefaultIpResolver).await
    }

    pub async fn new_with_resolver<R: IpResolver>(
        options: ServerOptions,
        resolver: R,
    ) -> Result<Arc<Self>, PipelineError> {
Ryan Olson's avatar
Ryan Olson committed
141
142
143
144
145
146
147
148
149
150
151
152
153
        let local_ip = match options.interface {
            Some(interface) => {
                let interfaces: HashMap<String, std::net::IpAddr> =
                    list_afinet_netifas()?.into_iter().collect();

                interfaces
                    .get(&interface)
                    .ok_or(PipelineError::Generic(format!(
                        "Interface not found: {}",
                        interface
                    )))?
                    .to_string()
            }
154
155
156
            None => {
                let resolved_ip = resolver.local_ip().or_else(|err| match err {
                    Error::LocalIpAddressNotFound => resolver.local_ipv6(),
157
                    _ => Err(err),
158
159
160
161
162
163
164
165
166
                });

                match resolved_ip {
                    Ok(addr) => addr,
                    Err(Error::LocalIpAddressNotFound) => IpAddr::from([127, 0, 0, 1]),
                    Err(err) => return Err(err.into()),
                }
                .to_string()
            }
Ryan Olson's avatar
Ryan Olson committed
167
168
169
170
171
172
173
174
175
176
        };

        let state = Arc::new(Mutex::new(State::default()));

        let local_port = Self::start(local_ip.clone(), options.port, state.clone())
            .await
            .map_err(|e| {
                PipelineError::Generic(format!("Failed to start TcpStreamServer: {}", e))
            })?;

177
        tracing::debug!("tcp transport service on {local_ip}:{local_port}");
Ryan Olson's avatar
Ryan Olson committed
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

        Ok(Arc::new(Self {
            local_ip,
            local_port,
            state,
        }))
    }

    #[allow(clippy::await_holding_lock)]
    async fn start(local_ip: String, local_port: u16, state: Arc<Mutex<State>>) -> Result<u16> {
        let addr = format!("{}:{}", local_ip, local_port);
        let state_clone = state.clone();
        let mut guard = state.lock().await;
        if guard.handle.is_some() {
            panic!("TcpStreamServer already started");
        }
        let (ready_tx, ready_rx) = tokio::sync::oneshot::channel::<Result<u16>>();
        let handle = tokio::spawn(tcp_listener(addr, state_clone, ready_tx));
        guard.handle = Some(handle);
        drop(guard);
        let local_port = ready_rx.await??;
        Ok(local_port)
    }
}

// todo - possible rename ResponseService to ResponseServer
#[async_trait::async_trait]
impl ResponseService for TcpStreamServer {
    /// Register a new subject and sender with the response subscriber
    /// Produces an RAII object that will deregister the subject when dropped
    ///
    /// we need to register both data in and data out entries
    /// there might be forward pipeline that want to consume the data out stream
    /// and there might be a response stream that wants to consume the data in stream
    /// on registration, we need to specific if we want data-in, data-out or both
    /// this will map to the type of service that is runniing, i.e. Single or Many In //
    /// Single or Many Out
    ///
    /// todo(ryan) - return a connection object that can be awaited. when successfully connected,
    /// can ask for the sender and receiver
    ///
    /// OR
    ///
    /// we make it into register sender and register receiver, both would return a connection object
    /// and when a connection is established, we'd get the respective sender or receiver
    ///
    /// the registration probably needs to be done in one-go, so we should use a builder object for
    /// requesting a receiver and optional sender
    async fn register(&self, options: StreamOptions) -> PendingConnections {
        // oneshot channels to pass back the sender and receiver objects

        let address = format!("{}:{}", self.local_ip, self.local_port);
        tracing::debug!("Registering new TcpStream on {}", address);

        let send_stream = if options.enable_request_stream {
            let sender_subject = uuid::Uuid::new_v4().to_string();

            let (pending_sender_tx, pending_sender_rx) = oneshot::channel();

            let connection_info = RequestedSendConnection {
                context: options.context.clone(),
                connection: pending_sender_tx,
            };

            let mut state = self.state.lock().await;
            state
                .tx_subjects
                .insert(sender_subject.clone(), connection_info);

            let registered_stream = RegisteredStream {
                connection_info: TcpStreamConnectionInfo {
                    address: address.clone(),
                    subject: sender_subject.clone(),
                    context: options.context.id().to_string(),
                    stream_type: StreamType::Request,
                }
                .into(),
                stream_provider: pending_sender_rx,
            };

            Some(registered_stream)
        } else {
            None
        };

        let recv_stream = if options.enable_response_stream {
            let (pending_recver_tx, pending_recver_rx) = oneshot::channel();
            let receiver_subject = uuid::Uuid::new_v4().to_string();

            let connection_info = RequestedRecvConnection {
                context: options.context.clone(),
                connection: pending_recver_tx,
            };

            let mut state = self.state.lock().await;
            state
                .rx_subjects
                .insert(receiver_subject.clone(), connection_info);

            let registered_stream = RegisteredStream {
                connection_info: TcpStreamConnectionInfo {
                    address: address.clone(),
                    subject: receiver_subject.clone(),
                    context: options.context.id().to_string(),
                    stream_type: StreamType::Response,
                }
                .into(),
                stream_provider: pending_recver_rx,
            };

            Some(registered_stream)
        } else {
            None
        };

        PendingConnections {
            send_stream,
            recv_stream,
        }
    }
}

// this method listens on a tcp port for incoming connections
// new connections are expected to send a protocol specific handshake
// for us to determine the subject they are interested in, in this case,
// we expect the first message to be [`FirstMessage`] from which we find
// the sender, then we spawn a task to forward all bytes from the tcp stream
// to the sender
async fn tcp_listener(
    addr: String,
    state: Arc<Mutex<State>>,
    read_tx: tokio::sync::oneshot::Sender<Result<u16>>,
310
) -> Result<()> {
Ryan Olson's avatar
Ryan Olson committed
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
    let listener = tokio::net::TcpListener::bind(&addr)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to start TcpListender on {}: {}", addr, e));

    let listener = match listener {
        Ok(listener) => {
            let addr = listener
                .local_addr()
                .map_err(|e| anyhow::anyhow!("Failed get SocketAddr: {:?}", e))
                .unwrap();

            read_tx
                .send(Ok(addr.port()))
                .expect("Failed to send ready signal");

            listener
        }
        Err(e) => {
            read_tx.send(Err(e)).expect("Failed to send ready signal");
330
            return Err(anyhow::anyhow!("Failed to start TcpListender on {}", addr));
Ryan Olson's avatar
Ryan Olson committed
331
332
333
334
        }
    };

    loop {
335
336
337
338
339
        // todo - add instrumentation
        // todo - add counter for all accepted connections
        // todo - add gauge for all inflight connections
        // todo - add counter for incoming bytes
        // todo - add counter for outgoing bytes
340
        let (stream, _addr) = match listener.accept().await {
341
342
343
344
345
346
            Ok((stream, _addr)) => (stream, _addr),
            Err(e) => {
                // the client should retry, so we don't need to abort
                tracing::warn!("failed to accept tcp connection: {}", e);
                eprintln!("failed to accept tcp connection: {}", e);
                continue;
347
348
            }
        };
349
350
351
352
353
354
355
356

        match stream.set_nodelay(true) {
            Ok(_) => (),
            Err(e) => {
                tracing::warn!("failed to set tcp stream to nodelay: {}", e);
            }
        }

357
358
359
360
361
362
363
        match stream.set_linger(Some(std::time::Duration::from_secs(0))) {
            Ok(_) => (),
            Err(e) => {
                tracing::warn!("failed to set tcp stream to linger: {}", e);
            }
        }

Ryan Olson's avatar
Ryan Olson committed
364
365
366
367
368
369
370
371
        tokio::spawn(handle_connection(stream, state.clone()));
    }

    // #[instrument(level = "trace"), skip(state)]
    // todo - clone before spawn and trace process_stream
    async fn handle_connection(stream: tokio::net::TcpStream, state: Arc<Mutex<State>>) {
        let result = process_stream(stream, state).await;
        match result {
372
373
374
375
376
377
            Ok(_) => tracing::trace!("successfully processed tcp connection"),
            Err(e) => {
                tracing::warn!("failed to handle tcp connection: {}", e);
                #[cfg(debug_assertions)]
                eprintln!("failed to handle tcp connection: {}", e);
            }
Ryan Olson's avatar
Ryan Olson committed
378
379
380
381
382
        }
    }

    /// This method is responsible for the internal tcp stream handshake
    /// The handshake will specialize the stream as a request/sender or response/receiver stream
383
    async fn process_stream(stream: tokio::net::TcpStream, state: Arc<Mutex<State>>) -> Result<()> {
Ryan Olson's avatar
Ryan Olson committed
384
385
386
387
388
389
390
391
392
393
394
395
        // split the socket in to a reader and writer
        let (read_half, write_half) = tokio::io::split(stream);

        // attach the codec to the reader and writer to get framed readers and writers
        let mut framed_reader = FramedRead::new(read_half, TwoPartCodec::default());
        let framed_writer = FramedWrite::new(write_half, TwoPartCodec::default());

        // the internal tcp [`CallHomeHandshake`] connects the socket to the requester
        // here we await this first message as a raw bytes two part message
        let first_message = framed_reader
            .next()
            .await
396
            .ok_or(error!("Connection closed without a ControlMessage"))??;
Ryan Olson's avatar
Ryan Olson committed
397
398
399

        // we await on the raw bytes which should come in as a header only message
        // todo - improve error handling - check for no data
400
401
        let handshake: CallHomeHandshake = match first_message.header() {
            Some(header) => serde_json::from_slice(header).map_err(|e| {
402
                error!(
403
                    "Failed to deserialize the first message as a valid `CallHomeHandshake`: {e}",
Ryan Olson's avatar
Ryan Olson committed
404
                )
405
406
            })?,
            None => {
407
                return Err(error!("Expected ControlMessage, got DataMessage"));
408
409
            }
        };
Ryan Olson's avatar
Ryan Olson committed
410
411
412
413
414
415
416
417
418
419
420

        // branch here to handle sender stream or receiver stream
        match handshake.stream_type {
            StreamType::Request => process_request_stream().await,
            StreamType::Response => {
                process_response_stream(handshake.subject, state, framed_reader, framed_writer)
                    .await
            }
        }
    }

421
    async fn process_request_stream() -> Result<()> {
Ryan Olson's avatar
Ryan Olson committed
422
423
424
425
426
427
428
429
        Ok(())
    }

    async fn process_response_stream(
        subject: String,
        state: Arc<Mutex<State>>,
        mut reader: FramedRead<tokio::io::ReadHalf<tokio::net::TcpStream>, TwoPartCodec>,
        writer: FramedWrite<tokio::io::WriteHalf<tokio::net::TcpStream>, TwoPartCodec>,
430
    ) -> Result<()> {
Ryan Olson's avatar
Ryan Olson committed
431
432
433
434
        let response_stream = state
            .lock().await
            .rx_subjects
            .remove(&subject)
435
            .ok_or(error!("Subject not found: {}; upstream publisher specified a subject unknown to the downsteam subscriber", subject))?;
Ryan Olson's avatar
Ryan Olson committed
436
437
438
439
440
441
442
443
444
445
446
447

        // unwrap response_stream
        let RequestedRecvConnection {
            context,
            connection,
        } = response_stream;

        // the [`Prologue`]
        // there must be a second control message it indicate the other segment's generate method was successful
        let prologue = reader
            .next()
            .await
448
            .ok_or(error!("Connection closed without a ControlMessge"))??;
Ryan Olson's avatar
Ryan Olson committed
449
450
451
452
453

        // deserialize prologue
        let prologue = match prologue.into_message_type() {
            TwoPartMessageType::HeaderOnly(header) => {
                let prologue: ResponseStreamPrologue = serde_json::from_slice(&header)
454
                    .map_err(|e| error!("Failed to deserialize ControlMessage: {}", e))?;
Ryan Olson's avatar
Ryan Olson committed
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
                prologue
            }
            _ => {
                panic!("Expected HeaderOnly ControlMessage; internally logic error")
            }
        };

        // await the control message of GTG or Error, if error, then connection.send(Err(String)), which should fail the
        // generate call chain
        //
        // note: this second control message might be delayed, but the expensive part of setting up the connection
        // is both complete and ready for data flow; awaiting here is not a performance hit or problem and it allows
        // us to trace the initial setup time vs the time to prologue
        if let Some(error) = &prologue.error {
            let _ = connection.send(Err(error.clone()));
470
            return Err(error!("Received error prologue: {}", error));
Ryan Olson's avatar
Ryan Olson committed
471
472
473
        }

        // we need to know the buffer size from the registration options; add this to the RequestRecvConnection object
474
        let (response_tx, response_rx) = mpsc::channel(64);
Ryan Olson's avatar
Ryan Olson committed
475
476

        if connection
477
478
479
            .send(Ok(crate::pipeline::network::StreamReceiver {
                rx: response_rx,
            }))
Ryan Olson's avatar
Ryan Olson committed
480
481
            .is_err()
        {
482
483
484
            return Err(error!(
                "The requester of the stream has been dropped before the connection was established"
            ));
Ryan Olson's avatar
Ryan Olson committed
485
486
        }

487
        let (control_tx, control_rx) = mpsc::channel::<ControlMessage>(1);
Ryan Olson's avatar
Ryan Olson committed
488

489
490
491
492
        // sender task
        // issues control messages to the sender and when finished shuts down the socket
        // this should be the last task to finish and must
        let send_task = tokio::spawn(network_send_handler(writer, control_rx));
Ryan Olson's avatar
Ryan Olson committed
493
494

        // forward task
495
        let recv_task = tokio::spawn(network_receive_handler(
Ryan Olson's avatar
Ryan Olson committed
496
            reader,
497
            response_tx,
Ryan Olson's avatar
Ryan Olson committed
498
499
500
501
502
            control_tx,
            context.clone(),
        ));

        // check the results of each of the tasks
503
        let (monitor_result, forward_result) = tokio::join!(send_task, recv_task);
Ryan Olson's avatar
Ryan Olson committed
504

505
506
        monitor_result?;
        forward_result?;
Ryan Olson's avatar
Ryan Olson committed
507
508
509
510

        Ok(())
    }

511
    async fn network_receive_handler(
Ryan Olson's avatar
Ryan Olson committed
512
513
        mut framed_reader: FramedRead<tokio::io::ReadHalf<tokio::net::TcpStream>, TwoPartCodec>,
        response_tx: mpsc::Sender<Bytes>,
514
        control_tx: mpsc::Sender<ControlMessage>,
Ryan Olson's avatar
Ryan Olson committed
515
        context: Arc<dyn AsyncEngineContext>,
516
    ) {
Ryan Olson's avatar
Ryan Olson committed
517
        // loop over reading the tcp stream and checking if the writer is closed
518
        let mut can_stop = true;
Ryan Olson's avatar
Ryan Olson committed
519
520
        loop {
            tokio::select! {
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
                biased;

                _ = response_tx.closed() => {
                    tracing::trace!("response channel closed before the client finished writing data");
                    control_tx.send(ControlMessage::Kill).await.expect("the control channel should not be closed");
                    break;
                }

                _ = context.killed() => {
                    tracing::trace!("context kill signal received; shutting down");
                    control_tx.send(ControlMessage::Kill).await.expect("the control channel should not be closed");
                    break;
                }

                _ = context.stopped(), if can_stop => {
536
                    tracing::trace!("context stop signal received; shutting down");
537
538
539
540
                    can_stop = false;
                    control_tx.send(ControlMessage::Stop).await.expect("the control channel should not be closed");
                }

Ryan Olson's avatar
Ryan Olson committed
541
542
543
544
545
                msg = framed_reader.next() => {
                    match msg {
                        Some(Ok(msg)) => {
                            let (header, data) = msg.into_parts();

546
547
548
549
550
551
552
553
554
555
556
557
558
559
                            // received a control message
                            if !header.is_empty() {
                                match process_control_message(header) {
                                    Ok(ControlAction::Continue) => {}
                                    Ok(ControlAction::Shutdown) => {
                                        assert!(data.is_empty(), "received sentinel message with data; this should never happen");
                                        tracing::trace!("received sentinel message; shutting down");
                                        break;
                                    }
                                    Err(e) => {
                                        // TODO(#171) - address fatal errors
                                        panic!("{:?}", e);
                                    }
                                }
Ryan Olson's avatar
Ryan Olson committed
560
561
                            }

562
563
                            if !data.is_empty()
                                && let Err(err) = response_tx.send(data).await {
564
565
566
                                    tracing::debug!("forwarding body/data message to response channel failed: {}", err);
                                    control_tx.send(ControlMessage::Kill).await.expect("the control channel should not be closed");
                                    break;
567
                                };
Ryan Olson's avatar
Ryan Olson committed
568
                        }
569
570
571
                        Some(Err(_)) => {
                            // TODO(#171) - address fatal errors
                            panic!("invalid message issued over socket; this should never happen");
Ryan Olson's avatar
Ryan Olson committed
572
573
                        }
                        None => {
574
575
576
577
578
579
                            // this is allowed but we try to avoid it
                            // the logic is that the client will tell us when its is done and the server
                            // will close the connection naturally when the sentinel message is received
                            // the client closing early represents a transport error outside the control of the
                            // transport library
                            tracing::trace!("tcp stream was closed by client");
Ryan Olson's avatar
Ryan Olson committed
580
581
582
583
                            break;
                        }
                    }
                }
584

Ryan Olson's avatar
Ryan Olson committed
585
586
587
588
            }
        }
    }

589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
    async fn network_send_handler(
        socket_tx: FramedWrite<tokio::io::WriteHalf<tokio::net::TcpStream>, TwoPartCodec>,
        control_rx: mpsc::Receiver<ControlMessage>,
    ) {
        let mut socket_tx = socket_tx;
        let mut control_rx = control_rx;

        while let Some(control_msg) = control_rx.recv().await {
            assert_ne!(
                control_msg,
                ControlMessage::Sentinel,
                "received sentinel message; this should never happen"
            );
            let bytes =
                serde_json::to_vec(&control_msg).expect("failed to serialize control message");
            let message = TwoPartMessage::from_header(bytes.into());
            match socket_tx.send(message).await {
                Ok(_) => tracing::debug!("issued control message {control_msg:?} to sender"),
                Err(_) => {
                    tracing::debug!("failed to send control message {control_msg:?} to sender")
Ryan Olson's avatar
Ryan Olson committed
609
610
611
                }
            }
        }
612
613
614
615
616
617
618
619

        let mut inner = socket_tx.into_inner();
        if let Err(e) = inner.flush().await {
            tracing::debug!("failed to flush socket: {}", e);
        }
        if let Err(e) = inner.shutdown().await {
            tracing::debug!("failed to shutdown socket: {}", e);
        }
Ryan Olson's avatar
Ryan Olson committed
620
    }
621
}
Ryan Olson's avatar
Ryan Olson committed
622

623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
enum ControlAction {
    Continue,
    Shutdown,
}

fn process_control_message(message: Bytes) -> Result<ControlAction> {
    match serde_json::from_slice::<ControlMessage>(&message)? {
        ControlMessage::Sentinel => {
            // the client issued a sentinel message
            // it has finished writing data and is now awaiting the server to close the connection
            tracing::trace!("sentinel received; shutting down");
            Ok(ControlAction::Shutdown)
        }
        ControlMessage::Kill | ControlMessage::Stop => {
            // TODO(#171) - address fatal errors
            anyhow::bail!(
                "fatal error - unexpected control message received - this should never happen"
            );
Ryan Olson's avatar
Ryan Olson committed
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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::AsyncEngineContextProvider;
    use crate::pipeline::Context;

    // Mock resolver that always fails to simulate the fallback scenario
    struct FailingIpResolver;

    impl IpResolver for FailingIpResolver {
        fn local_ip(&self) -> Result<std::net::IpAddr, Error> {
            Err(Error::LocalIpAddressNotFound)
        }

        fn local_ipv6(&self) -> Result<std::net::IpAddr, Error> {
            Err(Error::LocalIpAddressNotFound)
        }
    }

    #[tokio::test]
    async fn test_tcp_stream_server_default_behavior() {
        // Test that TcpStreamServer::new works with default options
        // This verifies normal operation when IP detection succeeds
        let options = ServerOptions::default();
        let result = TcpStreamServer::new(options).await;

        assert!(
            result.is_ok(),
            "TcpStreamServer::new should succeed with default options"
        );

        let server = result.unwrap();

        // Verify the server can be used by registering a stream
        let context = Context::new(());
        let stream_options = StreamOptions::builder()
            .context(context.context())
            .enable_request_stream(false)
            .enable_response_stream(true)
            .build()
            .unwrap();

        let pending_connection = server.register(stream_options).await;

        // Verify connection info is available and valid
        let connection_info = pending_connection
            .recv_stream
            .as_ref()
            .unwrap()
            .connection_info
            .clone();

        let tcp_info: TcpStreamConnectionInfo = connection_info.try_into().unwrap();
        let socket_addr = tcp_info.address.parse::<std::net::SocketAddr>().unwrap();

        // Should have a valid port assigned
        assert!(
            socket_addr.port() > 0,
            "Server should be assigned a valid port number"
        );

        println!(
            "Server created successfully with address: {}",
            tcp_info.address
        );
    }

    #[tokio::test]
    async fn test_tcp_stream_server_fallback_to_loopback() {
        // Test fallback behavior using a mock resolver that always fails
        // This guarantees the fallback logic is triggered

        let options = ServerOptions::builder().port(0).build().unwrap();

        // Use the failing resolver to force the fallback
        let result = TcpStreamServer::new_with_resolver(options, FailingIpResolver).await;
        assert!(
            result.is_ok(),
            "Server creation should succeed with fallback even when IP detection fails"
        );

        let server = result.unwrap();

        // Get the actual bound address by registering a stream
        let context = Context::new(());
        let stream_options = StreamOptions::builder()
            .context(context.context())
            .enable_request_stream(false)
            .enable_response_stream(true)
            .build()
            .unwrap();

        let pending_connection = server.register(stream_options).await;
        let connection_info = pending_connection
            .recv_stream
            .as_ref()
            .unwrap()
            .connection_info
            .clone();

        let tcp_info: TcpStreamConnectionInfo = connection_info.try_into().unwrap();
        let socket_addr = tcp_info.address.parse::<std::net::SocketAddr>().unwrap();

        // With the failing resolver, fallback should ALWAYS be used
        let ip = socket_addr.ip();
        assert!(
            ip.is_loopback(),
            "Should use loopback when IP detection fails"
        );

        // Verify it's specifically 127.0.0.1 (the fallback value from the patch)
        assert_eq!(
            ip,
            std::net::IpAddr::V4(std::net::Ipv4Addr::new(127, 0, 0, 1)),
            "Fallback should use exactly 127.0.0.1, got: {}",
            ip
        );

        println!("SUCCESS: Fallback to 127.0.0.1 was confirmed: {}", ip);

        // The server should work with the fallback IP
        assert!(socket_addr.port() > 0, "Server should have a valid port");
    }
}