fs2-aws-sqs
An FS2 Streams-based API for consuming and publishing AWS SQS messages.
These docs are for the 7.x release; the older 6.x docs are here.
Import
libraryDependencies += "io.laserdisc" %% "fs2-aws-sqs" % "6.6.0"
This module provides the SQS[F] algebra:
trait SQS[F[_]] {
def sqsStream: Stream[F, Message]
def sqsStreamBatched: Stream[F, Chunk[Message]]
def changeMessageVisibilityPipe(timeout: FiniteDuration): Pipe[F, Message, Message]
def deleteMessagePipe: Pipe[F, Message, DeleteMessageResponse]
def sendMessagePipe: Pipe[F, SQS.MsgBody, SendMessageResponse]
}
Usage
To use SQS[F], you need an instance of SqsAsyncClientOp[F]:
- This is a Tagless-Final wrapper around the
SqsAsyncClient - You get this automatically as
fs2-aws-sqshas a transitive dependency onpure-sqs-tagless(see pure-aws).
The general usage pattern is as follows:
// create the tagless-final wrapper resource (pass an SqsAsyncClient.builder()
// if you need to configure credentials, region, etc.)
val sqsInterpreter = SqsInterpreter[IO].resource
// use the interpreter directly for effectful AWS SDK calls
sqsInterpreter.use { sqsOp =>
SQS.create[IO](config, sqsOp).flatMap { sqs =>
sqs.sqsStream
.. etc ..
}
}
Full Example
import cats.effect.*
import fs2.aws.sqs.{SQS, SqsConfig}
import io.laserdisc.pure.sqs.tagless.SqsInterpreter
import software.amazon.awssdk.services.sqs.model.ListQueuesResponse
import scala.concurrent.duration.*
val config = SqsConfig(
queueUrl = "https://sqs.us-east-1.amazonaws.com/123456789012/my-queue",
pollRate = 3.seconds, // default
fetchMessageCount = 10 // default; must be 1 to 10
)
object SQSExample {
// use the tagless-final wrapper directly for effectful AWS SDK calls
def basicExample: IO[ListQueuesResponse] =
SqsInterpreter[IO].resource.use { client =>
client.listQueues
}
// or make use of the streaming API for consuming and publishing messages
def fs2StreamingExample: IO[Unit] =
SqsInterpreter[IO].resource.use { sqsOp =>
SQS.create[IO](config, sqsOp).flatMap { sqs =>
for {
// publish
_ <- fs2.Stream("hello", "world")
.through(sqs.sendMessagePipe)
.compile
.drain
// consume
_ <- sqs.sqsStream
.evalTap(msg => IO.println(s"received: ${msg.body()}"))
.through(sqs.deleteMessagePipe) // acknowledge by deleting
.compile
.drain
} yield ()
}
}
}
Long polling
SQS.createWithReceiveRequest applies a function to every ReceiveMessageRequest. With long polling, each receive waits up to 20 seconds for messages, so there's no need to pause between receives:
import cats.effect.*
import fs2.aws.sqs.{SQS, SqsConfig}
import io.laserdisc.pure.sqs.tagless.SqsInterpreter
import scala.concurrent.duration.*
val longPolling: IO[Unit] =
SqsInterpreter[IO].resource.use { sqsOp =>
SQS
.createWithReceiveRequest[IO](
SqsConfig("https://sqs.us-east-1.amazonaws.com/123456789012/my-queue", pollRate = Duration.Zero),
sqsOp,
_.waitTimeSeconds(20)
)
.flatMap { sqs =>
sqs.sqsStream
.evalTap(msg => IO.println(msg.body()))
.through(sqs.deleteMessagePipe)
.compile
.drain
}
}
Notes
sqsStreampolls the queue at the configuredpollRate(default 3 seconds) and emits raw SDKMessages, fetching up tofetchMessageCountmessages per poll (default 10; must be 1 to 10). Only usepollRate = Duration.Zerowith long polling (per request, or the queue'sReceiveMessageWaitTimeSeconds); without it, the stream busy-loops on empty receives.- Besides long polling, the
createWithReceiveRequestfunction can set_.visibilityTimeout(...)per receive, or_.messageSystemAttributeNames(MessageSystemAttributeName.APPROXIMATE_RECEIVE_COUNT)to spot redeliveries. The queue URL and message count always come fromSqsConfig. - A receive hides up to
fetchMessageCountmessages at once, butsqsStreamhands them over one at a time. If handling can outlast the queue's visibility timeout, usefetchMessageCount = 1, or consumesqsStreamBatched(one chunk per receive) and extend or delete each batch as a whole. - Use
deleteMessagePipeto acknowledge messages by deleting them from the queue. changeMessageVisibilityPipe(timeout)sets each message's timeout once, rounded up to whole seconds. It isn't a heartbeat: to keep a message hidden during long processing, call it again before the timeout runs out.
Testing
The SQS algebra calls SqsAsyncClientOp[F]. The pure-sqs-tagless test jar contains
MockSqsAsyncClientOp[F], a stub where every method throws NotImplementedError until you override it.
Add the test jar as a test dependency:
libraryDependencies += "io.laserdisc" %% "pure-sqs-tagless" % "6.6.0" % "tests"
Override the calls your code makes, then build the streaming algebra on top of the stub:
import cats.effect.*
import cats.syntax.all.*
import fs2.aws.sqs.{SQS, SqsConfig}
import io.laserdisc.pure.sqs.tagless.MockSqsAsyncClientOp
import software.amazon.awssdk.services.sqs.model.{SendMessageRequest, SendMessageResponse}
import scala.concurrent.duration.*
val sqsOp = new MockSqsAsyncClientOp[IO] {
override def sendMessage(a: SendMessageRequest): IO[SendMessageResponse] =
IO.println(s"sent: ${a.messageBody()}").as(SendMessageResponse.builder().build())
}
SQS.create[IO](SqsConfig("https://sqs.us-east-1.amazonaws.com/123456789012/my-queue", pollRate = Duration.Zero), sqsOp)
.flatMap(sqs => fs2.Stream.emit("hello").covary[IO].through(sqs.sendMessagePipe).compile.drain)