Skip to content

Commit 7e172c2

Browse files
committed
Refactor "@time" module
- Improve Duration parsing - Use static constructors for Instant and Duration - Add tests
1 parent d763c9f commit 7e172c2

File tree

17 files changed

+192
-107
lines changed

17 files changed

+192
-107
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ regex = { version = "1.0", optional = true }
3838
quick_cache = { version = "0.6", optional = true }
3939
futures-util = { version = "0.3", optional = true }
4040
parking_lot = "0.12"
41+
humantime = "2.3"
4142

4243
# http
4344
http = { version = "1.3", optional = true }

lua/testing.lua

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ local deps = ...
22
local assertions = deps.assertions
33

44
local println, style = deps.println, deps.style
5-
local instant = deps.instant
5+
local Instant = deps.Instant
66

77
local Testing = {}
88
Testing.__index = Testing
@@ -88,7 +88,7 @@ end
8888
-- Run a single test
8989
function Testing:_run_single_test(test)
9090
local ctx = TestContext.new(test.name)
91-
local start_time = instant()
91+
local start_time = Instant.now()
9292
local success, err = true, nil
9393

9494
-- Run before_each hooks
@@ -143,7 +143,7 @@ function Testing:run(opts)
143143
opts = opts or {}
144144
local pattern = opts.pattern
145145
self._results = {}
146-
local start_time = instant()
146+
local start_time = Instant.now()
147147

148148
-- Run before_all hooks
149149
for _, func in ipairs(self._hooks.before_all) do

src/http/request.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use mlua::{
99
};
1010

1111
use crate::http::{LuaBody, LuaHeaderMapExt, LuaHeaders, LuaMethod};
12-
use crate::time::Duration;
12+
use crate::time::LuaDuration;
1313

1414
/// A Lua wrapper around [`http::Request`].
1515
pub struct LuaRequest {
@@ -181,13 +181,13 @@ impl FromLua for LuaRequest {
181181
/// Additional custom request parameters
182182
#[derive(Clone, Debug, Default)]
183183
pub(crate) struct RequestParams {
184-
pub(crate) timeout: Option<Duration>,
184+
pub(crate) timeout: Option<LuaDuration>,
185185
}
186186

187187
impl RequestParams {
188188
pub(crate) fn from_table(table: &Table) -> Result<Self> {
189189
let mut params = RequestParams::default();
190-
if let Some(timeout) = opt_param!(Duration, Some(table), "timeout")? {
190+
if let Some(timeout) = opt_param!(LuaDuration, Some(table), "timeout")? {
191191
params.timeout = Some(timeout);
192192
}
193193
Ok(params)

src/http/server.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use tokio::io::{AsyncRead, AsyncWrite};
1717
use super::{LuaRequest, LuaResponse};
1818
use crate::net::common::Accept;
1919
use crate::net::{AnyListener, AnyStream};
20-
use crate::time::Duration;
20+
use crate::time::LuaDuration;
2121

2222
/// Local executor that can spawn `!Send` futures
2323
#[derive(Clone, Copy)]
@@ -55,7 +55,7 @@ impl LuaHttpServer {
5555
if let Some(max_headers) = opt_param!(http1, "max_headers")? {
5656
conn.http1().max_headers(max_headers);
5757
}
58-
if let Some(header_read_timeout) = opt_param!(Duration, http1, "header_read_timeout")? {
58+
if let Some(header_read_timeout) = opt_param!(LuaDuration, http1, "header_read_timeout")? {
5959
conn.http1().header_read_timeout(header_read_timeout.0);
6060
}
6161
if let Some(max_buf_size) = opt_param!(http1, "max_buf_size")? {
@@ -83,10 +83,10 @@ impl LuaHttpServer {
8383
if let Some(max_concurrent_streams) = opt_param!(u32, http2, "max_concurrent_streams")? {
8484
conn.http2().max_concurrent_streams(max_concurrent_streams);
8585
}
86-
if let Some(keep_alive_interval) = opt_param!(Duration, http2, "keep_alive_interval")? {
86+
if let Some(keep_alive_interval) = opt_param!(LuaDuration, http2, "keep_alive_interval")? {
8787
conn.http2().keep_alive_interval(keep_alive_interval.0);
8888
}
89-
if let Some(keep_alive_timeout) = opt_param!(Duration, http2, "keep_alive_timeout")? {
89+
if let Some(keep_alive_timeout) = opt_param!(LuaDuration, http2, "keep_alive_timeout")? {
9090
conn.http2().keep_alive_timeout(keep_alive_timeout.0);
9191
}
9292
if let Some(max_header_list_size) = opt_param!(u32, http2, "max_header_list_size")? {
@@ -167,7 +167,7 @@ impl LuaHttpServer {
167167
}
168168

169169
/// Shutdown the server gracefully, waiting for existing connections to finish
170-
pub async fn graceful_shutdown(&self, wait: Duration) {
170+
pub async fn graceful_shutdown(&self, wait: LuaDuration) {
171171
let shutdown_tx = mem::take(&mut *self.shutdown_notify.lock());
172172
let _ = shutdown_tx.send(());
173173
let graceful = mem::take(&mut *self.graceful.lock());
@@ -199,8 +199,8 @@ impl UserData for LuaHttpServer {
199199

200200
registry.add_async_method(
201201
"graceful_shutdown",
202-
|_lua, this, wait: Option<Duration>| async move {
203-
let wait = wait.unwrap_or(Duration(std::time::Duration::from_secs(60)));
202+
|_lua, this, wait: Option<LuaDuration>| async move {
203+
let wait = wait.unwrap_or(LuaDuration(std::time::Duration::from_secs(60)));
204204
this.graceful_shutdown(wait).await;
205205
Ok(())
206206
},

src/net/tcp/stream.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,15 @@ use tokio::net::{TcpStream, lookup_host};
1111

1212
use super::{LuaTcpSocket, SocketOptions};
1313
use crate::net::{AddressProvider, AnySocketAddr};
14-
use crate::time::Duration;
14+
use crate::time::LuaDuration;
1515

1616
/// Lua wrapper around tokio [`TcpStream`].
1717
pub struct LuaTcpStream {
1818
pub(crate) stream: TcpStream,
1919
#[allow(unused)]
2020
pub(crate) host: Option<String>,
21-
pub(crate) read_timeout: Option<Duration>,
22-
pub(crate) write_timeout: Option<Duration>,
21+
pub(crate) read_timeout: Option<LuaDuration>,
22+
pub(crate) write_timeout: Option<LuaDuration>,
2323
}
2424

2525
impl Deref for LuaTcpStream {
@@ -91,12 +91,12 @@ impl UserData for LuaTcpStream {
9191
registry.add_method("local_addr", |_, this, ()| Ok(this.local_addr()?));
9292
registry.add_method("peer_addr", |_, this, ()| Ok(this.peer_addr()?));
9393

94-
registry.add_method_mut("set_read_timeout", |_, this, dur: Option<Duration>| {
94+
registry.add_method_mut("set_read_timeout", |_, this, dur: Option<LuaDuration>| {
9595
this.read_timeout = dur;
9696
Ok(())
9797
});
9898

99-
registry.add_method_mut("set_write_timeout", |_, this, dur: Option<Duration>| {
99+
registry.add_method_mut("set_write_timeout", |_, this, dur: Option<LuaDuration>| {
100100
this.write_timeout = dur;
101101
Ok(())
102102
});
@@ -160,10 +160,10 @@ pub async fn connect(
160160
let addrs = lua_try!(lookup_host((&*host, port)).await);
161161
let options = SocketOptions::from_table(&params)?;
162162

163-
let timeout = opt_param!(Duration, params, "timeout")?; // A single timeout for any operation
164-
let connect_timeout = opt_param!(Duration, params, "connect_timeout")?.or(timeout);
165-
let read_timeout = opt_param!(Duration, params, "read_timeout")?.or(timeout);
166-
let write_timeout = opt_param!(Duration, params, "write_timeout")?.or(timeout);
163+
let timeout = opt_param!(LuaDuration, params, "timeout")?; // A single timeout for any operation
164+
let connect_timeout = opt_param!(LuaDuration, params, "connect_timeout")?.or(timeout);
165+
let read_timeout = opt_param!(LuaDuration, params, "read_timeout")?.or(timeout);
166+
let write_timeout = opt_param!(LuaDuration, params, "write_timeout")?.or(timeout);
167167

168168
let try_connect = |addr: SocketAddr| async move {
169169
let sock = LuaTcpSocket::new_for_addr(addr)?;

src/net/tls/stream.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,16 @@ use tokio_rustls::{TlsAcceptor, TlsConnector, TlsStream};
1010
use super::client::TlsClientConfig;
1111
use super::server::TlsServerConfig;
1212
use crate::net::AddressProvider;
13-
use crate::time::Duration;
13+
use crate::time::LuaDuration;
1414

1515
/// A TLS stream wrapper for Lua.
1616
///
1717
/// This type wraps a TLS stream and provides read/write methods.
1818
/// It consumes the underlying stream to prevent further use of the plain stream.
1919
pub struct LuaTlsStream<S> {
2020
inner: TlsStream<S>,
21-
read_timeout: Option<Duration>,
22-
write_timeout: Option<Duration>,
21+
read_timeout: Option<LuaDuration>,
22+
write_timeout: Option<LuaDuration>,
2323
}
2424

2525
impl<S> LuaTlsStream<S>
@@ -58,11 +58,11 @@ where
5858
})
5959
}
6060

61-
pub(crate) fn set_read_timeout(&mut self, dur: Option<Duration>) {
61+
pub(crate) fn set_read_timeout(&mut self, dur: Option<LuaDuration>) {
6262
self.read_timeout = dur;
6363
}
6464

65-
pub(crate) fn set_write_timeout(&mut self, dur: Option<Duration>) {
65+
pub(crate) fn set_write_timeout(&mut self, dur: Option<LuaDuration>) {
6666
self.write_timeout = dur;
6767
}
6868

@@ -128,12 +128,12 @@ where
128128
registry.add_method("local_addr", |_, this, ()| Ok(this.local_addr()?));
129129
registry.add_method("peer_addr", |_, this, ()| Ok(this.peer_addr()?));
130130

131-
registry.add_method_mut("set_read_timeout", |_, this, dur: Option<Duration>| {
131+
registry.add_method_mut("set_read_timeout", |_, this, dur: Option<LuaDuration>| {
132132
this.read_timeout = dur;
133133
Ok(())
134134
});
135135

136-
registry.add_method_mut("set_write_timeout", |_, this, dur: Option<Duration>| {
136+
registry.add_method_mut("set_write_timeout", |_, this, dur: Option<LuaDuration>| {
137137
this.write_timeout = dur;
138138
Ok(())
139139
});

src/net/udp/socket.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@ use mlua::{Lua, Result, String as LuaString, Table, UserData, UserDataMethods, U
66
use tokio::net::UdpSocket;
77

88
use crate::net::{AddressProvider, AnySocketAddr};
9-
use crate::time::Duration;
9+
use crate::time::LuaDuration;
1010

1111
/// A Lua userdata wrapper around [`UdpSocket`].
1212
pub struct LuaUdpSocket {
1313
pub(crate) socket: UdpSocket,
14-
pub(crate) recv_timeout: Option<Duration>,
14+
pub(crate) recv_timeout: Option<LuaDuration>,
1515
}
1616

1717
impl Deref for LuaUdpSocket {
@@ -49,7 +49,7 @@ impl UserData for LuaUdpSocket {
4949
registry.add_method("local_addr", |_, this, ()| Ok(this.local_addr()?));
5050
registry.add_method("peer_addr", |_, this, ()| Ok(this.peer_addr()?));
5151

52-
registry.add_method_mut("set_recv_timeout", |_, this, dur: Option<Duration>| {
52+
registry.add_method_mut("set_recv_timeout", |_, this, dur: Option<LuaDuration>| {
5353
this.recv_timeout = dur;
5454
Ok(())
5555
});
@@ -122,7 +122,7 @@ pub async fn bind(
122122
(host, port, params): (String, Option<u16>, Option<Table>),
123123
) -> Result<StdResult<LuaUdpSocket, String>> {
124124
let port = port.unwrap_or(0);
125-
let recv_timeout = opt_param!(Duration, params, "recv_timeout")?;
125+
let recv_timeout = opt_param!(LuaDuration, params, "recv_timeout")?;
126126

127127
let socket = lua_try!(UdpSocket::bind((host, port)).await);
128128

src/net/unix/stream.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@ use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _, Re
1010
use tokio::net::UnixStream;
1111

1212
use crate::net::{AddressProvider, AnySocketAddr};
13-
use crate::time::Duration;
13+
use crate::time::LuaDuration;
1414

1515
pub struct LuaUnixStream {
1616
pub(crate) stream: UnixStream,
17-
pub(crate) read_timeout: Option<Duration>,
18-
pub(crate) write_timeout: Option<Duration>,
17+
pub(crate) read_timeout: Option<LuaDuration>,
18+
pub(crate) write_timeout: Option<LuaDuration>,
1919
}
2020

2121
impl Deref for LuaUnixStream {
@@ -85,12 +85,12 @@ impl UserData for LuaUnixStream {
8585
registry.add_method("local_addr", |_, this, ()| Ok(this.local_addr()?));
8686
registry.add_method("peer_addr", |_, this, ()| Ok(this.peer_addr()?));
8787

88-
registry.add_method_mut("set_read_timeout", |_, this, dur: Option<Duration>| {
88+
registry.add_method_mut("set_read_timeout", |_, this, dur: Option<LuaDuration>| {
8989
this.read_timeout = dur;
9090
Ok(())
9191
});
9292

93-
registry.add_method_mut("set_write_timeout", |_, this, dur: Option<Duration>| {
93+
registry.add_method_mut("set_write_timeout", |_, this, dur: Option<LuaDuration>| {
9494
this.write_timeout = dur;
9595
Ok(())
9696
});
@@ -139,7 +139,7 @@ pub async fn connect(
139139
_: Lua,
140140
(path, params): (PathBuf, Option<Table>),
141141
) -> Result<StdResult<LuaUnixStream, String>> {
142-
let timeout = opt_param!(Duration, params, "timeout")?; // A single timeout for any operation
142+
let timeout = opt_param!(LuaDuration, params, "timeout")?; // A single timeout for any operation
143143
let connect_timeout = opt_param!(params, "connect_timeout")?.or(timeout);
144144
let read_timeout = opt_param!(params, "read_timeout")?.or(timeout);
145145
let write_timeout = opt_param!(params, "write_timeout")?.or(timeout);

src/reqwest.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use mlua::{
33
};
44

55
use crate::http::{LuaHeaders, LuaRequest, LuaResponse};
6-
use crate::time::Duration;
6+
use crate::time::LuaDuration;
77

88
/// A Lua wrapper around [`reqwest::Client`].
99
#[derive(Clone, Debug)]
@@ -15,16 +15,16 @@ impl UserData for Client {
1515
let mut builder = reqwest::Client::builder();
1616

1717
// Timeouts and connection pool
18-
if let Some(timeout) = opt_param!(Duration, params, "timeout")? {
18+
if let Some(timeout) = opt_param!(LuaDuration, params, "timeout")? {
1919
builder = builder.timeout(timeout.0);
2020
}
21-
if let Some(connect_timeout) = opt_param!(Duration, params, "connect_timeout")? {
21+
if let Some(connect_timeout) = opt_param!(LuaDuration, params, "connect_timeout")? {
2222
builder = builder.connect_timeout(connect_timeout.0);
2323
}
24-
if let Some(read_timeout) = opt_param!(Duration, params, "read_timeout")? {
24+
if let Some(read_timeout) = opt_param!(LuaDuration, params, "read_timeout")? {
2525
builder = builder.read_timeout(read_timeout.0);
2626
}
27-
if let Some(pool_idle_timeout) = opt_param!(Duration, params, "pool_idle_timeout")? {
27+
if let Some(pool_idle_timeout) = opt_param!(LuaDuration, params, "pool_idle_timeout")? {
2828
builder = builder.pool_idle_timeout(pool_idle_timeout.0);
2929
}
3030
if let Some(pool_max_idle_per_host) = opt_param!(params, "pool_max_idle_per_host")? {

src/task.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,18 @@ use tokio::task::{AbortHandle, JoinHandle, JoinSet};
1111
use tokio::time::{Instant as TokioInstant, MissedTickBehavior};
1212
use tokio_util::time::FutureExt as _;
1313

14-
use crate::time::Duration;
14+
use crate::time::LuaDuration;
1515

1616
#[derive(Clone, Default)]
1717
struct Params {
1818
name: Option<String>,
19-
timeout: Option<Duration>,
19+
timeout: Option<LuaDuration>,
2020
}
2121

2222
pub struct TaskHandle {
2323
name: Option<String>,
2424
started: Rc<RefCell<Option<Instant>>>,
25-
elapsed: Rc<RefCell<Option<Duration>>>,
25+
elapsed: Rc<RefCell<Option<LuaDuration>>>,
2626
handle: Either<Option<JoinHandle<Result<Value>>>, AbortHandle>,
2727
}
2828

@@ -64,7 +64,7 @@ impl UserData for TaskHandle {
6464

6565
registry.add_method("elapsed", |_, this, ()| match *this.elapsed.borrow() {
6666
Some(dur) => Ok(Some(dur)),
67-
None => Ok(this.started.borrow().map(|s| Duration(s.elapsed()))),
67+
None => Ok(this.started.borrow().map(|s| LuaDuration(s.elapsed()))),
6868
});
6969

7070
registry.add_method("is_finished", |_, this, ()| match this.handle.as_ref() {
@@ -83,7 +83,7 @@ pub struct Task {
8383
impl Task {
8484
fn new(func: Function, params: Option<Table>) -> Result<Self> {
8585
let name: Option<String> = opt_param!(params, "name")?;
86-
let timeout: Option<Duration> = opt_param!(params, "timeout")?;
86+
let timeout: Option<LuaDuration> = opt_param!(params, "timeout")?;
8787
Ok(Self {
8888
func,
8989
params: Params { name, timeout },
@@ -122,7 +122,7 @@ impl UserData for Group {
122122
let abort_handle = this.0.spawn_local(async move {
123123
*started2.borrow_mut() = Some(Instant::now());
124124
defer! {
125-
*elapsed2.borrow_mut() = Some(Duration(started2.borrow().unwrap().elapsed()));
125+
*elapsed2.borrow_mut() = Some(LuaDuration(started2.borrow().unwrap().elapsed()));
126126
}
127127

128128
let result = match timeout {
@@ -191,7 +191,7 @@ fn spawn_inner(params: Params, fut: impl Future<Output = Result<Value>> + 'stati
191191
let handle = tokio::task::spawn_local(async move {
192192
*started2.borrow_mut() = Some(Instant::now());
193193
defer! {
194-
*elapsed2.borrow_mut() = Some(Duration(started2.borrow().unwrap().elapsed()));
194+
*elapsed2.borrow_mut() = Some(LuaDuration(started2.borrow().unwrap().elapsed()));
195195
}
196196

197197
let result = match timeout {
@@ -226,7 +226,7 @@ pub fn spawn(_: &Lua, (func, args): (Either<Function, UserDataRef<Task>>, MultiV
226226

227227
pub fn spawn_every(
228228
_: &Lua,
229-
(dur, func, args): (Duration, Either<Function, UserDataRef<Task>>, MultiValue),
229+
(dur, func, args): (LuaDuration, Either<Function, UserDataRef<Task>>, MultiValue),
230230
) -> Result<TaskHandle> {
231231
let (func, params) = match func {
232232
Either::Left(f) => (f, Params::default()),
@@ -243,7 +243,7 @@ pub fn spawn_every(
243243
})
244244
}
245245

246-
pub async fn sleep(_: Lua, dur: Duration) -> Result<()> {
246+
pub async fn sleep(_: Lua, dur: LuaDuration) -> Result<()> {
247247
tokio::time::sleep(dur.0).await;
248248
Ok(())
249249
}

0 commit comments

Comments
 (0)