openigtlink-rust 0.1.0

Rust implementation of the OpenIGTLink protocol for image-guided therapy
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
//! Asynchronous OpenIGTLink client implementation
//!
//! Provides a non-blocking, async/await-based client for OpenIGTLink communication.
//! Uses Tokio for async I/O operations.

use crate::error::Result;
use crate::protocol::header::Header;
use crate::protocol::message::{IgtlMessage, Message};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tracing::{debug, info, trace, warn};

/// Asynchronous OpenIGTLink client
///
/// Uses non-blocking I/O with Tokio for high-concurrency scenarios.
///
/// # Examples
///
/// ```no_run
/// use openigtlink_rust::io::AsyncIgtlClient;
/// use openigtlink_rust::protocol::types::StatusMessage;
/// use openigtlink_rust::protocol::message::IgtlMessage;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let mut client = AsyncIgtlClient::connect("127.0.0.1:18944").await?;
///
///     let status = StatusMessage::ok("Hello");
///     let msg = IgtlMessage::new(status, "AsyncClient")?;
///     client.send(&msg).await?;
///
///     Ok(())
/// }
/// ```
#[deprecated(
    since = "0.2.0",
    note = "Use ClientBuilder instead: ClientBuilder::new().tcp(addr).async_mode().build().await"
)]
pub struct AsyncIgtlClient {
    stream: TcpStream,
    verify_crc: bool,
}

impl AsyncIgtlClient {
    /// Connect to an OpenIGTLink server asynchronously
    ///
    /// # Arguments
    ///
    /// * `addr` - Server address (e.g., "127.0.0.1:18944")
    ///
    /// # Errors
    ///
    /// - [`IgtlError::Io`](crate::error::IgtlError::Io) - Failed to connect
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use openigtlink_rust::io::AsyncIgtlClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = AsyncIgtlClient::connect("127.0.0.1:18944").await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn connect(addr: &str) -> Result<Self> {
        info!(addr = %addr, "Connecting to OpenIGTLink server (async)");
        let stream = TcpStream::connect(addr).await?;
        let local_addr = stream.local_addr()?;
        info!(
            local_addr = %local_addr,
            remote_addr = %addr,
            "Connected to OpenIGTLink server (async)"
        );
        Ok(AsyncIgtlClient {
            stream,
            verify_crc: true,
        })
    }

    /// Enable or disable CRC verification for received messages
    ///
    /// # Arguments
    ///
    /// * `verify` - true to enable CRC verification (default), false to disable
    ///
    /// # Safety
    ///
    /// Disabling CRC verification should only be done in trusted environments
    /// where data corruption is unlikely (e.g., loopback, local network).
    pub fn set_verify_crc(&mut self, verify: bool) {
        if verify != self.verify_crc {
            info!(verify = verify, "CRC verification setting changed");
            if !verify {
                warn!("CRC verification disabled - use only in trusted environments");
            }
        }
        self.verify_crc = verify;
    }

    /// Get current CRC verification setting
    pub fn verify_crc(&self) -> bool {
        self.verify_crc
    }

    /// Send a message to the server asynchronously
    ///
    /// # Arguments
    ///
    /// * `msg` - Message to send
    ///
    /// # Errors
    ///
    /// - [`IgtlError::Io`](crate::error::IgtlError::Io) - Network write failed
    /// - [`IgtlError::BodyTooLarge`](crate::error::IgtlError::BodyTooLarge) - Message exceeds maximum size
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use openigtlink_rust::io::AsyncIgtlClient;
    /// use openigtlink_rust::protocol::types::StatusMessage;
    /// use openigtlink_rust::protocol::message::IgtlMessage;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let mut client = AsyncIgtlClient::connect("127.0.0.1:18944").await?;
    ///
    ///     let status = StatusMessage::ok("Ready");
    ///     let msg = IgtlMessage::new(status, "Client")?;
    ///     client.send(&msg).await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn send<T: Message>(&mut self, msg: &IgtlMessage<T>) -> Result<()> {
        let data = msg.encode()?;
        let msg_type = msg.header.type_name.as_str().unwrap_or("UNKNOWN");
        let device_name = msg.header.device_name.as_str().unwrap_or("UNKNOWN");

        debug!(
            msg_type = msg_type,
            device_name = device_name,
            size = data.len(),
            "Sending message (async)"
        );

        self.stream.write_all(&data).await?;
        self.stream.flush().await?;

        trace!(
            msg_type = msg_type,
            bytes_sent = data.len(),
            "Message sent successfully (async)"
        );

        Ok(())
    }

    /// Receive a message from the server asynchronously
    ///
    /// # Errors
    ///
    /// - [`IgtlError::Io`](crate::error::IgtlError::Io) - Network read failed
    /// - [`IgtlError::InvalidHeader`](crate::error::IgtlError::InvalidHeader) - Received malformed header
    /// - [`IgtlError::CrcMismatch`](crate::error::IgtlError::CrcMismatch) - Data corruption detected
    /// - [`IgtlError::UnknownMessageType`](crate::error::IgtlError::UnknownMessageType) - Unsupported message type
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use openigtlink_rust::io::AsyncIgtlClient;
    /// use openigtlink_rust::protocol::types::TransformMessage;
    /// use openigtlink_rust::protocol::message::IgtlMessage;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let mut client = AsyncIgtlClient::connect("127.0.0.1:18944").await?;
    ///     let msg: IgtlMessage<TransformMessage> = client.receive().await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn receive<T: Message>(&mut self) -> Result<IgtlMessage<T>> {
        trace!("Waiting for message header (async)");

        let mut header_buf = vec![0u8; Header::SIZE];
        self.stream.read_exact(&mut header_buf).await?;

        let header = Header::decode(&header_buf)?;

        let msg_type = header.type_name.as_str().unwrap_or("UNKNOWN");
        let device_name = header.device_name.as_str().unwrap_or("UNKNOWN");

        debug!(
            msg_type = msg_type,
            device_name = device_name,
            body_size = header.body_size,
            version = header.version,
            "Received message header (async)"
        );

        let mut body_buf = vec![0u8; header.body_size as usize];
        self.stream.read_exact(&mut body_buf).await?;

        trace!(
            msg_type = msg_type,
            bytes_read = body_buf.len(),
            "Message body received (async)"
        );

        let mut full_msg = header_buf;
        full_msg.extend_from_slice(&body_buf);

        let result = IgtlMessage::decode_with_options(&full_msg, self.verify_crc);

        match &result {
            Ok(_) => {
                debug!(
                    msg_type = msg_type,
                    device_name = device_name,
                    "Message decoded successfully (async)"
                );
            }
            Err(e) => {
                warn!(
                    msg_type = msg_type,
                    error = %e,
                    "Failed to decode message (async)"
                );
            }
        }

        result
    }

    /// Set read timeout for the underlying TCP stream
    pub async fn set_read_timeout(&mut self, timeout: Option<std::time::Duration>) -> Result<()> {
        // Tokio doesn't use set_read_timeout, instead use tokio::time::timeout
        // This is a placeholder for API compatibility
        debug!(timeout_ms = ?timeout.map(|d| d.as_millis()), "Read timeout not directly supported in async (use tokio::time::timeout)");
        Ok(())
    }

    /// Set write timeout for the underlying TCP stream
    pub async fn set_write_timeout(
        &mut self,
        timeout: Option<std::time::Duration>,
    ) -> Result<()> {
        // Tokio doesn't use set_write_timeout, instead use tokio::time::timeout
        // This is a placeholder for API compatibility
        debug!(timeout_ms = ?timeout.map(|d| d.as_millis()), "Write timeout not directly supported in async (use tokio::time::timeout)");
        Ok(())
    }

    /// Enable or disable TCP_NODELAY (Nagle's algorithm)
    pub async fn set_nodelay(&self, nodelay: bool) -> Result<()> {
        self.stream.set_nodelay(nodelay)?;
        debug!(nodelay = nodelay, "TCP_NODELAY configured");
        Ok(())
    }

    /// Get the current TCP_NODELAY setting
    pub async fn nodelay(&self) -> Result<bool> {
        Ok(self.stream.nodelay()?)
    }

    /// Get the local address
    pub fn local_addr(&self) -> Result<std::net::SocketAddr> {
        Ok(self.stream.local_addr()?)
    }

    /// Get the remote peer address
    pub fn peer_addr(&self) -> Result<std::net::SocketAddr> {
        Ok(self.stream.peer_addr()?)
    }

    /// Split the client into read and write halves
    ///
    /// This allows concurrent reading and writing on separate tasks.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use openigtlink_rust::io::AsyncIgtlClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = AsyncIgtlClient::connect("127.0.0.1:18944").await?;
    ///     let (reader, writer) = client.into_split();
    ///
    ///     // Use reader and writer in separate tasks
    ///     Ok(())
    /// }
    /// ```
    pub fn into_split(self) -> (AsyncIgtlReader, AsyncIgtlWriter) {
        let (reader, writer) = self.stream.into_split();
        (
            AsyncIgtlReader {
                reader,
                verify_crc: self.verify_crc,
            },
            AsyncIgtlWriter { writer },
        )
    }
}

/// Read half of an async OpenIGTLink client
pub struct AsyncIgtlReader {
    reader: tokio::net::tcp::OwnedReadHalf,
    verify_crc: bool,
}

impl AsyncIgtlReader {
    /// Receive a message from the read half
    pub async fn receive<T: Message>(&mut self) -> Result<IgtlMessage<T>> {
        trace!("Waiting for message header (async reader)");

        let mut header_buf = vec![0u8; Header::SIZE];
        self.reader.read_exact(&mut header_buf).await?;

        let header = Header::decode(&header_buf)?;

        let msg_type = header.type_name.as_str().unwrap_or("UNKNOWN");
        let device_name = header.device_name.as_str().unwrap_or("UNKNOWN");

        debug!(
            msg_type = msg_type,
            device_name = device_name,
            body_size = header.body_size,
            "Received message header (async reader)"
        );

        let mut body_buf = vec![0u8; header.body_size as usize];
        self.reader.read_exact(&mut body_buf).await?;

        trace!(
            msg_type = msg_type,
            bytes_read = body_buf.len(),
            "Message body received (async reader)"
        );

        let mut full_msg = header_buf;
        full_msg.extend_from_slice(&body_buf);

        IgtlMessage::decode_with_options(&full_msg, self.verify_crc)
    }
}

/// Write half of an async OpenIGTLink client
pub struct AsyncIgtlWriter {
    writer: tokio::net::tcp::OwnedWriteHalf,
}

impl AsyncIgtlWriter {
    /// Send a message to the write half
    pub async fn send<T: Message>(&mut self, msg: &IgtlMessage<T>) -> Result<()> {
        let data = msg.encode()?;
        let msg_type = msg.header.type_name.as_str().unwrap_or("UNKNOWN");

        debug!(
            msg_type = msg_type,
            size = data.len(),
            "Sending message (async writer)"
        );

        self.writer.write_all(&data).await?;
        self.writer.flush().await?;

        trace!(
            msg_type = msg_type,
            bytes_sent = data.len(),
            "Message sent (async writer)"
        );

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocol::types::StatusMessage;
    use tokio::time::Duration;

    #[tokio::test]
    async fn test_async_client_connect_timeout() {
        // Try to connect to a non-existent server with timeout
        let result = tokio::time::timeout(
            Duration::from_millis(100),
            AsyncIgtlClient::connect("127.0.0.1:19999"),
        )
        .await;

        // Should timeout or fail to connect
        assert!(result.is_err() || result.unwrap().is_err());
    }

    #[tokio::test]
    async fn test_async_client_crc_setting() {
        // Test CRC setting without actual connection
        let stream = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .unwrap()
            .local_addr()
            .unwrap();

        tokio::spawn(async move {
            let listener = tokio::net::TcpListener::bind(stream).await.unwrap();
            let _ = listener.accept().await;
        });

        tokio::time::sleep(Duration::from_millis(10)).await;

        let mut client = AsyncIgtlClient::connect(&stream.to_string())
            .await
            .unwrap();
        assert_eq!(client.verify_crc(), true);

        client.set_verify_crc(false);
        assert_eq!(client.verify_crc(), false);

        client.set_verify_crc(true);
        assert_eq!(client.verify_crc(), true);
    }

    #[tokio::test]
    async fn test_async_client_server_communication() {
        // Create server
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .unwrap();
        let addr = listener.local_addr().unwrap();

        // Spawn server task
        tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            let mut client = AsyncIgtlClient {
                stream,
                verify_crc: true,
            };

            // Receive message
            let msg: IgtlMessage<StatusMessage> = client.receive().await.unwrap();
            assert_eq!(msg.content.status_string, "Hello");

            // Send response
            let response = StatusMessage::ok("World");
            let response_msg = IgtlMessage::new(response, "Server").unwrap();
            client.send(&response_msg).await.unwrap();
        });

        tokio::time::sleep(Duration::from_millis(10)).await;

        // Connect client
        let mut client = AsyncIgtlClient::connect(&addr.to_string())
            .await
            .unwrap();

        // Send message
        let status = StatusMessage::ok("Hello");
        let msg = IgtlMessage::new(status, "Client").unwrap();
        client.send(&msg).await.unwrap();

        // Receive response
        let response: IgtlMessage<StatusMessage> = client.receive().await.unwrap();
        assert_eq!(response.content.status_string, "World");
    }
}