Scala etcd client with etcd4s and cats-effects

Happy devOps

(λx.x)eranga
Effectz.AI
2 min readJan 13, 2020

--

Backgroud

etcd4s is scala etcd client library. It support etcd-v3 API with grpc, scalapb and akka-streams. In this post I’m gonna build etcd client application with using etcd4s and cast-effects IO monad stack. All the source codes which related to this post available in gitlab. Please clone the repo and continue the post.

Run etcd

First I need to run etcd key value pair storage. I have run etcd with docker. Following is way to run etcd.

Sbt dependency

I have used IntelliJ Idea as my IDE to work with Scala applications. I need to create sbt project and add the build.sbt dependency file with etcd4s, cats-effects and other dependencies. Following is the build.sbt dependency file.

Load config

I have used cats-effects IO monads to build this application. To load etcd the configurations with IO monads I have used circe-config library. Following is the way to parse configurations into cats-effects IO.

Etcd repository

I have used etcd to store microservice health statuses. etcd keys which corresponds to services starting with services/ prefix and follow services/<service-name> format. Assume I need to create a service named octopus with health status running. When creating this service, it will add services/octopus: running key/value pair in etcd storage.

I have created EtcdRepo with createService, updateService, getService , getServices and deleteService functions. createService add a new service status in etcd. updateService updates the existing service status in etcd. getService returns the services status in etcd. getServices returns all service statuses in etcd. deleteService delete service status in etcd.

EtcdRepoImpl is the cats-effects based implementation of EtcdRepo. etcd4s library provides Future based API to deal with etcd storage. All the functions in EtcdRepoImpl wraps with IO.fromFuture to handle the Future API calls.

Execute functions

Finally I have run the functions on etcdRepo, which wraps with IO monad. To unwrap and run the side-effecting code in the IO monad I need to invoke unsafeRunSync(). Following are the different functions that I have run and their outputs.

Inside etcd

We can view the values stored in etcd by using etcdctl command line client. In this example I have used etcd-v3 API. Following is the way to interact with etcd-v3 API by using etcdctl.

Reference

  1. https://typelevel.org/cats-effect/
  2. https://github.com/mingchuno/etcd4s
  3. https://medium.com/rahasak/toggl4s-feature-toggle-service-with-etcd-backend-77e146e0fc32
  4. https://coreos.com/blog/running-etcd-in-containers.html
  5. https://www.compose.com/articles/java-etcd-and-the-alternative-to-jetcd-etcd-java/
  6. https://github.com/maciej/etcd-client
  7. https://etcd.io/docs/v3.4.0/dev-guide/interacting_v3/
  8. https://github.com/etcd-io/etcd/tree/master/etcdctl

--

--