|
| 1 | +use std::net::SocketAddr; |
| 2 | +use std::ops::{Deref, DerefMut}; |
| 3 | +use std::result::Result as StdResult; |
| 4 | + |
| 5 | +use mlua::{Lua, Result, String as LuaString, Table, UserData, UserDataMethods, UserDataRegistry}; |
| 6 | +use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; |
| 7 | +use tokio::net::lookup_host; |
| 8 | +use tokio::time::timeout; |
| 9 | + |
| 10 | +use super::{SocketOptions, TcpSocket}; |
| 11 | +use crate::time::Duration; |
| 12 | + |
| 13 | +pub struct TcpStream { |
| 14 | + stream: tokio::net::TcpStream, |
| 15 | + read_timeout: Option<Duration>, |
| 16 | + write_timeout: Option<Duration>, |
| 17 | +} |
| 18 | + |
| 19 | +impl Deref for TcpStream { |
| 20 | + type Target = tokio::net::TcpStream; |
| 21 | + |
| 22 | + #[inline] |
| 23 | + fn deref(&self) -> &Self::Target { |
| 24 | + &self.stream |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +impl DerefMut for TcpStream { |
| 29 | + #[inline] |
| 30 | + fn deref_mut(&mut self) -> &mut Self::Target { |
| 31 | + &mut self.stream |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +macro_rules! with_io_timeout { |
| 36 | + ($timeout:expr, $fut:expr) => { |
| 37 | + match $timeout { |
| 38 | + Some(dur) => (timeout(dur.0, $fut).await) |
| 39 | + .map_err(|e| std::io::Error::new(std::io::ErrorKind::TimedOut, e)) |
| 40 | + .flatten(), |
| 41 | + None => $fut.await, |
| 42 | + } |
| 43 | + }; |
| 44 | +} |
| 45 | + |
| 46 | +impl From<tokio::net::TcpStream> for TcpStream { |
| 47 | + fn from(stream: tokio::net::TcpStream) -> Self { |
| 48 | + TcpStream { |
| 49 | + stream, |
| 50 | + read_timeout: None, |
| 51 | + write_timeout: None, |
| 52 | + } |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +impl UserData for TcpStream { |
| 57 | + fn register(registry: &mut UserDataRegistry<Self>) { |
| 58 | + registry.add_async_function("connect", connect); |
| 59 | + |
| 60 | + registry.add_method("local_addr", |_, this, ()| Ok(this.local_addr()?.to_string())); |
| 61 | + |
| 62 | + registry.add_method("peer_addr", |_, this, ()| Ok(this.peer_addr()?.to_string())); |
| 63 | + |
| 64 | + registry.add_method_mut("set_read_timeout", |_, this, dur: Option<Duration>| { |
| 65 | + this.read_timeout = dur; |
| 66 | + Ok(()) |
| 67 | + }); |
| 68 | + |
| 69 | + registry.add_method_mut("set_write_timeout", |_, this, dur: Option<Duration>| { |
| 70 | + this.write_timeout = dur; |
| 71 | + Ok(()) |
| 72 | + }); |
| 73 | + |
| 74 | + registry.add_async_method_mut("read", |lua, mut this, size: usize| async move { |
| 75 | + let mut buf = vec![0; size]; |
| 76 | + let n = with_io_timeout!(this.read_timeout, this.read(&mut buf)); |
| 77 | + let n = lua_try!(n); |
| 78 | + buf.truncate(n); |
| 79 | + Ok(Ok(lua.create_string(buf)?)) |
| 80 | + }); |
| 81 | + |
| 82 | + registry.add_async_method_mut("read_to_end", |lua, mut this, ()| async move { |
| 83 | + let mut buf = Vec::new(); |
| 84 | + let n = with_io_timeout!(this.read_timeout, this.read_to_end(&mut buf)); |
| 85 | + let _n = lua_try!(n); |
| 86 | + Ok(Ok(lua.create_string(buf)?)) |
| 87 | + }); |
| 88 | + |
| 89 | + registry.add_async_method_mut("write", |_, mut this, data: LuaString| async move { |
| 90 | + let n = with_io_timeout!(this.write_timeout, this.write(&data.as_bytes())); |
| 91 | + let n = lua_try!(n); |
| 92 | + Ok(Ok(n)) |
| 93 | + }); |
| 94 | + |
| 95 | + registry.add_async_method_mut("write_all", |_, mut this, data: LuaString| async move { |
| 96 | + let r = with_io_timeout!(this.write_timeout, this.write_all(&data.as_bytes())); |
| 97 | + lua_try!(r); |
| 98 | + Ok(Ok(true)) |
| 99 | + }); |
| 100 | + |
| 101 | + registry.add_async_method_mut("flush", |_, mut this, ()| async move { |
| 102 | + let r = with_io_timeout!(this.write_timeout, this.flush()); |
| 103 | + lua_try!(r); |
| 104 | + Ok(Ok(true)) |
| 105 | + }); |
| 106 | + |
| 107 | + registry.add_async_method_mut("shutdown", |_, mut this, ()| async move { |
| 108 | + lua_try!(this.shutdown().await); |
| 109 | + Ok(Ok(true)) |
| 110 | + }); |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +pub async fn connect( |
| 115 | + _: Lua, |
| 116 | + (addr, params): (String, Option<Table>), |
| 117 | +) -> Result<StdResult<TcpStream, String>> { |
| 118 | + let addrs = lua_try!(lookup_host(addr).await); |
| 119 | + let options = SocketOptions::from_table(¶ms)?; |
| 120 | + |
| 121 | + let timeout = opt_param!(Duration, params, "timeout")?; // A single timeout for any operation |
| 122 | + let connect_timeout = opt_param!(Duration, params, "connect_timeout")?.or(timeout); |
| 123 | + let read_timeout = opt_param!(Duration, params, "read_timeout")?.or(timeout); |
| 124 | + let write_timeout = opt_param!(Duration, params, "write_timeout")?.or(timeout); |
| 125 | + |
| 126 | + let try_connect = |addr: SocketAddr| async move { |
| 127 | + let sock = TcpSocket::new_for_addr(addr)?; |
| 128 | + sock.set_options(options)?; |
| 129 | + with_io_timeout!(connect_timeout, sock.0.connect(addr)) |
| 130 | + }; |
| 131 | + |
| 132 | + let mut last_err = None; |
| 133 | + for addr in addrs { |
| 134 | + match try_connect(addr).await { |
| 135 | + Ok(stream) => { |
| 136 | + return Ok(Ok(TcpStream { |
| 137 | + stream, |
| 138 | + read_timeout, |
| 139 | + write_timeout, |
| 140 | + })); |
| 141 | + } |
| 142 | + Err(e) => { |
| 143 | + last_err = Some(e); |
| 144 | + continue; |
| 145 | + } |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + Ok(Err(last_err.map(|err| err.to_string()).unwrap_or_else(|| { |
| 150 | + "could not resolve to any address".to_string() |
| 151 | + }))) |
| 152 | +} |
0 commit comments