The platform · Kv
Values in memory, by key
Kv keeps values by key in the server's memory, for as long as you say or until the server stops. Nothing goes to disk: a restart forgets everything. Use it for what is cheap to lose and read on many requests: rate-limit counts, a cache, a one-time token. A value is any type JSON can encode, read back as the type its reader asks for.
Counting: a rate limit#
## Five sign-in tries a minute from each address: the count is the store's, a window a minute
## long from the first try.
may_try! : Str => Bool
may_try! = |address| {
tries = Kv.increment!("login:${address}", 1, { ttl_ms: 60_000 }) ?? 0
tries <= 5
}Kv.increment! counts atomically: two requests at once both count. A counter's time to live starts when it is made and later increments don't move it, so it counts in windows: here, one minute from an address's first try.
Once: a sign-in's state#
## A sign-in with another site begins: a random state it will send back, kept ten minutes.
begin_sign_in! : {} => Str
begin_sign_in! = |{}| {
state = Base64.url_encode(Random.bytes!(16))
Kv.set!("oauth:${state}", Time.now_millis!({}), { ttl_ms: 600_000 })
state
}
## The state comes back: good once, within ten minutes. A second use finds nothing.
finish_sign_in! : Str => Try({}, [UnknownState])
finish_sign_in! = |state| {
started : Try(U64, [NotFound, BadValue(Str)])
started = Kv.take!("oauth:${state}")
match started {
Ok(_) => Ok({})
Err(_) => Err(UnknownState)
}
}Kv.take! returns a value and forgets it in one step. The state another site sends back completes one sign-in; a second use finds nothing. Of two requests taking one key at once, one gets the value, the other NotFound.
The operations#
Every operation is atomic. Each that keeps a value takes a time to live, { ttl_ms }; 0, the default, keeps it until the server stops.
Kv.set!(key, value, { ttl_ms })keeps a value, replacing what was there.Kv.get!(key)reads it:NotFoundif missing or expired,BadValue(why)if it isn't the type asked for.Kv.delete!(key)forgets it.Kv.increment!(key, by, opts)adds to an integer (from 0) and returns the new value: counts and rate limits.Kv.add!(key, value, opts)keeps a value only if the key is empty, else answersExists. Of two requests adding one key, one wins: a claim, or a request seen once (an idempotency key).Kv.take!(key)reads a value and forgets it: a one-time token.Kv.update!(key, start, change, opts)changes a value from its old one (a tally, a list of overrides): read (startwhen there is none), changed, and swapped back only if nothing changed it meanwhile, else read and changed again, so concurrent updates never lose one. Writers that keep colliding spread out (a random wait of up to 4 ms after three lost tries), so none is starved; after a thousand it answersBusy.Kv.swap!(key, was, value, opts), the stepupdate!is made of, replaces a value only if it is stillwas, else answersChanged.Kv.push!(key, value, { keep })puts a value at the front of a capped list, keeping its newestkeep;Kv.list!(key)reads it, newest first.
The store holds 64 MiB (--kv-max-mb, or KV_MAX_MB); past that, the least recently used values go, so a cache can't grow without end. By convention, a key starts with its owner (login:…, email:mailbox), so a package's keys never meet an app's. An app runs as one server, so there is one store, with no network between it and your code.
What must survive a restart belongs in a table (the database) or an actor. Every kind of state, side by side: which to use.