Skip to content

feat: add GetOrTrySetFunc to support fallible value loading - #226

Open
AdamMagued wants to merge 1 commit into
jellydator:v3from
AdamMagued:feat-add-get-or-try-set-func
Open

AdamMagued wants to merge 1 commit into
jellydator:v3from
AdamMagued:feat-add-get-or-try-set-func

Conversation

@AdamMagued

Copy link
Copy Markdown

Summary

Adds GetOrTrySetFunc to Cache to support fallible value computation and loading without caching transient errors or partial failures.

Problem

Currently, GetOrSetFunc executes a value factory func() V and unconditionally inserts the result into the cache. When loading values that may fail (e.g., transient network or database errors), callers must either catch the error outside and manually delete the cached entry or avoid GetOrSetFunc, which can lead to race conditions or caching invalid data.

Solution

Introduces GetOrTrySetFunc(key K, fn func() (V, bool), opts ...Option[K, V]) (*Item[K, V], bool):

  • If the item is already present in the cache and not expired, it is returned with retrieved=true without executing fn.
  • If the item is missing or expired, fn is executed under the cache mutex.
  • If fn returns cancel=true, the operation is aborted: no item is inserted or overwritten in the cache, and (nil, false) is returned.
  • If fn returns cancel=false, the item is created, stored with the configured options (such as TTL), and returned with (item, false).
  • Subsequent attempts for a key that previously cancelled will re-execute the loader function.

Verification

  • Added Test_Cache_GetOrTrySetFunc covering successful set, hit without execution, cancellation on cache miss, loader re-execution after cancellation, and expired item handling.
  • Verified test suite passes: go test -v ./... and go test -race ./....

Fixes #188

Add GetOrTrySetFunc to Cache, enabling callers to atomically retrieve
or attempt to compute and set an item using a fallible loader function.
If the loader function signals cancellation (cancel=true), no item is
cached or overwritten, and (nil, false) is returned without caching
transient errors. Subsequent calls can re-execute the loader.

Fixes jellydator#188
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add support for GetOrTrySetFunc

1 participant