Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(mlcache) guarantee non-zero remaining ttl values from 'peek()' #124

Merged
merged 1 commit into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -745,8 +745,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
Expand Down
11 changes: 10 additions & 1 deletion lib/resty/mlcache.lua
Original file line number Diff line number Diff line change
Expand Up @@ -1262,7 +1262,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
Expand Down
8 changes: 3 additions & 5 deletions t/03-peek.t
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -152,8 +150,8 @@ ttl: 18
}
}
--- response_body
ttl: -1
ttl: -2
ttl: 0
ttl: 0
--- no_error_log
[error]
[crit]
Expand Down