module std.kv
std.kv — the transactional key-value store of a node (§12.8, D-4410..D-4419).
A Kv is a named store: Kv.open("sessions") keeps its data under <data-dir>/kv-sessions (the LSM of the node; in a cluster the
store is replicated shard by shard by Raft and reads go through the shard leader, so they are linearizable). Keys are str,
values bytes. Every key has a version (0 = absent) that grows with each write: it is the base of compare-and-set and of
transactions.
let kv = Kv.open("sessions")!
kv.put("user/{7}/name", Utf8.encode("ann"))!
let name = kv.get("user/{7}/name") // bytes?
let moved = kv.txn(tx => { // optimistic: retried when a key it read changed
let n = tx.get("user/{7}/visits")
tx.put("user/{7}/visits", next(n))
})!
for await ev in kv.watch("user/{7}/") { … } // events from now onA batch or transaction must stay on one shard: the keys' hash decides it, or only the text inside the first {…} when the key
has one (user/{7}/name and user/{7}/cart live together). Keys on two shards are CrossShardTx (2PC is 1.0).
Runtime: runtime/src/shard/kv_api.cpp over the shard state machine runtime/src/shard/kv_shard.cpp.
Example:
use std.kv { Kv }
fn main() io, db {
let kv = Kv.open("docs-module-kv")!
kv.put("user/1", b"ann")!
let found = kv.scan("user/", 10)!
print("{found.len()} {found[0].key}")
kv.close()
}1 user/1
Types
enum Consistency | Which replica a read of a clustered store is served from (§12.4, D-8220..D-8229). |
data Kv | Handle of an open store. |
data KvEntry | A key with its value and version. |
data KvError | A store operation failed |
enum KvErrorKind | Why a store operation failed. |
data KvEvent | A change seen by watch |
data KvTx | The view of the store inside Kv.txn. |
Functions
replicaReads | How many reads this process has served from a replica instead of the leader (diagnostics; Follower and Stale reads of a clustered store on a node that holds a replica of the shard). |