diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fa330eb --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +target +.sbtopts +project/.sbt +.idea +activemq-data diff --git a/.scalafmt.conf b/.scalafmt.conf new file mode 100644 index 0000000..bb1c30b --- /dev/null +++ b/.scalafmt.conf @@ -0,0 +1,14 @@ +maxColumn = 120 +align = most +continuationIndent.defnSite = 2 +assumeStandardLibraryStripMargin = true +docstrings = JavaDoc +lineEndings = preserve +includeCurlyBraceInSelectChains = false +danglingParentheses = true +spaces { + inImportCurlyBraces = true +} +optIn.annotationNewlines = true + +rewrite.rules = [SortImports, RedundantBraces] \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a800b25 --- /dev/null +++ b/README.md @@ -0,0 +1,95 @@ +ZIO-JMS +=== + +ZIO-JMS adapts JMS API to ZIO streams and makes it working more conveniently and seamlessly integrates ZIO + +--- + +For receiving messages it needs to create a message consumer using utility methods in JmsConsumer object + +```scala +import zio.{ZIO, Has, Chunk} +import zio.blocking._ +import javax.jms.{Connection, Message, JMSException} +import com.gh.dobrynya.zio.jms._ + +val received: ZIO[Has[Connection] with Blocking, JMSException, Chunk[Message]] = + JmsConsumer.consume(Queue("test-queue")) + .take(5) + .collect(onlyText) + .runCollect +``` + +You can process a stream of messages transactionally like follows + +```scala +import zio.{ZIO, Has, Chunk, UIO} +import zio.blocking._ +import javax.jms.{Connection, Message, JMSException} +import com.gh.dobrynya.zio.jms._ + +def messageProcessor(message: Message): UIO[Unit] = ??? + +val received: ZIO[Has[Connection] with Blocking, JMSException, Unit] = + JmsConsumer.consumeTx(Queue("test-queue")) + .take(5) + .tap(transactionalMessage => messageProcessor(transactionalMessage.message) <* transactionalMessage.commit) + .runDrain +``` + +Another ability to process input messages without using ZIO streams is more concise + +```scala +import zio.{ZIO, Has} +import zio.blocking._ +import zio.console._ +import javax.jms.{Connection, Message, JMSException} +import com.gh.dobrynya.zio.jms._ + +def someMessageProcessor(message: Message): ZIO[Console, Exception, Unit] = + putStrLn(s"Received message $message") + +val processing: ZIO[Console with Blocking with Has[Connection]] = + JmsConsumer.consumeWith(Topic("test-topic"), someMessageProcessor) +``` + +In case of possible failures during processing a message I recommend using a transactional consumer which commits a message +when it is processed successfully and rolls back when it fails + +```scala +import zio.{ZIO, IO, Has} +import zio.blocking._ +import javax.jms.{Connection, Message, JMSException} +import com.gh.dobrynya.zio.jms._ + +def someMessageProcessor(message: Message): IO[String, Unit] = + IO.fail(s"Error occurred during processing a message $message") + +val processing: ZIO[Blocking with Has[Connection], Any, Unit] = + JmsConsumer.consumeTxWith(Topic("test-topic"), someMessageProcessor) +``` + +For sending messages it needs to create sinks providing a destination and a message encoder as follows + +```scala +import zio.stream.ZStream +import com.gh.dobrynya.zio.jms._ + +val messages = (1 to 100).map(i => s"Message $i") + +ZStream.fromIterable(messages).run(JmsProducer.sink(Queue("test-queue"), textMessageEncoder)) +``` + +The last thing is to provide a connection like follows + +```scala +import zio.{ZLayer, Has} +import zio.blocking._ +import javax.jms.{ConnectionFactory, Connection, JMSException} +import com.gh.dobrynya.zio.jms.connection + +def connectionFactory: ConnectionFactory = ??? + +val connection: ZLayer[Blocking, JMSException, Blocking with Has[Connection]] = + ZLayer.fromManaged(connection(connectionFactory)).passthrough +``` \ No newline at end of file diff --git a/build.sbt b/build.sbt new file mode 100644 index 0000000..bb061fe --- /dev/null +++ b/build.sbt @@ -0,0 +1,17 @@ +name := "zio-jms" +version := "0.1" +scalaVersion := "2.13.2" + +libraryDependencies ++= Seq( + "dev.zio" %% "zio" % "1.0.0-RC21", + "dev.zio" %% "zio-streams" % "1.0.0-RC21", + "dev.zio" %% "zio-test" % "1.0.0-RC21" % Test, + "dev.zio" %% "zio-test-sbt" % "1.0.0-RC21" % Test, + "dev.zio" %% "zio-test-junit" % "1.0.0-RC21" % Test, + "org.apache.geronimo.specs" % "geronimo-jms_1.1_spec" % "1.1", + "org.apache.activemq" % "activemq-broker" % "5.15.12" % Test, + "org.apache.activemq" % "activemq-kahadb-store" % "5.15.12" % Test, + "ch.qos.logback" % "logback-classic" % "[1.2,)" % Test +) + +testFrameworks += new TestFramework("zio.test.sbt.ZTestFramework") diff --git a/project/build.properties b/project/build.properties new file mode 100644 index 0000000..95cca09 --- /dev/null +++ b/project/build.properties @@ -0,0 +1 @@ +sbt.version = 1.3.12 \ No newline at end of file diff --git a/project/plugin.sbt b/project/plugin.sbt new file mode 100644 index 0000000..edbf6b7 --- /dev/null +++ b/project/plugin.sbt @@ -0,0 +1 @@ +addSbtPlugin("com.geirsson" % "sbt-scalafmt" % "1.6.0-RC4") diff --git a/src/main/scala/com/gh/dobrynya/zio/jms/JmsConsumer.scala b/src/main/scala/com/gh/dobrynya/zio/jms/JmsConsumer.scala new file mode 100644 index 0000000..5304473 --- /dev/null +++ b/src/main/scala/com/gh/dobrynya/zio/jms/JmsConsumer.scala @@ -0,0 +1,81 @@ +package com.gh.dobrynya.zio.jms + +import javax.jms.{JMSException, Message, MessageConsumer, Session, Connection => JMSConnection} +import zio._ +import zio.blocking._ +import zio.stream.ZStream + +class JmsConsumer[T](session: Session, consumer: MessageConsumer) { + + /** + * Consumes the specified destination and emits received message with this consumer to provide helpful operations. + * @return a stream of received messages and a session to commit/rollback messages when working transactionally + */ + def consume(enrich: (Message, JmsConsumer[T]) => T): ZStream[Blocking, JMSException, T] = + ZStream.repeatEffect(effectBlockingInterrupt(enrich(consumer.receive(), this)).refineToOrDie) + + def commit: IO[JMSException, Unit] = + Task(session.commit()).refineToOrDie + + def rollback: IO[JMSException, Unit] = + Task(session.rollback()).refineToOrDie +} + +class TransactionalMessage(val message: Message, consumer: JmsConsumer[TransactionalMessage]) { + def commit: IO[JMSException, Unit] = consumer.commit + def rollback: IO[JMSException, Unit] = consumer.rollback +} + +object JmsConsumer { + + def consume(destination: DestinationFactory, + acknowledgementMode: Int = Session.AUTO_ACKNOWLEDGE): ZStream[BlockingConnection, JMSException, Message] = + ZStream + .managed(make[Message](destination, transacted = false, acknowledgementMode)) + .flatMap(_.consume((m, _) => m)) + + def make[A](destination: DestinationFactory, + transacted: Boolean, + acknowledgementMode: Int): ZManaged[BlockingConnection, JMSException, JmsConsumer[A]] = + for { + connection <- ZIO.service[JMSConnection].toManaged_ + session <- session(connection, transacted, acknowledgementMode) + mc <- consumer(session, destination(session)) + } yield new JmsConsumer(session, mc) + + def consumeTx(destination: DestinationFactory): ZStream[BlockingConnection, JMSException, TransactionalMessage] = + ZStream + .managed(make[TransactionalMessage](destination, transacted = true, Session.SESSION_TRANSACTED)) + .flatMap(_.consume(new TransactionalMessage(_, _))) + + def consumeWith[R, E >: JMSException]( + destination: DestinationFactory, + processor: Message => ZIO[R, E, Any], + acknowledgementMode: Int = Session.AUTO_ACKNOWLEDGE + ): ZIO[R with BlockingConnection, E, Unit] = + make[Message](destination, transacted = false, acknowledgementMode) + .use(_.consume((m, _) => m).foreach(processor).unit) + + /** + * Consumes the specified destination and provides the processor with received message. + * Automatically commits successfully processed messages or rollbacks a message in case of failure. + * @param destination consume from + * @param processor a function to proceed with a message + * @tparam R specifies dependencies + * @tparam E specifies possible error type + * @return unit + */ + def consumeTxWith[R, E >: JMSException]( + destination: DestinationFactory, + processor: Message => ZIO[R, E, Any], + ): ZIO[R with BlockingConnection, E, Unit] = + make[TransactionalMessage](destination, transacted = true, Session.AUTO_ACKNOWLEDGE) + .use( + _.consume(new TransactionalMessage(_, _)) + .foreach { tm => + processor(tm.message) + .tapBoth(_ => tm.rollback, _ => tm.commit) + } + .unit + ) +} diff --git a/src/main/scala/com/gh/dobrynya/zio/jms/JmsProducer.scala b/src/main/scala/com/gh/dobrynya/zio/jms/JmsProducer.scala new file mode 100644 index 0000000..ff39fc4 --- /dev/null +++ b/src/main/scala/com/gh/dobrynya/zio/jms/JmsProducer.scala @@ -0,0 +1,66 @@ +package com.gh.dobrynya.zio.jms + +import javax.jms.{Destination, JMSException, Message, Session, Connection => JMSConnection} +import zio._ +import zio.stream.ZSink + +class JmsProducer[R, E >: JMSException, A](session: Session, sender: A => ZIO[R, E, Message]) { + def produce(message: A): ZIO[R, E, (A, Message)] = sender(message).map(message -> _) + def commit: IO[JMSException, Unit] = Task(session.commit()).refineToOrDie + def rollback: IO[JMSException, Unit] = Task(session.rollback()).refineToOrDie +} + +object JmsProducer { + def sink[R, E >: JMSException, A]( + destination: DestinationFactory, + encoder: (A, Session) => ZIO[R, E, Message], + transacted: Boolean = false, + acknowledgementMode: Int = Session.AUTO_ACKNOWLEDGE + ): ZSink[R with BlockingConnection, E, A, A, Unit] = + ZSink.managed[R with BlockingConnection, E, A, JmsProducer[R, E, A], A, Unit]( + make(destination, encoder, transacted, acknowledgementMode) + ) { jmsProducer => + ZSink.foreach(jmsProducer.produce) + } + + def make[R, E >: JMSException, A]( + destination: DestinationFactory, + encoder: (A, Session) => ZIO[R, E, Message], + transacted: Boolean = false, + acknowledgementMode: Int = Session.AUTO_ACKNOWLEDGE + ): ZManaged[R with BlockingConnection, JMSException, JmsProducer[R, E, A]] = + for { + connection <- ZIO.service[JMSConnection].toManaged_ + session <- session(connection, transacted, acknowledgementMode) + d <- Task(destination(session)).refineToOrDie.toManaged_ + mp <- producer(session) + } yield + new JmsProducer[R, E, A](session, + message => + encoder(message, session).map { encoded => + mp.send(d, encoded) + encoded + }) + + def routerSink[R, E >: JMSException, A]( + encoderAndRouter: (A, Session) => ZIO[R, E, (Destination, Message)], + transacted: Boolean = false, + acknowledgementMode: Int = Session.AUTO_ACKNOWLEDGE + ): ZSink[R with BlockingConnection, E, A, A, Unit] = + ZSink.managed[R with BlockingConnection, E, A, JmsProducer[R, E, A], A, Unit]( + for { + connection <- ZIO.service[JMSConnection].toManaged_ + session <- session(connection, transacted, acknowledgementMode) + mp <- producer(session) + } yield + new JmsProducer[R, E, A](session, + message => + encoderAndRouter(message, session).map { + case (d, encoded) => + mp.send(d, encoded) + encoded + }) + ) { jmsProducer => + ZSink.foreach(jmsProducer.produce) + } +} diff --git a/src/main/scala/com/gh/dobrynya/zio/jms/destinations.scala b/src/main/scala/com/gh/dobrynya/zio/jms/destinations.scala new file mode 100644 index 0000000..119970c --- /dev/null +++ b/src/main/scala/com/gh/dobrynya/zio/jms/destinations.scala @@ -0,0 +1,19 @@ +package com.gh.dobrynya.zio.jms + +import javax.jms._ + +case class Queue(name: String) extends DestinationFactory { + override def apply(session: Session): Destination = session.createQueue(name) +} + +case class Topic(name: String) extends DestinationFactory { + override def apply(session: Session): Destination = session.createTopic(name) +} + +case object TemporaryQueue extends DestinationFactory { + override def apply(session: Session): Destination = session.createTemporaryQueue() +} + +case object TemporaryTopic extends DestinationFactory { + override def apply(session: Session): Destination = session.createTemporaryQueue() +} diff --git a/src/main/scala/com/gh/dobrynya/zio/jms/package.scala b/src/main/scala/com/gh/dobrynya/zio/jms/package.scala new file mode 100644 index 0000000..5178386 --- /dev/null +++ b/src/main/scala/com/gh/dobrynya/zio/jms/package.scala @@ -0,0 +1,53 @@ +package com.gh.dobrynya.zio + +import javax.jms._ +import zio._ +import zio.blocking._ + +package object jms { + + type DestinationFactory = Session => Destination + type MessageFactory[T] = (T, Session) => Message + type BlockingConnection = Blocking with Has[Connection] + + def connection(connectionFactory: ConnectionFactory, + credentials: Option[(String, String)] = None): ZManaged[Blocking, JMSException, Connection] = + Managed.make { + effectBlockingInterrupt { + val connection = credentials + .map(creds => connectionFactory.createConnection(creds._1, creds._2)) + .getOrElse(connectionFactory.createConnection()) + connection.start() + connection + } + }(c => Task(c.close()).ignore).refineToOrDie + + def textMessageEncoder: (String, Session) => IO[JMSException, TextMessage] = + (text: String, session: Session) => Task(session.createTextMessage(text)).refineToOrDie + + def onlyText: PartialFunction[Message, String] = { + case text: TextMessage => text.getText + } + + def acknowledge(message: Message): ZIO[Blocking, JMSException, Message] = + effectBlockingInterrupt { + message.acknowledge() + message + }.refineToOrDie + + private[jms] def session(connection: Connection, + transacted: Boolean, + acknowledgeMode: Int): ZManaged[Blocking, JMSException, Session] = + Managed + .make(effectBlockingInterrupt(connection.createSession(transacted, acknowledgeMode)))( + s => Task(s.close()).ignore + ) + .refineToOrDie + + private[jms] def producer(session: Session): ZManaged[Blocking, JMSException, MessageProducer] = + Managed.make(effectBlockingInterrupt(session.createProducer(null)).refineToOrDie)(p => UIO(p.close())) + + private[jms] def consumer(session: Session, + destination: Destination): ZManaged[Blocking, JMSException, MessageConsumer] = + Managed.make(effectBlockingInterrupt(session.createConsumer(destination)).refineToOrDie)(c => UIO(c.close())) +} diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml new file mode 100644 index 0000000..18cd1fa --- /dev/null +++ b/src/test/resources/logback-test.xml @@ -0,0 +1,14 @@ + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + \ No newline at end of file diff --git a/src/test/scala/com/gh/dobrynya/zio/jms/ConnectionAware.scala b/src/test/scala/com/gh/dobrynya/zio/jms/ConnectionAware.scala new file mode 100644 index 0000000..e540fdb --- /dev/null +++ b/src/test/scala/com/gh/dobrynya/zio/jms/ConnectionAware.scala @@ -0,0 +1,23 @@ +package com.gh.dobrynya.zio.jms + +import javax.jms.{Connection, JMSException} +import org.apache.activemq.broker.BrokerService +import org.apache.activemq.ActiveMQConnectionFactory +import zio._ +import zio.blocking.Blocking + +trait ConnectionAware { + val connectionFactory = new ActiveMQConnectionFactory("vm://localhost") + val managedConnection: ZManaged[Blocking, JMSException, Connection] = connection(connectionFactory) + + val brokerService: IO[Any, BrokerService] = Task { + val brokerService = new BrokerService() + brokerService.setUseJmx(true) + brokerService.setPersistent(false) + brokerService.setUseShutdownHook(true) + brokerService.start() + brokerService + } + + val stopBroker: BrokerService => UIO[Unit] = (brokerService: BrokerService) => UIO(brokerService.stop()) +} diff --git a/src/test/scala/com/gh/dobrynya/zio/jms/JmsComponentsSpec.scala b/src/test/scala/com/gh/dobrynya/zio/jms/JmsComponentsSpec.scala new file mode 100644 index 0000000..234ea2c --- /dev/null +++ b/src/test/scala/com/gh/dobrynya/zio/jms/JmsComponentsSpec.scala @@ -0,0 +1,158 @@ +package com.gh.dobrynya.zio.jms + +import javax.jms.{ Queue => _, _ } +import zio.{ Queue => ZQueue, _ } +import zio.blocking.Blocking +import zio.console._ +import zio.duration._ +import zio.random._ +import zio.stream._ +import zio.test._ +import zio.test.Assertion._ +import zio.test.TestAspect._ + +object JmsComponentsSpec extends DefaultRunnableSpec with ConnectionAware { + val connectionLayer: ZLayer[Blocking, JMSException, Blocking with Has[Connection]] = + ZLayer.fromManaged(managedConnection).passthrough + + def spec: ZSpec[environment.TestEnvironment, Any] = + suite("JMS components")( + testM("All sent messages should be received with auto acknowledgements") { + val dest = Queue("JmsComponentsSpec-1") + + checkM(Gen.listOf(Gen.alphaNumericString)) { messages => + (for { + _ <- send(messages, dest) + received <- JmsConsumer + .consume(dest) + .take(messages.size) + .collect(onlyText) + .runCollect + } yield assert(received.toList)(equalTo(messages))) + .provideSomeLayer[Blocking with Console](connectionLayer) + } + }, + testM("Not committed messages should arrive twice") { + val dest = Queue("JmsComponentsSpec-2") + + checkM(Gen.listOf(Gen.alphaNumericString)) { messages => + (for { + _ <- send(messages, dest) + received <- ZIO.foreach(1 to 2)( + i => + JmsConsumer + .consumeTx(dest) + .take(messages.size) + .tap(_.commit.when(i == 2)) + .map(_.message) + .collect(onlyText) + .runCollect + ) + } yield assert(received.flatten)(equalTo(messages ++ messages))) + .provideSomeLayer[Blocking with Console](connectionLayer) + } + }, + testM("Not acknowledged messages should arrive twice") { + val dest = Queue("JmsComponentsSpec-3") + + checkM(Gen.listOf(Gen.alphaNumericString)) { messages => + (for { + _ <- send(messages, dest) + received <- ZIO.foreach(1 to 2)( + i => + JmsConsumer + .consume(dest, Session.CLIENT_ACKNOWLEDGE) + .take(messages.size) + .tap(acknowledge(_).when(i == 2)) + .collect(onlyText) + .runCollect + ) + } yield assert(received.flatten)(equalTo(messages ++ messages))) + .provideSomeLayer[Blocking with Console](connectionLayer) + } + }, + testM("Processor should collect all sent messages") { + val dest = Queue("JmsComponentsSpec-4") + + checkM(Gen.listOf(Gen.alphaNumericString)) { messages => + (for { + _ <- send(messages, dest) + collector <- ZQueue.unbounded[String] + _ <- JmsConsumer.consumeWith(dest, message => collector.offer(onlyText(message))).fork + received <- ZStream.fromQueue(collector).take(messages.size).runCollect + } yield assert(received.toList)(equalTo(messages))) + .provideSomeLayer[Console with Blocking](connectionLayer) + } + }, + testM("Failing processor should not lose any message") { + val dest = Queue("JmsComponentsSpec-5") + + checkM(Gen.listOf(Gen.alphaNumericString).filter(_.nonEmpty)) { + messages => + ( + for { + _ <- send(messages, dest) + collector <- ZQueue.unbounded[String] + _ <- JmsConsumer + .consumeTxWith(dest, message => ZIO.fail(s"Some processing error: ${onlyText(message)}!")) + .ignore + _ <- JmsConsumer + .consumeTxWith(dest, message => collector.offer(onlyText(message))) + .fork + received <- ZStream.fromQueue(collector).take(messages.size).runCollect.map(_.toList) + } yield assert(received)(equalTo(messages)) + ).provideSomeLayer[Blocking with Console with Random](connectionLayer) + } + }, + testM("Client requires a response to be sent to a dedicated queue via JMSReplyTo header") { + val source = Queue("JmsComponentsSpec-6") + val replyQueue = Queue("JmsComponentsSpec-7") + + val messages = List("1", "2", "3") + + val produceWithReplyTo = (for { + jmsProducer <- JmsProducer.make( + source, + (message: String, session: Session) => + Task { + val replyTo = replyQueue(session) + val msg = session.createTextMessage(message) + msg.setJMSReplyTo(replyTo) + msg.setJMSCorrelationID(message) + msg + }.refineToOrDie + ) + } yield jmsProducer).use( + p => + ZStream + .fromIterable(messages) + .foreach(p.produce) + ) + + (for { + _ <- produceWithReplyTo + _ <- JmsConsumer + .consume(source) + .tap(s => putStrLn(s"Received request $s")) + .take(messages.size) + .map(m => onlyText(m) -> m.getJMSReplyTo) + .run( + JmsProducer.routerSink( + (message, session) => + textMessageEncoder(message._1.toUpperCase, session) + .tap(m => UIO(m.setJMSCorrelationID(message._1))) + .map(message._2 -> _) + .tap(p => putStrLn(s"Responding to ${p._1}")) + ) + ) + received <- JmsConsumer.consume(replyQueue).take(messages.size).collect(onlyText).runCollect + } yield assert(received.toList)(equalTo(messages))) + .provideSomeLayer[Console with Blocking](connectionLayer) + } + ) @@ timeout(3.minute) @@ timed @@ sequential @@ around(brokerService)(stopBroker) + + private def send(messages: List[String], destination: DestinationFactory) = + ZStream + .fromIterable(messages) + .run(JmsProducer.sink(destination, textMessageEncoder)) +} diff --git a/src/test/scala/com/gh/dobrynya/zio/jms/JmsSpec.scala b/src/test/scala/com/gh/dobrynya/zio/jms/JmsSpec.scala new file mode 100644 index 0000000..778027f --- /dev/null +++ b/src/test/scala/com/gh/dobrynya/zio/jms/JmsSpec.scala @@ -0,0 +1,97 @@ +package com.gh.dobrynya.zio.jms + +import javax.jms.{Queue => _, _} +import zio.{Queue => _, _} +import zio.blocking.Blocking +import zio.duration._ +import zio.test._ +import zio.test.Assertion._ +import zio.test.TestAspect._ +import zio.test.environment._ + +object JmsSpec extends DefaultRunnableSpec with ConnectionAware { + def spec: ZSpec[TestEnvironment, Any] = + suite("JMS")( + testM("Messages should be sent and received in order of sending") { + checkM(Gen.listOf(Gen.anyString)) { messages => + val received = jmsObjects("JmsSpec-1").use { + case (s, p, mc, d) => + ZIO.foreach(messages)(send(p, s, d, _)) *> ZIO.foreach(1 to messages.size)(_ => receiveText(mc)) + } + assertM(received)(equalTo(messages)) + } + }, + testM("Transactional producer should send messages transactionally") { + checkM(Gen.anyString) { + message => + val received: ZIO[Blocking, Throwable, List[String]] = + jmsObjects("JmsSpec-2", transacted = true, Session.SESSION_TRANSACTED).use { + case (s, p, _, d) => + send(p, s, d, message) *> Task(s.rollback()) *> send(p, s, d, message) *> Task(s.commit()) + } *> + jmsObjects("JmsSpec-2").use { + case (_, _, mc, _) => + ZIO.collectAll(List(receiveText(mc, Some(100)), receiveText(mc, Some(100)))) + } + assertM(received)(equalTo(List(message, null))) + } + }, + testM("Transactional consumer should rollback session and get the same message twice") { + checkM(Gen.anyString) { message => + val received: ZIO[Blocking, Throwable, List[String]] = + jmsObjects("JmsSpec-3").use { + case (s, p, _, d) => send(p, s, d, message) + } *> + ZIO.foreach(1 to 2) { i => + jmsObjects("JmsSpec-3", transacted = true, Session.SESSION_TRANSACTED).use { + case (s, _, mc, _) => receiveText(mc) <* Task(if (i == 1) s.rollback() else s.commit()) + } + } + assertM(received)(equalTo(List(message, message))) + } + }, + testM("Acknowledging consumer should get the same message twice without acknowledgement") { + checkM(Gen.anyString) { message => + val received: ZIO[Blocking, Throwable, List[String]] = + jmsObjects("JmsSpec-4").use { + case (s, p, _, d) => send(p, s, d, message) + } *> + ZIO.foreach(1 to 2) { i => + jmsObjects("JmsSpec-4", transacted = false, Session.CLIENT_ACKNOWLEDGE).use { + case (s, _, mc, _) => + receive(mc) + .tap(m => Task(if (i == 2) m.acknowledge())) + .map(onlyText orElse nullableMessage) + } + } + assertM(received)(equalTo(List(message, message))) + } + } + ) @@ around(brokerService)(stopBroker) @@ sequential @@ timeout(1.minute) @@ timed + + def receive(consumer: MessageConsumer, timeout: Option[Long] = None): ZIO[Any, JMSException, Message] = + Task(timeout.map(consumer.receive).getOrElse(consumer.receive())).refineToOrDie + + def receiveText(consumer: MessageConsumer, timeout: Option[Long] = None): ZIO[Any, JMSException, String] = + receive(consumer, timeout).map(onlyText orElse nullableMessage) + + private def send(p: MessageProducer, s: Session, d: Destination, message: String) = + Task(p.send(d, s.createTextMessage(message))) + + def jmsObjects( + dest: String, + transacted: Boolean = false, + acknowledgementMode: Int = Session.AUTO_ACKNOWLEDGE + ): ZManaged[Blocking, Throwable, (Session, MessageProducer, MessageConsumer, Destination)] = + for { + c <- managedConnection + s <- session(c, transacted, acknowledgementMode) + d = Queue(dest)(s) + p <- producer(s) + mc <- consumer(s, d) + } yield (s, p, mc, d) + + def nullableMessage[T <: AnyRef]: PartialFunction[Message, T] = { + case null => null.asInstanceOf[T] + } +}