/pulsar4s

Idiomatic, typesafe, and reactive Scala client for Apache Pulsar

Primary LanguageScalaApache License 2.0Apache-2.0

pulsar4s - Apache Pulsar Scala Client

build

pulsar4s is a concise, idiomatic, reactive, type safe Scala client for Apache Pulsar. As a simple wrapper over the Java client, we benefit from the reliability and performance of that client while providing better integration with the Scala ecosystem and idioms.

Warning!!

(This disclaimer was written on 2023-01-05.)

Starting in version 2.9.0, we support scala 3. This means we had to perform some "aggressive" bumps on libs:

Libs that were bumped for everyone:

  • play-json 2.10 (Currently in RC7)
  • cats-effect 3.3 (was 2.x)
  • ZIO 2.0 (was 1.x) & zio-cats-interop 23.0.0

Libs that come in different versions across scala versions:

  • avro4s
    • for Scala 3: 5.0+
    • for Scala 2: 4.1+
  • scala-java8-compat
    • for Scala ≥2.13: 1.0.2
    • for Scala 2.12: 0.8.0 (Was already the case before scala 3)

Check carefully that bumping pulsar4s will not break, especially with cats-effect!

Using the client

The first step is to create a client attached to the pulsar cluster, providing the service url.

val client = PulsarClient("pulsar://localhost:6650")

Alternatively, you can use an instance of PulsarClientConfig if you need to set further configuration options such as authentication, tls, timeouts and so on.

val config = PulsarClientConfig("pulsar://localhost:6650", ...)
val client = PulsarClient(config)

Then we can create either a producer or a consumer from the client. We need an implicit schema in scope - more on that later.

To create a producer, we need the topic, and an instance of ProducerConfig. We can set further options on the config object, such as max pending messages, router mode, producer name and so on.

implicit val schema: Schema[String] = Schema.STRING

val topic = Topic("persistent://sample/standalone/ns1/b")
val producerConfig = ProducerConfig(topic, ...)
val producer = client.producer[String](producerConfig)

To create a consumer, we need one or more topics to subscribe to, the subscription name, and an instance of ConsumerConfig. We can set further options on the config object, such as subscription type, consumer name, queue size and so on.

implicit val schema: Schema[String] = Schema.STRING

val topic = Topic("persistent://sample/standalone/ns1/b")
val consumerConfig = ConsumerConfig(Seq(topic), Subscription("mysub"), ...)
val consumerFn = client.consumer[String](ConsumerConfig(, )

Note: Call close() on the client, producer, and consumer once you are finished. The client and producer also implement AutoCloseable and Closeable.

Schemas

A message must be the correct type for the producer or consumer. When a producer or consumer is created, an implicit Schema typeclass must be available. In the earlier examples, you saw that we added an implicit schema for String using implicit val schema: Schema[String] = Schema.STRING.

There are built in schemas for bytes and strings, but other complex types required a custom schema. Some people prefer to write custom typeclasses manually for the types they need to support. Other people like to just have it done automagically. For those people, pulsar4s provides extensions for the well known Scala Json libraries that can be used to generate messages where the body is a JSON representation of the class.

An example of creating a producer for a complex type using the circe json library to generate the schema:

import io.circe.generic.auto._
import com.sksamuel.pulsar4s.circe._

val topic = Topic("persistent://sample/standalone/ns1/b")
val producer = client.producer[Food](ProducerConfig(topic))
producer.send(Food("pizza", "ham and pineapple"))

Note: The imports bring into scope a method that will generate an implicit schema when required.

The following extension modules can be used for automatic schemas

Library Module Import
Circe pulsar4s-circe import io.circe.generic.auto._
import com.sksamuel.pulsar4s.circe._
Jackson pulsar4s-jackson import com.sksamuel.pulsar4s.jackson._
Json4s pulsar4s-json4s import com.sksamuel.pulsar4s.json4s._
Spray Json pulsar4s-spray-json import com.sksamuel.pulsar4s.sprayjson._
Play Json pulsar4s-play-json import com.sksamuel.pulsar4s.playjson._

Producing

There are two ways to send a message - either with a plain value, or with an instance of ProducerMessage. If you do not need to specify extra options on the message - such as key, event time, headers, etc - then you can just send a plain value, and the client will wrap the value in a pulsar message. Alternatively, you can create an instance of ProducerMessage to specify extra options.

Each method can be synchronous or asynchronous. The asynchronous methods return a scala.concurrent.Future. If you are using another effect library, such as cats, scalaz or monix, then pulsar4s also supports those effects. See the section on #effects.

If the send method is successful, you will receive the MessageId of the generated message. If an exception is generated, then in the synchronous methods, you will receive a Failure with the error. In the asynchronous methods the exception will be surfaced as a failed Future.

To send a plain value, we just invoke send with the value:

producer.send("wibble")

Or to send a message, we first create an instance of ProducerMessage.

val message = DefaultProducerMessage(Some("mykey"), "wibble", eventTime = Some(EventTime(System.currentTimeMillis)))
producer.send(message)

Consuming

To receive a message, create a consumer and invoke either the receive, receive(Duration), or the receiveAsync methods. The first two are synchronous and return an instance of ConsumerMessage, blocking if necessary, and the latter is asynchronous, returning a Future (or other effect) with the ConsumerMessage once ready.

val message: Message = consumer.receive

or

val message: Future[T] = consumer.receiveAsync

Once a message has been consumed, it is important to acknowledge the message by using the message id with the ack methods.

consumer.acknowledge(message.messageId)

Akka Streams

Pulsar4s integrates with the outstanding akka-streams library - it provides both a source and a sink. To use this, you need to add a dependency on the pulsar4s-akka-streams module.

Sources

To create a source all that is required is a function that will create a consumer on demand and the message id to seek. The function must return a fresh consumer each time it is invoked. The consumer is just a regular pulsar4s Consumer and can be created in the normal way, for example.

val topic = Topic("persistent://sample/standalone/ns1/b")
val consumerFn = () => client.consumer(ConsumerConfig(topic, subscription))

We pass that function into the source method, providing the seek. Note the imports.

import com.sksamuel.pulsar4s.akka.streams._
val pulsarSource = source(consumerFn, Some(MessageId.earliest))

The materialized value of the source is an instance of Control which provides a method called 'close' which can be used to stop consuming messages. Once the akka streams source is completed (or fails) the consumer will be automatically closed.

Sinks

To create a sink, we need a producer function similar to the source's consumer function. Again, the producer used is just a regular pulsar4s Producer. The function must return a fresh producer each time it is invoked.

val topic = Topic("persistent://sample/standalone/ns1/b")
val producerFn = () => client.producer(ProducerConfig(topic))

We pass that function into the sink method. Once again, take note of the imports.

import com.sksamuel.pulsar4s.akka.streams._
val pulsarSink = sink(producerFn)

A sink requires messages of type ProducerMessage[T] where T is the value type of the message. For example, if we were producing String messages, then we would map our upstream messages into instances of ProducerMessage[String] before passing them to the sink.

import com.sksamuel.pulsar4s.akka.streams._
Source.fromIterator(() => List("a", "b", "c", "d").iterator)
  .map(string => ProducerMessage(string))
  .runWith(sink(producerFn))

A sink will run until the upstream source completes. In other words, to terminate the sink, the source must be cancelled or completed. Once the sink completes the producer will be automatically closed.

The materialized value of the sink is a Future[Done] which will be completed once the upstream source has completed.

There is also an implementation of a 'multi-sink'. Multi-sink allows to produce to multiple topics in Pulsar, while using just 1 sink. Multi-sink expects, in addition to ProducerMessage[T], a Topic, so the input format is (Topic, ProducerMessage[T]). All producers in the sink are lazily-created, once a tuple with a new topic is received. There is also a possibility to provide a collection of topics in the constructing function, to create those topics ahead of time if the names are known. New topics read from the stream will also be created on-the-fly.

Example usage of a multi-sink:

import com.sksamuel.pulsar4s.akka.streams._

val topic1 = Topic("persistent://sample/standalone/ns1/b")
val topic2 = Topic("persistent://sample/standalone/ns1/bb")
val producerFn = (topic: Topic) => client.producer(ProducerConfig(topic))
val pulsarMultiSink = multiSink(producerFn)
# or to create those topics ahead of time:
val pulsarMultiSink2 = multiSink(producerFn, Set(topic1, topic2))

Full Example

Here is a full example of consuming from a topic for 10 seconds, publising the messages back into another topic. Obviously this is a bit of a toy example but shows everything in one place.

import com.sksamuel.pulsar4s.{ConsumerConfig, MessageId, ProducerConfig, PulsarClient, Subscription, Topic}
import org.apache.pulsar.client.api.Schema

implicit val system: ActorSystem = ActorSystem()
implicit val materializer: ActorMaterializer = ActorMaterializer()
implicit val schema: Schema[Array[Byte]] = Schema.BYTES

val client = PulsarClient("pulsar://localhost:6650")

val intopic = Topic("persistent://sample/standalone/ns1/in")
val outtopic = Topic("persistent://sample/standalone/ns1/out")

val consumerFn = () => client.consumer(ConsumerConfig(Seq(intopic), Subscription("mysub")))
val producerFn = () => client.producer(ProducerConfig(outtopic))

val control = source(consumerFn, Some(MessageId.earliest))
                .map { consumerMessage => ProducerMessage(consumerMessage.data) }
                .to(sink(producerFn)).run()

Thread.sleep(10000)
control.close()

FS2 Support

Pulsar4s integrates with the fs2 library - it provides both a source and a sink. To use this, you need to add a dependency on the pulsar4s-{effect} + pulsar4s-fs2 module.

Example

import com.sksamuel.pulsar4s._
import com.sksamuel.pulsar4s.cats.CatsAsyncHandler._
import com.sksamuel.pulsar4s.fs2.Streams

import org.apache.pulsar.client.api.Schema

implicit val schema: Schema[Array[Byte]] = Schema.BYTES

val client = PulsarClient("pulsar://localhost:6650")

val intopic = Topic("persistent://sample/standalone/ns1/in")
val outtopic = Topic("persistent://sample/standalone/ns1/out")

Streams.batch[IO, Array[Byte]](client.consumerAsync[Array[Byte], IO](ConsumerConfig(
  subscriptionName = Subscription("mysub"),
  topics = Seq(intopic),
  subscriptionInitialPosition = Some(SubscriptionInitialPosition.Earliest)
)))
  .map(_.map(ProducerMessage(_.value)))
  .through(Streams.committableSink(client.producerAsync[Array[Byte], IO](ProducerConfig(outtopic))))
  .compile
  .drain

Example SBT Setup

val pulsar4sVersion = "x.x.x"
libraryDependencies ++= Seq(
  "com.clever-cloud.pulsar4s" %% "pulsar4s-core" % pulsar4sVersion,

  // for the akka-streams integration
  "com.clever-cloud.pulsar4s" %% "pulsar4s-akka-streams" % pulsar4sVersion,

  // if you want to use avro for schemas
  "com.clever-cloud.pulsar4s" %% "pulsar4s-avro" % pulsar4sVersion,

  // if you want to use circe for schemas
  "com.clever-cloud.pulsar4s" %% "pulsar4s-circe" % pulsar4sVersion,

  // if you want to use json4s for schemas
  "com.clever-cloud.pulsar4s" %% "pulsar4s-json4s" % pulsar4sVersion,

  // if you want to use jackson for schemas
  "com.clever-cloud.pulsar4s" %% "pulsar4s-jackson" % pulsar4sVersion,

  // if you want to use spray-json for schemas
  "com.clever-cloud.pulsar4s" %% "pulsar4s-spray-json" % pulsar4sVersion,

  // if you want to use play-json for schemas
  "com.clever-cloud.pulsar4s" %% "pulsar4s-play-json" % pulsar4sVersion,

  // if you want to use monix effects
  "com.clever-cloud.pulsar4s" %% "pulsar4s-monix" % pulsar4sVersion,

  // if you want to use scalaz effects
  "com.clever-cloud.pulsar4s" %% "pulsar4s-scalaz" % pulsar4sVersion,

  // if you want to use cats effects
  "com.clever-cloud.pulsar4s" %% "pulsar4s-cats-effect" % pulsar4sVersion,

  // if you want to use fs2
  "com.clever-cloud.pulsar4s" %% "pulsar4s-fs2" % pulsar4sVersion,

  // if you want to use zio
  "com.clever-cloud.pulsar4s" %% "pulsar4s-zio" % pulsar4sVersion
)

Contributions

Contributions to pulsar4s are always welcome. Good ways to contribute include:

  • Raising bugs and feature requests
  • Improving the performance of pulsar4s
  • Adding to the documentation

License

This software is licensed under the Apache 2 license, quoted below.

Copyright 2017-2018 Stephen Samuel

Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.