FS2 Kafka Vulcan

Quick Example

We start by defining the type we want to serialize or deserialize, and create a Codec.

import cats.syntax.all.*
import org.typelevel.vulcan.Codec

final case class Person(name: String, age: Option[Int])

object Person {
  given Codec[Person] =
    Codec.record(
      name = "Person",
      namespace = "com.example"
    ) { field =>
      (
        field("name", _.name),
        field("age", _.age)
      ).mapN(apply)
    }
}

We then create a SchemaRegistryClient for the schema registry.

import cats.effect.{IO, Resource}
import org.http4s.client.Client
import org.http4s.schemaregistry.{Auth, SchemaRegistryClient, SchemaRegistryClientBuilder}
import org.http4s.syntax.all.*

def schemaRegistryClient(client: Client[IO]): IO[SchemaRegistryClient[IO]] =
  SchemaRegistryClientBuilder
    .default(client, uri"http://localhost:8081")
    .withAuth(Auth.Basic("username", "password"))
    .build

We can then create a Serializer and Deserializer using AvroSerializer and AvroDeserializer.

import fs2.kafka.{ValueDeserializer, ValueSerializer}
import fs2.kafka.vulcan.{AvroDeserializer, AvroSerializer}

def personSerializer(
  client: SchemaRegistryClient[IO]
): Resource[IO, ValueSerializer[IO, Person]] =
  AvroSerializer.default(client).forValue[Person]

def personDeserializer(
  client: SchemaRegistryClient[IO]
): Resource[IO, ValueDeserializer[IO, Person]] =
  AvroDeserializer.default(client).forValue[Person]

Finally, we can create settings, passing the Serializer and Deserializer.

import fs2.kafka.{AutoOffsetReset, ConsumerSettings, Deserializer, ProducerSettings, Serializer}

def consumerSettings(
  client: SchemaRegistryClient[IO]
): ConsumerSettings[IO, String, Person] =
  ConsumerSettings(
    keyDeserializer = Deserializer[IO, String],
    valueDeserializer = personDeserializer(client)
  ).withAutoOffsetReset(AutoOffsetReset.Earliest)
    .withBootstrapServers("localhost:9092")
    .withGroupId("group")

def producerSettings(
  client: SchemaRegistryClient[IO]
): ProducerSettings[IO, String, Person] =
  ProducerSettings(
    keySerializer = Serializer[IO, String],
    valueSerializer = personSerializer(client)
  ).withBootstrapServers("localhost:9092")

The serializers and deserializers share the client, including its schema cache.