Skip to content
davils-comPublic

About

The etcd v3 client of Davils: KV, transactions, watches, leases, auth and cluster administration with coroutines and builders, locks, elections, STM and mirrors on top, a write never sent twice and an etcd in memory for tests, for Kotlin on the JVM.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

65 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Kvant

Kvant is the etcd v3 client of Davils: a Kotlin client for the JVM with coroutines, flows and builders, made for production and for critical systems. It never sends a write twice, checks every answer of etcd before it trusts it, keeps secrets out of every message and comes with coordination recipes, a mirror and an etcd in memory for tests. It is built on Kore and published under the Apache License 2.0.

Module Artifact What it holds
kvant-core com.davils:kvant-core The client: KV, transactions, watches, leases, cluster, maintenance, auth and namespaces, with endpoint balancing and discovery, TLS, retries and telemetry
kvant-concurrency com.davils:kvant-concurrency Sessions, mutexes, read-write mutexes, elections, software transactional memory, barriers, double barriers and work queues
kvant-sync com.davils:kvant-sync The mirror of a prefix and a guard against answers that go back in time
kvant-shutdown com.davils:kvant-shutdown Optional: sessions and the client in the shutdown of Knot
kvant-testing com.davils:kvant-testing An etcd in memory with faults, a test PKI and the conformance suite of etcd; keep it out of production class paths
kvant-bom com.davils:kvant-bom One version for every Kvant module

Kvant talks to etcd 3.5, 3.6 and 3.7 through grpc-java with its shaded Netty and a bounded protobuf codec of its own, without protobuf-java. It secures connections through Krypt, retries through Kontinuity and reports through Kollect and Konfetti; it never logs. Kvant is written for Kotlin 2.4 or newer and requires JDK 25.

Installation

Kvant is published to the Davils repository, not to Maven Central. Declare it for the com.davils group only:

// settings.gradle.kts
dependencyResolutionManagement {
    repositories {
        exclusiveContent {
            forRepository { maven("https://repo.davils.com/releases") }
            filter { includeGroupAndSubgroups("com.davils") }
        }
        mavenCentral()
    }
}
// build.gradle.kts
dependencies {
    implementation(platform("com.davils:kvant-bom:1.2.1"))
    implementation("com.davils:kvant-core")
    implementation("com.davils:kvant-concurrency")
    testImplementation("com.davils:kvant-testing")
}

A client

val client = etcdClient(scope) {
    name = "billing"
    endpoints("https://etcd-0:2379", "https://etcd-1:2379", "https://etcd-2:2379")
    tls(crypto) { trust { anchors = listOf(anchor) } }
    password("billing", password)
    namespace("/apps/billing/")
    timeouts {
        call = 10.seconds
        attempt = 3.seconds
    }
    resilience { retry { maxAttempts = 5 } }
    telemetry {
        meters(registry)
        events(bus)
    }
}

The client checks its configuration as a whole and reports every violation at once. Plaintext is refused unless insecureTransport() is set, and a password or token is never sent over plaintext. Instead of fixed endpoints, discovery { dnsSrv("example.com"); memberSync { interval = 5.minutes } } finds the members through DNS SRV and keeps them in step with the cluster. shutdown() ends the client gracefully, close() at once.

Keys and transactions

client.kv.put("/config/limit".encodeToByteString(), "10".encodeToByteString())

val page = client.kv.get("/config/".encodeToByteString()) {
    prefix()
    sort(SortTarget.KEY, SortOrder.ASCEND)
    limit = 100
}

client.kv.list("/config/".encodeToByteString()) { pageSize = 500 }.collect { kv -> println(kv.key) }

val moved = client.kv.txn {
    whenever { version(key) eq 0L }
    then { put(key, value) }
    otherwise { get(key) }
}

A read that fails is retried on another member. A write is never retried once it may have reached etcd: when its outcome is unknown, it fails with EtcdFailure.OutcomeUnknown, so the caller decides. Every failure is an EtcdException with a sealed EtcdFailure; attempt { } turns a block into an Outcome instead.

A member that hangs, such as a paused or overloaded process that keeps its connections open, does not hold the client: each attempt of a read ends after timeouts.attempt and goes to another member, and the hanging member is asked last until it answers again. A write that reached a hanging member fails with EtcdFailure.OutcomeUnknown.

Watches and leases

client.watcher.watch("/config/".encodeToByteString()) {
    prefix()
    startRevision = revision + 1
}.collect { response -> response.events.forEach(::apply) }

val lease = client.leases.grant(30.seconds)
client.leases.keepAlive(lease.id).collect { ttl -> }

All watches of a client share one stream. A watch that loses its stream resumes at the next revision it has not seen, without a gap and without a duplicate, and fails with EtcdFailure.Compacted when that revision was compacted. A stream that has been silent for timeouts.streamProbe is probed with a progress request and moved to another member when its member does not answer. Keepalives move the same way. Give a lease a TTL well above the longest pause a member of the cluster may suffer plus a third of the TTL: a leader that comes back from a pause revokes a lease that expired in its own view, even when the new leader kept it alive. Reads fail with ServerError.NO_LEADER once their retries run out during an election, so let the retries cover the election timeout of the cluster.

Coordination

val session = client.session(scope) { ttl = 30.seconds }

val mutex = session.mutex("/locks/invoices")
mutex.withLock {
    client.kv.txn {
        whenever { isHeld(mutex) }
        then { put(key, value) }
    }
}

val election = session.election("/elections/scheduler")
election.campaign("node-1".encodeToByteString())
election.observe().collect { leader -> }

client.stm({ isolation = Isolation.SERIALIZABLE }) {
    val balance = get(account)
    put(account, debited(balance))
}

session.close()

The recipes follow the concurrency package of etcd. A lock is only as safe as its session: fence the work done under it with isHeld(mutex) or with mutex.revision as a fencing token.

A copy of etcd

client.mirror("/config/".encodeToByteString()) {
    isIsolated = true
    isProgressNotified = true
    historyFrom = lastSeenRevision
}.collect { event ->
    when (event) {
        is MirrorEvent.Loaded -> store(event.kv)
        is MirrorEvent.History -> remember(event.event)
        is MirrorEvent.Synced -> ready(event.revision)
        is MirrorEvent.Changed -> apply(event.event)
        is MirrorEvent.Progress -> bookmark(event.revision)
    }
}

A snapshot of more than maxKeys keys, one million by default, fails the mirror instead of being truncated.

Tests

testEtcd { members = 3 }.use { etcd ->
    etcd.client(scope).use { client ->
        etcd.faults.fail(ServerError.NO_LEADER, method = "etcdserverpb.KV/Range")
        etcd.faults.breakStreams()
        // ...
    }
}

The etcd in memory serves KV, transactions, watches, leases, auth, cluster and maintenance over the in-process transport of gRPC or over TCP and TLS, with faults for failed, corrupt and hanging answers, lost leaders, expired tokens and broken streams, and members that go down or freeze like a paused process. conformanceCases() lists the behaviours it shares with real etcd; they run against etcd 3.5, 3.6 and 3.7 in the integration tests of Kvant and can run against any etcd you want to trust.

Building

./gradlew check
./gradlew integrationTest

check needs JDK 25 and network access; integrationTest also needs a running Docker. See AGENTS.md for the rules of the code and CONTRIBUTING.md for how a change gets in. Security problems are reported as described in SECURITY.md.

About

The etcd v3 client of Davils: KV, transactions, watches, leases, auth and cluster administration with coroutines and builders, locks, elections, STM and mirrors on top, a write never sent twice and an etcd in memory for tests, for Kotlin on the JVM.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Contributors

Languages