cache4k icon indicating copy to clipboard operation
cache4k copied to clipboard

Dynamic TTL

Open caeus opened this issue 3 years ago • 5 comments

Is it possible to set the expiration time during execution of the loader?

Trying to cache some oauth tokens whose expiration time is known when the loader gets them. Not before.

caeus avatar Apr 25 '22 17:04 caeus

It is such a good and useful enhancement and it would be awesome to have it in this lib.

glockbender avatar Aug 21 '22 20:08 glockbender

we even have kotlinx.datetime which should make this simpler to impl for all platforms in commonMain only.

Shabinder avatar Apr 24 '23 02:04 Shabinder

Thanks everyone, I might take a look at this soon.

Can you share a few examples of your use cases and how you think the APIs should look like? Is this a feature you've used in other caching libraries in the past?

ychescale9 avatar Apr 24 '23 03:04 ychescale9

Example of function description:


public data class LoaderContext internal constructor(
    var expireAfterAccessDuration: Duration,
    var expireAfterWriteDuration: Duration
)

public suspend fun get(key: Key, loader: suspend LoaderContext.() -> Value): Value
// looks like it should be a new 'put' function with 'customizing'
public suspend fun put(key: Key, loader: suspend LoaderContext.() -> Value)

Example of usage:

suspend fun cacheToken(key: String, ttl: Duration): Any {
   cache.put(key) {
      // by default cache-level configured values are set
      this.expireAfterAccessDuration = ttl
      // ...
   }
}

suspend fun someFun(key: String, ttl: Duration): Any {
   cache.get(key) {
      this.expireAfterWriteDuration = ttl
      // ...
   }
}

Is this a feature you've used in other caching libraries in the past?

Using it a lot with Redis

glockbender avatar Apr 25 '23 21:04 glockbender

I'd add the feature as part of the builder:

dynamicExpireAfterWrite{ it.expires_in.seconds }

caeus avatar Feb 23 '24 20:02 caeus