feat(get): add option replace
to cache:get options
#121
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
There is a common need to update a cached value forcibly, before its expiry. The library currently has functions like
cache:delete
andcache:set
that can either delete cached value or set the value and notify other workers about it. But there is one thing thatcache:get
has that those don't, and it is usage ofresty.lock
to prevent multiple light-threads (or workers) from trying to call the callback and retrieve the value at the same time.So while in theory you could do something like this:
This is not nice when dealing with multiple light threads, and leads you to implement extra locking there to make it atomic, something like this:
The
get
already has the locking built-in, so it would be much nicer if we could just utilize that, so the above code could just be written as:Use cases:
In both cases it would be nice if this could be abstracted with the
cache:get
as it already implements the needed locking, and we can put the code in right locations. It also simplifies the usage of this library in such cases as the locks don't need to be implemented outside, and there is potential delay betweendelete
and thecallback
so it is hard to even put things in exactly right places.cache:delete
causes async events happening, before the callback is even called, while it would be more optimal to broadcast invalidation in these cases after the callback is called (similar tocache:set
).Alternatively, it would be possible to change
cache:set
to accept callbacks, but it feels likecache:get
is a better interface as it is kinda THE interface that is used most of the time.This commit adds a
boolean
optionreplace
toopts
table ofcache:get(key, opts ...)
to allow skipping L1 and early return of non-expired L2, and make it call the callback. And it also sends invalidations after replacing the value in L2.