client.rs 9.79 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Ryan Olson's avatar
Ryan Olson committed
15
16
17
18

use std::sync::Arc;

use futures::{SinkExt, StreamExt};
19
use tokio::io::{ReadHalf, WriteHalf};
Ryan Olson's avatar
Ryan Olson committed
20
21
22
23
24
25
26
27
28
use tokio::{io::AsyncWriteExt, net::TcpStream};
use tokio_util::codec::{FramedRead, FramedWrite};

use super::{CallHomeHandshake, ControlMessage, TcpStreamConnectionInfo};
use crate::engine::AsyncEngineContext;
use crate::pipeline::network::{
    codec::{TwoPartCodec, TwoPartMessage},
    tcp::StreamType,
    ConnectionInfo, ResponseStreamPrologue, StreamSender,
29
30
};
use crate::{error, ErrorContext, Result}; // Import SinkExt to use the `send` method
Ryan Olson's avatar
Ryan Olson committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

#[allow(dead_code)]
pub struct TcpClient {
    worker_id: String,
}

impl Default for TcpClient {
    fn default() -> Self {
        TcpClient {
            worker_id: uuid::Uuid::new_v4().to_string(),
        }
    }
}

impl TcpClient {
    pub fn new(worker_id: String) -> Self {
        TcpClient { worker_id }
    }

50
51
52
53
54
55
56
57
58
59
60
61
    async fn connect(address: &str) -> std::io::Result<TcpStream> {
        // try to connect to the address; retry with exponential backoff if AddrNotAvailable
        let backoff = std::time::Duration::from_millis(200);
        loop {
            match TcpStream::connect(address).await {
                Ok(socket) => {
                    socket.set_nodelay(true)?;
                    return Ok(socket);
                }
                Err(e) => {
                    if e.kind() == std::io::ErrorKind::AddrNotAvailable {
                        tracing::warn!("retry warning: failed to connect: {:?}", e);
Ryan Olson's avatar
Ryan Olson committed
62

63
64
65
                        // TODO(#173) - remove with resolution of issue
                        #[cfg(debug_assertions)]
                        eprintln!("retry warning: failed to connect: {:?}", e);
Ryan Olson's avatar
Ryan Olson committed
66

67
68
69
70
71
72
73
                        tokio::time::sleep(backoff).await;
                    } else {
                        return Err(e);
                    }
                }
            }
        }
Ryan Olson's avatar
Ryan Olson committed
74
75
76
77
78
    }

    pub async fn create_response_steam(
        context: Arc<dyn AsyncEngineContext>,
        info: ConnectionInfo,
79
80
81
    ) -> Result<StreamSender> {
        let info =
            TcpStreamConnectionInfo::try_from(info).context("tcp-stream-connection-info-error")?;
Ryan Olson's avatar
Ryan Olson committed
82
83
84
        tracing::trace!("Creating response stream for {:?}", info);

        if info.stream_type != StreamType::Response {
85
            return Err(error!(
Ryan Olson's avatar
Ryan Olson committed
86
87
88
89
90
91
                "Invalid stream type; TcpClient requires the stream type to be `response`; however {:?} was passed",
                info.stream_type
            ));
        }

        if info.context != context.id() {
92
            return Err(error!(
Ryan Olson's avatar
Ryan Olson committed
93
94
95
96
97
98
99
100
101
                "Invalid context; TcpClient requires the context to be {:?}; however {:?} was passed",
                context.id(),
                info.context
            ));
        }

        let stream = TcpClient::connect(&info.address).await?;
        let (read_half, write_half) = tokio::io::split(stream);

102
        let framed_reader = FramedRead::new(read_half, TwoPartCodec::default());
Ryan Olson's avatar
Ryan Olson committed
103
104
105
106
107
108
109
        let mut framed_writer = FramedWrite::new(write_half, TwoPartCodec::default());

        // this is a oneshot channel that will be used to signal when the stream is closed
        // when the stream sender is dropped, the bytes_rx will be closed and the forwarder task will exit
        // the forwarder task will capture the alive_rx half of the oneshot channel; this will close the alive channel
        // so the holder of the alive_tx half will be notified that the stream is closed; the alive_tx channel will be
        // captured by the monitor task
110
111
        let (alive_tx, alive_rx) = tokio::sync::oneshot::channel::<()>();

112
        let reader_task = tokio::spawn(handle_reader(framed_reader, context, alive_tx));
Ryan Olson's avatar
Ryan Olson committed
113
114
115
116
117
118
119

        // transport specific handshake message
        let handshake = CallHomeHandshake {
            subject: info.subject,
            stream_type: StreamType::Response,
        };

120
121
122
        let handshake_bytes = match serde_json::to_vec(&handshake) {
            Ok(hb) => hb,
            Err(err) => {
123
                return Err(error!(
124
125
126
127
                    "create_response_steam: Error converting CallHomeHandshake to JSON array: {err:#}"
                ));
            }
        };
Ryan Olson's avatar
Ryan Olson committed
128
129
130
131
132
133
        let msg = TwoPartMessage::from_header(handshake_bytes.into());

        // issue the the first tcp handshake message
        framed_writer
            .send(msg)
            .await
134
            .map_err(|e| error!("failed to send handshake: {:?}", e))?;
Ryan Olson's avatar
Ryan Olson committed
135
136

        // set up the channel to send bytes to the transport layer
137
        let (bytes_tx, bytes_rx) = tokio::sync::mpsc::channel(16);
Ryan Olson's avatar
Ryan Olson committed
138
139

        // forwards the bytes send from this stream to the transport layer; hold the alive_rx half of the oneshot channel
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162

        let writer_task = tokio::spawn(handle_writer(framed_writer, bytes_rx, alive_rx));

        tokio::spawn(async move {
            // await both tasks
            let (reader, writer) = tokio::join!(reader_task, writer_task);

            match (reader, writer) {
                (Ok(reader), Ok(writer)) => {
                    let reader = reader.into_inner();
                    let writer = writer.into_inner();

                    let mut stream = reader.unsplit(writer);

                    // close the stream
                    Ok(stream.shutdown().await?)
                }
                _ => {
                    tracing::error!("failed to join reader and writer tasks");
                    anyhow::bail!("failed to join reader and writer tasks");
                }
            }
        });
Ryan Olson's avatar
Ryan Olson committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176

        // set up the prologue for the stream
        // this might have transport specific metadata in the future
        let prologue = Some(ResponseStreamPrologue { error: None });

        // create the stream sender
        let stream_sender = StreamSender {
            tx: bytes_tx,
            prologue,
        };

        Ok(stream_sender)
    }
}
177

178
179
async fn handle_reader(
    framed_reader: FramedRead<tokio::io::ReadHalf<tokio::net::TcpStream>, TwoPartCodec>,
180
    context: Arc<dyn AsyncEngineContext>,
181
182
183
184
    alive_tx: tokio::sync::oneshot::Sender<()>,
) -> FramedRead<tokio::io::ReadHalf<tokio::net::TcpStream>, TwoPartCodec> {
    let mut framed_reader = framed_reader;
    let mut alive_tx = alive_tx;
185
186
187
188
189
190
191
    loop {
        tokio::select! {
            msg = framed_reader.next() => {
                match msg {
                    Some(Ok(two_part_msg)) => {
                        match two_part_msg.optional_parts() {
                           (Some(bytes), None) => {
192
                                let msg = match serde_json::from_slice::<ControlMessage>(bytes) {
193
                                    Ok(msg) => msg,
194
195
196
                                    Err(_) => {
                                        // TODO(#171) - address fatal errors
                                        tracing::error!("fatal error - invalid control message detected");
197
198
199
                                        break;
                                    }
                                };
200
201


202
203
204
205
206
207
208
209
210
211
212
213
                                match msg {
                                    ControlMessage::Stop => {
                                        context.stop();
                                        break;
                                    }
                                    ControlMessage::Kill => {
                                        context.kill();
                                        break;
                                    }
                                }
                           }
                           _ => {
214
215
                                // not a control message, so we just continue
                               continue;
216
217
218
                           }
                        }
                    }
219
220
221
222
223
                    Some(Err(_)) => {
                        // TODO(#171) - address fatal errors
                        // in this case the binary representation of the message is invalid
                        tracing::error!("fatal error - failed to decode message from stream");
                        break;
224
225
                    }
                    None => {
226
227
228
229
230
                        // let mut writer = framed_reader.into_inner();
                        // if let Err(e) = writer.shutdown().await {
                        //     tracing::trace!("failed to shutdown reader: {:?}", e);
                        // }
                        break;
231
232
233
234
235
236
237
238
239
                    }
                }
            }
            _ = alive_tx.closed() => {
                // the channel was closed, we should stop the stream
                break;
            }
        }
    }
240
    framed_reader
241
242
}

243
244
async fn handle_writer(
    mut framed_writer: FramedWrite<tokio::io::WriteHalf<tokio::net::TcpStream>, TwoPartCodec>,
245
246
    mut bytes_rx: tokio::sync::mpsc::Receiver<TwoPartMessage>,
    alive_rx: tokio::sync::oneshot::Receiver<()>,
247
) -> FramedWrite<tokio::io::WriteHalf<tokio::net::TcpStream>, TwoPartCodec> {
248
249
    while let Some(msg) = bytes_rx.recv().await {
        if let Err(e) = framed_writer.send(msg).await {
250
251
252
253
            tracing::trace!(
                "failed to send message to stream; possible disconnect: {:?}",
                e
            );
254
255
256
257
258
259

            // TODO - possibly propagate the error upstream
            break;
        }
    }
    drop(alive_rx);
260
261

    framed_writer
262
}