Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

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#

server/test/app/Samples.roc, in part
## 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#

server/test/app/Samples.roc, in part
## 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.

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.