Skip to content

Commit

Permalink
feat(mlcache) 'peek()' only returns 0 when key has indefinite ttl
Browse files Browse the repository at this point in the history
Any non-zero ttl now guarantees a non-zero return value for `peek()`.
  • Loading branch information
thibaultcha committed Jan 31, 2024
1 parent ab418e4 commit bec3dc9
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 8 deletions.
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

0 comments on commit bec3dc9

Please sign in to comment.