From 821d5ed4bcf1611899338c9011689472f12cf194 Mon Sep 17 00:00:00 2001 From: Thibault Charbonnier Date: Tue, 30 Jan 2024 16:53:42 -0800 Subject: [PATCH] feat(mlcache) 'peek()' only returns 0 when key has indefinite ttl Any non-zero ttl now guarantees a non-zero return value for `peek()`. --- README.md | 8 ++++++-- lib/resty/mlcache.lua | 11 ++++++++++- t/03-peek.t | 8 +++----- 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 16587c20..4a09d195 100644 --- a/README.md +++ b/README.md @@ -748,8 +748,12 @@ If there is no value for the queried `key`, it returns `nil` and no error. If there is a value for the queried `key`, it returns a number indicating the remaining TTL of the cached value (in seconds) and no error. If the value for `key` has expired but is still in the L2 cache, returned TTL value will be -negative. Finally, the third returned value in that case will be the cached -value itself, for convenience. +negative. The remaining TTL return value will only be `0` if the queried `key` +has an indefinite ttl (`ttl=0`). Otherwise, this return value may be positive +(`key` still valid), or negative (`key` is stale). + +The third returned value will be the cached value as stored in the L2 cache, if +still available. This method is useful when you want to determine if a value is cached. A value stored in the L2 cache is considered cached regardless of whether or not it is diff --git a/lib/resty/mlcache.lua b/lib/resty/mlcache.lua index a5f3f734..edacfbea 100644 --- a/lib/resty/mlcache.lua +++ b/lib/resty/mlcache.lua @@ -1277,7 +1277,16 @@ function _M:peek(key, stale) "retrieval: " .. err end - local remaining_ttl = ttl - (now() - at) + local remaining_ttl = 0 + + if ttl > 0 then + remaining_ttl = ttl - (now() - at) + + if remaining_ttl == 0 then + -- guarantee a non-zero remaining_ttl if ttl is set + remaining_ttl = 0.001 + end + end return remaining_ttl, nil, value, went_stale end diff --git a/t/03-peek.t b/t/03-peek.t index f2326ea9..857e6a12 100644 --- a/t/03-peek.t +++ b/t/03-peek.t @@ -120,9 +120,7 @@ ttl: 18 -=== TEST 4: peek() returns a negative ttl when a key expired ---- main_config - timer_resolution 10ms; +=== TEST 4: peek() returns a 0 remaining_ttl if the ttl was 0 --- config location /t { content_by_lua_block { @@ -152,8 +150,8 @@ ttl: 18 } } --- response_body -ttl: -1 -ttl: -2 +ttl: 0 +ttl: 0 --- no_error_log [error] [crit]