KScript docs
EN

KScript.Cache

A cache of values by key, with time limits: in memory, or in files in the app's cache folder.

Import it at the top of a script:

<import package="KScript.Cache" />
import KScript.Cache

KScript.Cache keeps values between runs, so its examples can't run inside the docs. Copy one into a .ks.xml file and run it with kscript.

Commands

Commands are called with @, in any expression: @name(arguments).

#@cache(store?: memory|file|database, name?) → cache

A cache store: memory (the default, like $cache), file, which keeps values in files in the app's cache folder so they last between runs, or database, which keeps them in the kscript_cache table of the project's database so every server shares them. A name keeps a store's keys apart from other stores'.
ParameterTakes
store optionalone of these words: memory|file|database
name optionalany value

Arguments can be named: @cache(…, name: …).

Example
<let name="weather" value="@cache(file, name: 'weather')" />
<echo>{ $weather->remember('today', fn() => 'sunny', ttl: 1h) }</echo>
$weather = @cache(file, name: 'weather')
echo $weather->remember('today', fn() => 'sunny', ttl: 1h)

#@rate_limit(key, limit: number, per: duration, store?: cache) → rate_limit

A rate limit for anything, not just routes: at most limit attempts per key in each window of per, such as 5 password resets an hour per email. The attempts are counted in a cache store: the app's memory cache by default, or the store given (@cache(file), or a shared store when several servers must count together).
ParameterTakes
key requiredany value
limit requirednumber
per requiredduration
store optionalcache

Arguments can be named: @rate_limit(…, limit: …, per: …).

Example
<let name="limit" value="@rate_limit('reset:ann@example.com', limit: 5, per: 1h)" />
<echo>{ $limit->attempt(fn() => 'sent') } { $limit->remaining() } left</echo>
$limit = @rate_limit('reset:ann@example.com', limit: 5, per: 1h)
echo "{ $limit->attempt(fn() => 'sent') } { $limit->remaining() } left"

Methods

On cache values: ->get(), ->has(), ->set(), ->set_if_absent(), ->group(), ->clear_group(), ->remember(), ->remove(), ->pull(), ->lock(), ->increment(), ->ttl(), ->keys(), ->clear()

On rate_limit values: ->attempt(), ->hit(), ->is_limited(), ->remaining(), ->available_in(), ->clear()

Variables

VariableTypeDescription
$cachecacheThe app's cache in memory: $cache->remember('repos', fn() => @get_json($url), ttl: 10m). It lasts while kscript runs, so in kscript serve it is shared by every request. @cache(file) keeps values between runs.